Compare commits
138 Commits
2e3b008207
...
v0.2
Author | SHA1 | Date | |
---|---|---|---|
fc92b963d4 | |||
9acbd5dccf | |||
87ebc137d5 | |||
67189f34c6 | |||
fac6ed1853 | |||
ae2097fe6a | |||
9e3d3b1dd4 | |||
4f3abb3f67 | |||
3ca6e4df3c | |||
0d81452a67 | |||
3e14498437 | |||
3102a952df | |||
3903f18854 | |||
60a91967bb | |||
c6550e81bb | |||
744fa2ec7a | |||
f8542dc96a | |||
fdae7fd065 | |||
f8d6a1a586 | |||
61fa7ca16d | |||
61a446ec2d | |||
0e5abf96c8 | |||
52b296ff01 | |||
e5e43c8bfb | |||
862168418b | |||
a6ddcef0c0 | |||
821bed6706 | |||
8f69be229b | |||
4187c3bfca | |||
1ec42e4949 | |||
1ec7a5a865 | |||
d7b93d11d8 | |||
7d9c883abd | |||
49e408be50 | |||
abc126548b | |||
86d629c957 | |||
05fad3be17 | |||
5d702c9a95 | |||
45505e4447 | |||
51ead5e171 | |||
6f11a5e662 | |||
a1be088b7a | |||
d2885af463 | |||
26930c0022 | |||
05606dd502 | |||
db029dd915 | |||
3f85f214e3 | |||
f14e2e77cd | |||
15615776d3 | |||
5ed82a7dda | |||
ae57a22078 | |||
c2bd1b526b | |||
a3666f283e | |||
edc41d6f59 | |||
145cd150b1 | |||
26c7cdbc5f | |||
aed0ca31f7 | |||
40207c3399 | |||
e715be9787 | |||
bb1e653690 | |||
4aa850d5ed | |||
11af6e530e | |||
396c619cf1 | |||
1108a138f4 | |||
b6926d510f | |||
483ea04638 | |||
aeafa9560e | |||
a82818dc43 | |||
c867652b6f | |||
f8fe21d50b | |||
1e97f8dd26 | |||
ad0fc74439 | |||
e44fb1a942 | |||
472661bff6 | |||
4aa6d43674 | |||
2591a4ccba | |||
d66e395fda | |||
0d6fb1d482 | |||
8f2e77b152 | |||
3bdcb76d8e | |||
ee18142e36 | |||
3e03fed1a2 | |||
6439adffc6 | |||
02642a147a | |||
fe29641d0a | |||
830226ae59 | |||
6a5cb69e27 | |||
b137dec434 | |||
f67a37bc21 | |||
4a492fb356 | |||
9d160ed7a0 | |||
def766ba67 | |||
0d01fa977d | |||
b229d9a68d | |||
a0ced3f7d0 | |||
a8184191b3 | |||
a132485924 | |||
9b51e00737 | |||
d2d576e617 | |||
30414e3da3 | |||
8734d56d09 | |||
08da6b4349 | |||
629c1efba5 | |||
d73674937d | |||
59aa02f0cd | |||
1536781bda | |||
57bb5c48c8 | |||
84e13e432b | |||
e8f095f821 | |||
c99827e854 | |||
4d0d9ba9c6 | |||
e3440beae7 | |||
8194476fa6 | |||
2a024a9b40 | |||
0503325c47 | |||
62d3eac498 | |||
45de97d8fb | |||
622916db04 | |||
ef3f7bc72a | |||
a349d9bfe0 | |||
1cc7053193 | |||
0af7d4a3dc | |||
be41fab5d5 | |||
c51fd3c555 | |||
715023a3ee | |||
4234967ef5 | |||
d483d05db1 | |||
564b5ddae8 | |||
d7705241ee | |||
f3fbf4a1dc | |||
56414ee5e2 | |||
478d57b342 | |||
d43c35819d | |||
3d8b086f53 | |||
294455b861 | |||
7066cc1a45 | |||
bb8906ace4 | |||
d4864d4810 |
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
.user
|
||||
.o
|
||||
*.user
|
||||
*.o
|
||||
*.a
|
||||
moc_*.cpp
|
||||
moc_*.h
|
||||
Makefile
|
||||
cli/looqs
|
||||
gui/looqs-gui
|
||||
qrc_*
|
34
CHANGELOG.md
Normal file
34
CHANGELOG.md
Normal file
@ -0,0 +1,34 @@
|
||||
# looqs: Release notes
|
||||
|
||||
## 2022-06-07 - v0.2
|
||||
CHANGES:
|
||||
- Sandboxing: Add environment variable `LOOQS_DISABLE_SANDBOXING` to disable sandboxing. This is intended for troubleshooting
|
||||
- Sandboxing: Fix issue where activation failed on kernels without landlock
|
||||
|
||||
## 2022-06-06 - v0.1
|
||||
The first release comes with basic functionality. It's a start that can be considered useful to some degree.
|
||||
|
||||
looqs is still at an early stage and may exhibit some weirdness and contain bugs.
|
||||
|
||||
Tested architectures: amd64.
|
||||
|
||||
CHANGES:
|
||||
- CLI command "looqs" to add/update/delete and search
|
||||
- GUI: "looqs-gui" to search, render previews, and add files to index
|
||||
- General: Add multi-threaded indexing of all files (paths, mtime)
|
||||
- General: Generate sqlite based full-text search index for: .pdf,.odt,.ods, text files
|
||||
- General: Sandboxed content processing
|
||||
- GUI: Sandboxed IPC sub-process to render previews.
|
||||
- GUI: Add previews for pdf: Render the page the search keywords were found. Highlight the keywords when rendering the page.
|
||||
- GUI: Add previews for plaintext files: Extract snippets. Highlight the keywords when rendering the page.
|
||||
- General: Add basic filters for query.
|
||||
- GUI: Add icon. Special thanks to the following sources:
|
||||
https://www.svgrepo.com/svg/151751/magnifier-with-small-handle
|
||||
https://www.svgrepo.com/svg/52764/open-book
|
||||
|
||||
Thanks!
|
||||
- General: Documentation.
|
||||
|
||||
- Add packages: Ubuntu 21.10, 22.04
|
||||
|
||||
Thanks to all those who provided feedback (and endured bugs) at various stages. You know who you are, thx!
|
26
CONTRIBUTING.md
Normal file
26
CONTRIBUTING.md
Normal file
@ -0,0 +1,26 @@
|
||||
# looqs - Contributing
|
||||
Contributions are welcome, please use the following guidelines.
|
||||
|
||||
## Repository
|
||||
The github repository https://github.com/quitesimpleorg/looqs is the primary one. Pull-Requests and Issues go there, but you can also submit your feedback there.
|
||||
|
||||
Those who prefer a more classical approach can mail their patches etc. to looqs at quitesimple org. Ideally git-format patch and git send-email.
|
||||
|
||||
The repository at https://gitea.quitesimple.org/crtxcr/looqs was supposed to be the main one, but these
|
||||
plans are on hold for the time being. Just ignore it.
|
||||
|
||||
## Pull-Requests & Rebasing
|
||||
Your merge requests should be submitted against the dev branch. master branch won't be rebased. I'll try to avoid in the dev branch. I definitly rebase WIP/feature branches.
|
||||
|
||||
|
||||
## Commit messages
|
||||
Commit messages begin with the component your change affects, e. g. "gui:", "cli:", "shared:", followed by the class.
|
||||
Then choose an appropriate verb in present tense. Wrong: Fixed, Fixes. Correct: Fix. Make sure lines are not too long,
|
||||
I personally go by gut feeling in this matter.
|
||||
|
||||
If your change has an issue, link it at the end: Closes: https://github.com/quitesimpleorg/looqs/issues/1
|
||||
|
||||
Example: "shared: Indexer: Use WildcardMatcher to ignore paths"
|
||||
|
||||
## License
|
||||
You license your changes under the GPLv3 by contributing.
|
33
HACKING.md
Normal file
33
HACKING.md
Normal file
@ -0,0 +1,33 @@
|
||||
# looqs - Hacking
|
||||
|
||||
## Introduction
|
||||
Without elaborating here, I hacked looqs because I was not satisfied with the state of desktop search on Linux.
|
||||
|
||||
Originally a set of CLI python scripts, it is now written in C++ and offers a GUI made using Qt. While a "web app" would have been an option, I prefer a desktop application for something like looqs. I chose Qt because I am more familiar with it than with any other GUI framework. To my knowledge, potential alternatives like GTK do not include as many "batteries" as Qt anyway, so the job presumably would have been harder there.
|
||||
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md) contains the instructions on how to submit patches etc.
|
||||
|
||||
## Security
|
||||
The architecture ensures that the parsing of documents and the preview generation is sandboxed by [exile.h](https://github.com/quitesimpleorg/exile.h). looqs uses a multi-process architecture to achieve this.
|
||||
|
||||
Qt code is considered trusted in this model. While one may critize this, it was the only practical solution. looqs uses its serialization mechanism and other classes to communicate between the non-sandboxed GUI process and the sandboxed processes.
|
||||
|
||||
Set the enviornment variable `LOOQS_DISABLE_SANDBOX=1` to disable sandboxing. It's intended for troublehshooting.
|
||||
|
||||
## Database
|
||||
The heart is sqlite, with the FTS5 extensions behind the full-text search. I definitly did not
|
||||
want to run some heavy Java based solutions. I explored other options like Postgresql, I've discard them due to some limitations back then.
|
||||
|
||||
Down the road, alternatives will be explored of course if sqlite should not suffice anymore.
|
||||
|
||||
## File format support
|
||||
The pdf library is libpoppler. Files such as .odt or .docx documents are opened with libquazip. The XML files in there are not parsed,
|
||||
looqs simply strips the tags and that seems to work fine so far. Naturally, this is not the "proper way", so there is room for improvement maybehere. However, those file formats are not a huge priortiy for me personally. libuchardet does encoding detection and conversion.
|
||||
|
||||
Naturally looqs won't be able to index and render previews for everything. Such approach would create a huge bloated binary. In the future, there will be some plugin system of some sorts, either we will load .so objects or use subprocesses.
|
||||
|
||||
## Name
|
||||
looqs looks for files. You as the user can also look inside them. The 'k' was replaced by a 'q'. Originally wanted my projects to have "qs" (for quitesimple) in their name. While abandoned now, this got us to looqs.
|
||||
|
||||
|
||||
|
678
LICENSE
Normal file
678
LICENSE
Normal file
@ -0,0 +1,678 @@
|
||||
Copyright (c) 2018-2022: Albert Schwarzkopf <looqs at quitesimple period org>
|
||||
|
||||
looqs is made available under the following license:
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
95
README.md
95
README.md
@ -1,30 +1,101 @@
|
||||
# looqs - Looks for files. And looks inside them
|
||||
looqs creates a full text search for your files. It allows you to look at previews where your
|
||||
search terms have been found.
|
||||
|
||||
Currently, this allows you search all indexed pdfs and take a look at the pages side by side in an instant.
|
||||
# looqs - Full-text search with previews for your files
|
||||
looqs is a tool that creates a full-text search index for your files. It allows you to look at previews where your
|
||||
search terms have been found, as shown in the screenshots below.
|
||||
|
||||
## Screenshots
|
||||
Coming soon™
|
||||
The screenshots in this section may occasionally be slightly outdated, but they are usually recent enough to get an overall impression of the current state of the GUI.
|
||||
|
||||
### Preview
|
||||
looqs allow you to look inside files. It marks what you have searched for.
|
||||
|
||||

|
||||

|
||||
|
||||
### Results list
|
||||
#### Classic results list
|
||||
Just enter what you want to find, it will search paths and file content.
|
||||

|
||||
|
||||
#### Searching with filters
|
||||
You can be more specific to get what you want with filters
|
||||
|
||||
**Filters (long form)**
|
||||

|
||||
|
||||
**Filters (short form)**
|
||||
|
||||
There is no need to write the long form of filters. There are also booleans available
|
||||
|
||||

|
||||
|
||||
|
||||
## Current status
|
||||
Last version: 2022-06-07, v0.2
|
||||
|
||||
Please see [Changelog](CHANGELOG.md) for a human readable list of changes.
|
||||
|
||||
|
||||
## Goals and principles
|
||||
* **Find & Preview**. Instead of merely telling you where your search phrase has been found, it should also render the corresponding portion/pages of the documents and highlight the searched words.
|
||||
* **No daemons**. As other solutions are prone to have annoying daemons running that eat system resources away, this solution should make do without daemons if possible.
|
||||
* **Easy setup**. Similiarly, there should be no need for heavy-weight databases. Instead, this solution tries to squeeze out the most from simple approaches. In particular, it relies on sqlite.
|
||||
* **No daemons**. As some other desktop search projects are prone to have annoying daemons running that eat system resources away, this solution should make do without daemons where possible.
|
||||
* **Easy setup**. Similarly, there should be no need for heavy-weight databases. Instead, looqs tries to squeeze out the most from simple approaches. In particular, it relies on sqlite.
|
||||
* **GUI & CLI**. Provide CLI interfaces and GUI interfaces
|
||||
* **Sandboxing**. As reading and rendering lots of formats naturally opens the door for security bugs, those tasks are offloaded to small, sandboxed sub-processes to mitigate the effect of exploited vulnerabilities.
|
||||
|
||||
|
||||
## Features
|
||||
- GUI, CLI interface
|
||||
- Indexing of file path and some metadata.
|
||||
- Indexing of file file content for FTS search. Currently: .pdf, odt, docx, plaintext.
|
||||
- Preview of file formats: Currently: .pdf, plaintext
|
||||
- Highlight searched terms.
|
||||
- Quickly open PDF viewer or text editor at location of preview
|
||||
- Search filters
|
||||
|
||||
## Supported platforms
|
||||
Linux (on amd64) is currently the main focus. Currently, I don't plan on supporting anything else and the sandboxing architecture does not make it likely. I suppose a version without sandboxing might be conceivable for other platforms, but I have no plans or resources to actively target anything but Linux at this point.
|
||||
|
||||
### Licence
|
||||
GPLv3.
|
||||
|
||||
### Contributing
|
||||
Please see the [Contribution guidelines](CONTRIBUTING.md) file.
|
||||
|
||||
## Documentation
|
||||
Please see [USAGE.md](USAGE.md) for the user manual. There is also [HACKING.md](HACKING.md) with more technical information.
|
||||
|
||||
|
||||
## Build
|
||||
### Ubuntu 21.04
|
||||
|
||||
### Ubuntu 21.10/22.04
|
||||
|
||||
To build on Ubuntu and Debian, clone the repo and then run:
|
||||
```
|
||||
git submodule init
|
||||
git submodule update
|
||||
sudo apt install build-essential qtbase5-dev libpoppler-qt5-dev libuchardet-dev libquazip5-dev
|
||||
qmake
|
||||
make
|
||||
```
|
||||
|
||||
## Documentation
|
||||
Coming soon™
|
||||
The GUI is located in `gui/looqs-gui`, the binary for the CLI is in `cli/looqs`
|
||||
|
||||
## Packages
|
||||
Coming soon™
|
||||
At this point, looqs is not in any official distro package repo, but I maintain some packages.
|
||||
|
||||
### Ubuntu 21.10/22.04
|
||||
Latest release can be installed using apt from the repo.
|
||||
```
|
||||
# First, obtain key, assume it's trusted.
|
||||
wget -O- https://repo.quitesimple.org/repo.quitesimple.org.asc | gpg --dearmor > repo.quitesimple.org-keyring.gpg
|
||||
cat repo.quitesimple.org-keyring.gpg | sudo tee -a /usr/share/keyrings/repo.quitesimple.org.gpg > /dev/null
|
||||
|
||||
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/repo.quitesimple.org.gpg] https://repo.quitesimple.org/debian/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/quitesimple.list
|
||||
sudo apt-get update
|
||||
sudo apt-get install looqs
|
||||
```
|
||||
|
||||
### Other distros
|
||||
I'll probably add a package for voidlinux at some point and maybe will provide a Gentoo ebuild. However, I would appreciate help for others distros. If you create a package, let me know!
|
||||
|
||||
As for distro-agnostic packages, I will also take a look into appimage / flatpak etc. and/or maybe just provide a self-contained archive.
|
||||
|
33
TODO
33
TODO
@ -1,33 +0,0 @@
|
||||
general database classes instead of sqlite specific code
|
||||
database: set a number of paths to default index. will require an indexer code though
|
||||
sandboxing!
|
||||
allow from GUI to ues commandlin, e. g. "/add ..." would be the same as "qss add ..." in termial
|
||||
|
||||
PdfPreview: Use some kind of paging instead of memory limit
|
||||
Consider injecting Logger (default stdout/stderr) to classes instead of using Logger::info()/Logger::error()::
|
||||
sync/share GUI and CLI data-structures. Better to share codebase in general
|
||||
- cli: tagging
|
||||
- cli: command line parser: wrong position of [options]
|
||||
- ability to set the WHERE condition (allow editing the SQL query)
|
||||
- Basic OCR in images (screenshots)
|
||||
- Index .ebup
|
||||
- Preview for: .txt, source code files, .ebup, images
|
||||
- index: DVD menus, media metadata in audio/files etc?
|
||||
- Stats: Number of results found
|
||||
- PdfPreview: Files per file, or directory (so basically filter the
|
||||
results)
|
||||
- Hide PdfPreview Tab if there are no pdfs in the results
|
||||
-Tagging: add an "addtag" utility, to assign tags to folder and files
|
||||
-gui: Search expclitly for tags, list by tags, remove tags, add tags
|
||||
-gui: Filter already found results. For example, "show only folders",
|
||||
or just search with those results.
|
||||
-split each tab into own class, not everything in mainwindow.cpp?
|
||||
Menu:
|
||||
-Delete from index
|
||||
-Delete from fs
|
||||
-Reindex
|
||||
Filter:
|
||||
type:d
|
||||
type:file
|
||||
mtime:
|
||||
tag:
|
176
USAGE.md
Normal file
176
USAGE.md
Normal file
@ -0,0 +1,176 @@
|
||||
# looqs - User guide
|
||||
This document is still work in progress.
|
||||
|
||||
## General points
|
||||
Please consult the [README](README.md) for a description of what looqs is and on how to obtain it.
|
||||
|
||||
looqs is still at an early stage and may exhibit some weirdness and contain bugs.
|
||||
|
||||
## Current Limitations and things to know
|
||||
You should be aware of the following:
|
||||
|
||||
- It may seem natural, but the GUI and CLI operate on the same database, so if you add files using the CLI, the GUI will search them too.
|
||||
|
||||
- If a file is listed in the "Search results" tab, it does not imply that a preview will be available in the "Previews" tab, as looqs can search more file formats than it can generate previews for currently.
|
||||
|
||||
- Database paths are stored inefficiently, not deduplicated to simplify queries. This may add up quickly. Also, each PDF text is stored twice. Each page separately + the whole document to simplify queries.
|
||||
To give you some idea: At the time this section was written, 167874 files were in my index. A FTS index was built for 14280 of those, of which 4146 were PDF documents. The PDFs take around 10GB storage space on the filesystem. All files for which an FTS has been built are around 7GB in size on the filesystem. The looqs database had a size of 1.6 GB.
|
||||
|
||||
- Existing files are considered modified when the mtime has changed. looqs currently does not check whether the content
|
||||
has changed.
|
||||
|
||||
## Config
|
||||
The config file is in `$HOME/.config/quitesimple.org/looqs.conf`. It will be created on first execution of the CLI or GUI
|
||||
interface. The GUI has a menu entry to quickly open this config file. This is to be considered temporary and will be removed once the GUI itself can edit all settings.
|
||||
|
||||
Database default path: `$HOME/.local/share/quitesimple.org/looqs/looqs.sqlite`. If this does not work for
|
||||
you, move it and adjust adjust the path in the config file.
|
||||
|
||||
|
||||
## GUI
|
||||
The GUI is minimal at this point. Depending on what you want to do, you may need to open the config file and change the settings there. Chances are that you may not need to do that.
|
||||
|
||||
### First run
|
||||
You will be presented with an empty list. Go to the **"Index"** tab, add some directories and click **"Start indexing"**.
|
||||
|
||||
For large directories the progress bar is essentially just decoration. As long as you see the counters
|
||||
increase, everything is fine even if it seems the progress bar is stuck.
|
||||
|
||||
The indexing can be stopped. If you run it again you do not start from scratch, because looqs knows
|
||||
which files have been modified or not since they have been added to the index. Thus, files will
|
||||
only be reprocedded when necessary. Note that cancellation itself may take a moment as files finish processing.
|
||||
|
||||
### Search
|
||||
The text field at the top is where you type your query. It can be selected quickly using **CTRL + L**. Filters are avalable,
|
||||
see this document at the end. By default, both the full path and the content are searched. Path names take precedence.
|
||||
|
||||
### Configuring PDF viewer
|
||||
It's most convenient if, when you click on a preview, the PDF reader opens the page you clicked. For that, looqs needs to know which viewer you want to launch.
|
||||
|
||||
It tries to auto detect some common viewers. You must set the value of the ```pdfviewer=``` config entry yourself if it doesn't do something you
|
||||
like, such as not opening your favorite viewer. In the command line options, "%f" represents the filepath, "%p" the page number.
|
||||
|
||||
### Preview tab
|
||||
The preview tab shows previews. It marks your search keywords too. Click on a preview to open the file.
|
||||
A right click on a preview allows you to copy the file path, or to open the containing folder. Hovering tells you which file the preview originates from.
|
||||
|
||||
### Syncing index
|
||||
Over time, files get deleted or their content changes. Go to **looqs** -> **Sync index**. looqs will reindex the content of files which have been changed. Files that cannot be found anymore will be removed from the index.
|
||||
|
||||
Reindexing a path using the "Index" tab will index new files and update existing ones. Currently however, this does not deal with deleted files.
|
||||
|
||||
I recommend doing a sync from time to time.
|
||||
|
||||
## CLI
|
||||
The CLI command "looqs" comes with helptext. This documentation is incomplete at the moment.
|
||||
|
||||
### First run
|
||||
There is no point in using the "search" command on the first run. Add some files if not done so already.
|
||||
|
||||
### Adding files
|
||||
To add files to the index, run ```looqs add [path]```, where 'path' can be a directory or a single file.
|
||||
If the path is a directory, the directory will be recursively descended, and all files in there added.
|
||||
|
||||
"Skipped" implies the file has not been changed since it has been added to the index. If it has changed, the index content will be updated.
|
||||
|
||||
### Searching files
|
||||
Of course the CLI will not render any previews, but it can show you the paths where search results
|
||||
have been found.
|
||||
|
||||
```
|
||||
looqs search [terms...]
|
||||
```
|
||||
|
||||
There is an implicit "AND" condition, meaning if you search for "photo" and "mountain", only paths
|
||||
will be shown containing both terms, but not either alone.
|
||||
|
||||
### Deletion and Fixing Out of sync index
|
||||
You sometimes delete files, to get rid of those from the index too, run:
|
||||
|
||||
```
|
||||
looqs delete --deleted --dry-run
|
||||
```
|
||||
|
||||
This commands lists all files which are indexed, but which cannot be found anymore.
|
||||
|
||||
Remove them using:
|
||||
```
|
||||
looqs delete --deleted --verbose
|
||||
```
|
||||
|
||||
You can also delete by pattern:
|
||||
|
||||
```
|
||||
looqs delete --pattern '*.java'
|
||||
```
|
||||
|
||||
Delete never removes anything from the file system, it only operates on the database.
|
||||
|
||||
The equivalent of the GUI sync command is:
|
||||
```
|
||||
looks update -v --continue --delete
|
||||
```
|
||||
|
||||
|
||||
### Updating files
|
||||
The content and metadata index for files can be updated:
|
||||
|
||||
```
|
||||
looqs update -n
|
||||
```
|
||||
|
||||
Those files still exist, but the content that has been indexed it out of date. This can be corrected with
|
||||
|
||||
```
|
||||
looqs update
|
||||
```
|
||||
|
||||
This will not add new files, you must run ```looqs add``` for this. For this reason, most users
|
||||
will probably seldomly use the 'update' command alone.
|
||||
|
||||
|
||||
## Tips
|
||||
|
||||
### Keeping index up to date
|
||||
The most obvious way is to use the GUI and add your favorite paths in the "Index" tab. Then occasionally, just rescan. This works for me personally, looqs quickly picks up new files. This however may not be good enough for some users.
|
||||
|
||||
Some users may prefer setting up cronjobs or wire up the CLI interface with file system monitoring tools such as [adhocify](https://github.com/quitesimpleorg/adhocify).
|
||||
|
||||
### lh shell alias
|
||||
If you are in a shell and you know your file is somewhere in your current directory or its subdirs, and those
|
||||
are indexed by looqs, you may find the lh (look here) alias useful:
|
||||
|
||||
```
|
||||
alias lh='looqs search $(pwd)'
|
||||
```
|
||||
|
||||
So typing "lh recipes" searchs the current dir and its subdirs for a file containing 'recipes'.
|
||||
|
||||
## Query syntax / Search filters
|
||||
A number of search filters are available.
|
||||
|
||||
| Filter (long) | Filter (short) | Explanation |
|
||||
| ----------- | ----------- |----------- |
|
||||
| path.contains:(term) | p:(term) | Pretty much a SQL LIKE '%term%' conditions, just searches the path string |
|
||||
| path.ends:(term) | pe:(term) | Filters path ending with the specified term, e. g.: pe:(.ogg) |
|
||||
| path.begins:(term) | pb:(term) | Filters path beginning with the specified term |
|
||||
| contains:(terms) | c:(terms) | ull-text search, also understands quotes |
|
||||
|
||||
Filters can be combined. The booleans AND and OR are supported. Negations can be applied too, except for c:().
|
||||
The AND boolean is implicit and thus entering it strictly optional.
|
||||
|
||||
Examples:
|
||||
|
||||
| Query | Explanation |
|
||||
| ----------- | ----------- |
|
||||
|pe:(.ogg) p:(marley)| Finds paths that end with .ogg and contain 'marley' (case-insensitive)
|
||||
|p:(slides) support vector machine |Performs a content search for 'support vector machine' in all paths containing 'slides'|
|
||||
|p:(notes) (pe:(odt) OR pe:(docx)) |Finds files such as notes.docx, notes.odt but also any .docs and .odt when the path contains the string 'notes'|
|
||||
|memcpy !(pe:(.c) OR pe:(.cpp))| Performs a FTS search for 'memcpy' but excludes .cpp and .c files.
|
||||
|c:("I think, therefore")|Performs a FTS search for the phrase "I think, therefore".
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
39
cli/cli.pro
39
cli/cli.pro
@ -14,60 +14,29 @@ DEFINES += QT_DEPRECATED_WARNINGS
|
||||
# In order to do so, uncomment the following line.
|
||||
# You can also select to disable deprecated APIs only up to a certain version of Qt.
|
||||
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
|
||||
LIBS += -luchardet -lpoppler-qt5 -lquazip5
|
||||
SOURCES += \
|
||||
main.cpp \
|
||||
encodingdetector.cpp \
|
||||
pagedata.cpp \
|
||||
processor.cpp \
|
||||
pdfprocessor.cpp \
|
||||
defaulttextprocessor.cpp \
|
||||
commandadd.cpp \
|
||||
sandboxedprocessor.cpp \
|
||||
tagstripperprocessor.cpp \
|
||||
nothingprocessor.cpp \
|
||||
odtprocessor.cpp \
|
||||
utils.cpp \
|
||||
odsprocessor.cpp \
|
||||
commanddelete.cpp \
|
||||
commandupdate.cpp \
|
||||
filesaver.cpp \
|
||||
databasefactory.cpp \
|
||||
sqlitedbservice.cpp \
|
||||
logger.cpp \
|
||||
commandsearch.cpp \
|
||||
commandlist.cpp
|
||||
commandlist.cpp \
|
||||
command.cpp
|
||||
|
||||
HEADERS += \
|
||||
encodingdetector.h \
|
||||
processor.h \
|
||||
pagedata.h \
|
||||
pdfprocessor.h \
|
||||
defaulttextprocessor.h \
|
||||
command.h \
|
||||
commandadd.h \
|
||||
sandboxedprocessor.h \
|
||||
tagstripperprocessor.h \
|
||||
nothingprocessor.h \
|
||||
odtprocessor.h \
|
||||
utils.h \
|
||||
odsprocessor.h \
|
||||
commanddelete.h \
|
||||
commandupdate.h \
|
||||
filesaver.h \
|
||||
databasefactory.h \
|
||||
sqlitedbservice.h \
|
||||
logger.h \
|
||||
commandsearch.h \
|
||||
commandlist.h
|
||||
INCLUDEPATH += /usr/include/poppler/qt5/ /usr/include/quazip5
|
||||
|
||||
|
||||
|
||||
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../shared/release/ -lshared
|
||||
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../shared/debug/ -lshared
|
||||
else:unix: LIBS += -L$$OUT_PWD/../shared/ -lshared
|
||||
|
||||
LIBS += -luchardet -lpoppler-qt5 -lquazip5
|
||||
|
||||
INCLUDEPATH += $$PWD/../shared
|
||||
DEPENDPATH += $$PWD/../shared
|
||||
|
||||
|
@ -3,3 +3,12 @@
|
||||
#include <QDebug>
|
||||
#include "command.h"
|
||||
#include "looqsgeneralexception.h"
|
||||
|
||||
void Command::execute()
|
||||
{
|
||||
int result = handle(arguments);
|
||||
if(autoFinish)
|
||||
{
|
||||
emit finishedCmd(result);
|
||||
}
|
||||
}
|
||||
|
@ -1,26 +1,39 @@
|
||||
#ifndef COMMAND_H
|
||||
#define COMMAND_H
|
||||
#include <QStringList>
|
||||
#include <QSqlDatabase>
|
||||
#include <QSqlQuery>
|
||||
#include <QThreadStorage>
|
||||
#include <QVariant>
|
||||
#include <QMutex>
|
||||
#include <QWaitCondition>
|
||||
#include "utils.h"
|
||||
#include "sqlitedbservice.h"
|
||||
class Command
|
||||
class Command : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
signals:
|
||||
void finishedCmd(int retval);
|
||||
|
||||
protected:
|
||||
SqliteDbService *dbService;
|
||||
QString dbConnectionString;
|
||||
QStringList arguments;
|
||||
|
||||
bool autoFinish = true;
|
||||
|
||||
public:
|
||||
Command(SqliteDbService &dbService)
|
||||
{
|
||||
this->dbService = &dbService;
|
||||
}
|
||||
|
||||
void setArguments(QStringList arguments)
|
||||
{
|
||||
this->arguments = arguments;
|
||||
}
|
||||
virtual int handle(QStringList arguments) = 0;
|
||||
virtual ~Command(){};
|
||||
|
||||
public slots:
|
||||
void execute();
|
||||
};
|
||||
|
||||
#endif // COMMAND_H
|
||||
|
@ -1,7 +1,5 @@
|
||||
#include <QFileInfo>
|
||||
#include <QDebug>
|
||||
#include <QSqlQuery>
|
||||
#include <QSqlError>
|
||||
#include <QDateTime>
|
||||
#include <QMap>
|
||||
#include <QTextStream>
|
||||
@ -13,6 +11,32 @@
|
||||
#include "commandadd.h"
|
||||
#include "logger.h"
|
||||
|
||||
void CommandAdd::indexerFinished()
|
||||
{
|
||||
IndexResult result = indexer->getResult();
|
||||
|
||||
Logger::info() << "Total: " << result.total() << Qt::endl;
|
||||
Logger::info() << "Added: " << result.addedPaths << Qt::endl;
|
||||
Logger::info() << "Skipped: " << result.skippedPaths << Qt::endl;
|
||||
auto failedPathsCount = result.erroredPaths;
|
||||
Logger::info() << "Failed: " << failedPathsCount << Qt::endl;
|
||||
if(failedPathsCount > 0)
|
||||
{
|
||||
Logger::info() << "Failed paths: " << Qt::endl;
|
||||
for(QString paths : result.failedPaths())
|
||||
{
|
||||
Logger::info() << paths << Qt::endl;
|
||||
}
|
||||
}
|
||||
|
||||
int ret = 0;
|
||||
if(!keepGoing && failedPathsCount > 0)
|
||||
{
|
||||
ret = 1;
|
||||
}
|
||||
emit finishedCmd(ret);
|
||||
}
|
||||
|
||||
int CommandAdd::handle(QStringList arguments)
|
||||
{
|
||||
QCommandLineParser parser;
|
||||
@ -20,20 +44,13 @@ int CommandAdd::handle(QStringList arguments)
|
||||
"Continue adding files, don't exit on first error. If this option is not given, looqs will "
|
||||
"exit asap, but it's possible that a few files will still be processed. "
|
||||
"Set -t 1 to avoid this behavior, but processing will be slower. "},
|
||||
{{"a", "all"}, "On error, no files should be added, even already processed ones"},
|
||||
{{"v", "verbose"}, "Print skipped and added files"},
|
||||
{{"t", "threads"}, "Number of threads to use.", "threads"}});
|
||||
|
||||
parser.addHelpOption();
|
||||
parser.addPositionalArgument("add", "Add paths to the index", "add [paths...]");
|
||||
|
||||
parser.process(arguments);
|
||||
bool keepGoing = parser.isSet("continue");
|
||||
bool verbose = parser.isSet("verbose");
|
||||
if(parser.isSet("all"))
|
||||
{
|
||||
throw LooqsGeneralException("To be implemented");
|
||||
}
|
||||
this->keepGoing = parser.isSet("continue");
|
||||
if(parser.isSet("threads"))
|
||||
{
|
||||
QString threadsCount = parser.value("threads");
|
||||
@ -53,15 +70,19 @@ int CommandAdd::handle(QStringList arguments)
|
||||
}
|
||||
}
|
||||
|
||||
FileSaver saver(*this->dbService);
|
||||
int numFilesCount = files.size();
|
||||
int processedFilesCount = saver.addFiles(files.toVector(), keepGoing, verbose);
|
||||
if(processedFilesCount != numFilesCount)
|
||||
{
|
||||
Logger::error() << "Errors occured while trying to add files to the database. Processed " << processedFilesCount
|
||||
<< "out of" << numFilesCount << "files" << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
indexer = new Indexer(*this->dbService);
|
||||
indexer->setTargetPaths(files.toVector());
|
||||
indexer->setKeepGoing(keepGoing);
|
||||
|
||||
connect(indexer, &Indexer::pathsCountChanged, this,
|
||||
[](int pathsCount) { Logger::info() << "Found paths: " << pathsCount << Qt::endl; });
|
||||
connect(indexer, &Indexer::indexProgress, this,
|
||||
[](int pathsCount, unsigned int added, unsigned int skipped, unsigned int failed, unsigned int totalCount)
|
||||
{ Logger::info() << "Processed files: " << pathsCount << Qt::endl; });
|
||||
connect(indexer, &Indexer::finished, this, &CommandAdd::indexerFinished);
|
||||
|
||||
this->autoFinish = false;
|
||||
indexer->beginIndexing();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
@ -3,15 +3,22 @@
|
||||
#include <QMutex>
|
||||
#include "command.h"
|
||||
#include "filesaver.h"
|
||||
#include "indexer.h"
|
||||
|
||||
class CommandAdd : public Command
|
||||
{
|
||||
private:
|
||||
SaveFileResult addFile(QString path);
|
||||
Indexer *indexer;
|
||||
bool keepGoing = true;
|
||||
|
||||
protected:
|
||||
public:
|
||||
using Command::Command;
|
||||
|
||||
int handle(QStringList arguments) override;
|
||||
private slots:
|
||||
void indexerFinished();
|
||||
};
|
||||
|
||||
#endif // COMMANDADD_H
|
||||
|
@ -3,7 +3,6 @@
|
||||
#include <QFileInfo>
|
||||
#include <QDebug>
|
||||
#include <QRegularExpression>
|
||||
#include <QSqlError>
|
||||
#include "commanddelete.h"
|
||||
#include "logger.h"
|
||||
|
||||
|
@ -7,29 +7,31 @@ int CommandList::handle(QStringList arguments)
|
||||
{
|
||||
QCommandLineParser parser;
|
||||
parser.addOptions({
|
||||
{{"r", "reverse"}, "Print most-recent changed files first"},
|
||||
{{"c", "count"}, "Counts the number of paths listed"},
|
||||
{"pattern", "Only list files from index matching the pattern, e. g. */.git/*", "pattern"},
|
||||
{"pattern", "Only list files from index matching the pattern, e. g. '*.txt'", "pattern"},
|
||||
});
|
||||
|
||||
parser.addHelpOption();
|
||||
parser.addPositionalArgument("list", "Lists paths in the index", "list [options]");
|
||||
|
||||
parser.process(arguments);
|
||||
bool reverse = parser.isSet("reverse");
|
||||
if(reverse)
|
||||
|
||||
QString pattern = parser.value("pattern");
|
||||
|
||||
QVector<FileData> results;
|
||||
|
||||
int offset = 0;
|
||||
int limit = 1000;
|
||||
|
||||
auto resultscount = dbService->getFiles(results, pattern, offset, limit);
|
||||
while(resultscount > 0)
|
||||
{
|
||||
throw LooqsGeneralException("Reverse option to be implemented");
|
||||
for(FileData &fileData : results)
|
||||
{
|
||||
Logger::info() << fileData.absPath << Qt::endl;
|
||||
}
|
||||
offset += limit;
|
||||
results.clear();
|
||||
resultscount = dbService->getFiles(results, pattern, offset, limit);
|
||||
}
|
||||
|
||||
QStringList files = parser.positionalArguments();
|
||||
QString queryStrings = files.join(' ');
|
||||
auto results = dbService->search(LooqsQuery::build(queryStrings, TokenType::FILTER_PATH_CONTAINS, false));
|
||||
|
||||
for(SearchResult &result : results)
|
||||
{
|
||||
Logger::info() << result.fileData.absPath << Qt::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
#ifndef COMMANDSEARCH_H
|
||||
#define COMMANDSEARCH_H
|
||||
#ifndef COMMANDLIST_H
|
||||
#define COMMANDLIST_H
|
||||
#include "command.h"
|
||||
#include "../shared/sqlitesearch.h"
|
||||
|
||||
@ -11,4 +11,4 @@ class CommandList : public Command
|
||||
int handle(QStringList arguments) override;
|
||||
};
|
||||
|
||||
#endif // COMMANDSEARCH_H
|
||||
#endif // COMMANDLIST_H
|
||||
|
@ -8,14 +8,19 @@ int CommandSearch::handle(QStringList arguments)
|
||||
QCommandLineParser parser;
|
||||
parser.addOptions({
|
||||
{{"r", "reverse"},
|
||||
"Print most-recent changed files first. This is short for adding \"sort:(mtime asc)\" to the query."},
|
||||
"Print most-recently changed files last. This is short for adding \"sort:(mtime asc)\" to the query."},
|
||||
});
|
||||
|
||||
parser.addHelpOption();
|
||||
parser.process(arguments);
|
||||
|
||||
QStringList files = parser.positionalArguments();
|
||||
QString queryStrings = files.join(' ');
|
||||
QStringList terms = parser.positionalArguments();
|
||||
if(terms.length() == 0)
|
||||
{
|
||||
Logger::error() << "Please enter search terms" << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
QString queryStrings = terms.join(' ');
|
||||
LooqsQuery query = LooqsQuery::build(queryStrings, TokenType::FILTER_PATH_CONTAINS, false);
|
||||
bool reverse = parser.isSet("reverse");
|
||||
if(reverse)
|
||||
@ -26,11 +31,19 @@ int CommandSearch::handle(QStringList arguments)
|
||||
query.addSortCondition(sc);
|
||||
}
|
||||
|
||||
auto results = dbService->search(query);
|
||||
|
||||
for(SearchResult &result : results)
|
||||
try
|
||||
{
|
||||
Logger::info() << result.fileData.absPath << Qt::endl;
|
||||
auto results = dbService->search(query);
|
||||
|
||||
for(SearchResult &result : results)
|
||||
{
|
||||
Logger::info() << result.fileData.absPath << Qt::endl;
|
||||
}
|
||||
}
|
||||
catch(LooqsGeneralException &e)
|
||||
{
|
||||
Logger::error() << "Exception:" << e.message << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
@ -2,9 +2,9 @@
|
||||
#include <QFileInfo>
|
||||
#include <QDateTime>
|
||||
#include <QThreadPool>
|
||||
#include <QtConcurrentRun>
|
||||
#include "commandupdate.h"
|
||||
#include "logger.h"
|
||||
#include "../shared/indexsyncer.h"
|
||||
|
||||
int CommandUpdate::handle(QStringList arguments)
|
||||
{
|
||||
@ -13,18 +13,17 @@ int CommandUpdate::handle(QStringList arguments)
|
||||
{{{"v", "verbose"}, "Print path of the files while updating them"},
|
||||
{{"n", "dry-run"}, "Only print which files would be updated, don't actually update them"},
|
||||
{"pattern", "Only consider to update files in the index matching the pattern, e. g. */.git/*.", "pattern"},
|
||||
{{"d", "delete"}, "If a file does not exist anymore, delete it"},
|
||||
{{"d", "delete"}, "If a file does not exist anymore, delete it from the index"},
|
||||
{{"c", "continue"},
|
||||
"Continue adding files, don't exit on first error. If this option is not given, looqs will exit asap, but "
|
||||
"it's possible that a few files will still be processed. "
|
||||
"Set -t 1 to avoid this behavior, but processing will be slower."},
|
||||
{{"a", "all"}, "On error, no files should be updated, even already processed ones"},
|
||||
{{"t", "threads"}, "Number of threads to use.", "threads"}
|
||||
|
||||
});
|
||||
|
||||
parser.addHelpOption();
|
||||
parser.addPositionalArgument("update", "Checks files for changes and updates them", "update");
|
||||
parser.addPositionalArgument("update", "Checks files for changes and updates the index", "update");
|
||||
|
||||
parser.process(arguments);
|
||||
bool keepGoing = parser.isSet("continue");
|
||||
@ -33,84 +32,61 @@ int CommandUpdate::handle(QStringList arguments)
|
||||
bool dryRun = parser.isSet("dry-run");
|
||||
QString pattern = parser.value("pattern");
|
||||
|
||||
if(parser.isSet("all"))
|
||||
{
|
||||
throw LooqsGeneralException("To be implemented");
|
||||
}
|
||||
if(parser.isSet("threads"))
|
||||
{
|
||||
QString threadsCount = parser.value("threads");
|
||||
QThreadPool::globalInstance()->setMaxThreadCount(threadsCount.toInt());
|
||||
}
|
||||
FileSaver saver(*this->dbService);
|
||||
QVector<FileData> files;
|
||||
int offset = 0;
|
||||
int limit = 1000;
|
||||
int processedRows = dbService->getFiles(files, pattern, offset, limit);
|
||||
|
||||
while(processedRows > 0)
|
||||
bool hasErrors = false;
|
||||
IndexSyncer *syncer = new IndexSyncer(*this->dbService);
|
||||
syncer->setKeepGoing(keepGoing);
|
||||
syncer->setVerbose(verbose);
|
||||
syncer->setPattern(pattern);
|
||||
syncer->setDryRun(dryRun);
|
||||
syncer->setRemoveDeletedFromIndex(deleteMissing);
|
||||
|
||||
if(dryRun)
|
||||
{
|
||||
QVector<QString> filePathsToUpdate;
|
||||
for(FileData &fileData : files)
|
||||
{
|
||||
QFileInfo fileInfo(fileData.absPath);
|
||||
if(fileInfo.exists() && fileInfo.isFile())
|
||||
{
|
||||
if(fileInfo.lastModified().toSecsSinceEpoch() != fileData.mtime)
|
||||
{
|
||||
if(!dryRun)
|
||||
{
|
||||
filePathsToUpdate.append(fileData.absPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::info() << "Would update" << fileData.absPath << Qt::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(deleteMissing)
|
||||
{
|
||||
if(!dryRun)
|
||||
{
|
||||
if(!this->dbService->deleteFile(fileData.absPath))
|
||||
{
|
||||
Logger::error()
|
||||
<< "Error: Failed to delete" << fileData.absPath << "from databas" << Qt::endl;
|
||||
if(!keepGoing)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if(verbose)
|
||||
{
|
||||
Logger::info() << "Deleted" << fileData.absPath << Qt::endl;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Logger::info() << "Would delete" << fileData.absPath << Qt::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int updatedFilesCount = saver.updateFiles(filePathsToUpdate, keepGoing, verbose);
|
||||
int shouldHaveUpdatedCount = filePathsToUpdate.size();
|
||||
if(updatedFilesCount != shouldHaveUpdatedCount)
|
||||
{
|
||||
if(!keepGoing)
|
||||
{
|
||||
Logger::error() << "Failed to update all files selected for updating. Updated" << updatedFilesCount
|
||||
<< "out of" << shouldHaveUpdatedCount << "selected for upating" << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
offset += limit;
|
||||
processedRows = this->dbService->getFiles(files, pattern, offset, limit);
|
||||
connect(syncer, &IndexSyncer::removedDryRun, this,
|
||||
[](QString path) { Logger::info() << "Would delete" << path << Qt::endl; });
|
||||
connect(syncer, &IndexSyncer::updatedDryRun, this,
|
||||
[](QString path) { Logger::info() << "Would update" << path << Qt::endl; });
|
||||
}
|
||||
else
|
||||
{
|
||||
connect(syncer, &IndexSyncer::removed, this,
|
||||
[](QString path) { Logger::info() << "Removed " << path << Qt::endl; });
|
||||
/* TODO: updated not printed, handled be verbose in FileSaver, but this can be improved */
|
||||
}
|
||||
connect(syncer, &IndexSyncer::finished, this,
|
||||
[&](unsigned int totalUpdated, unsigned int totalRemoved, unsigned int totalErrors)
|
||||
{
|
||||
Logger::info() << "Syncing finished" << Qt::endl;
|
||||
|
||||
if(!dryRun)
|
||||
{
|
||||
Logger::info() << "Total updated:" << totalUpdated << Qt::endl;
|
||||
Logger::info() << "Total removed from index: " << totalRemoved << Qt::endl;
|
||||
Logger::info() << "Total deleted:" << totalErrors << Qt::endl;
|
||||
}
|
||||
|
||||
int retval = 0;
|
||||
if(hasErrors && !keepGoing)
|
||||
{
|
||||
retval = 1;
|
||||
}
|
||||
emit finishedCmd(retval);
|
||||
});
|
||||
connect(syncer, &IndexSyncer::error, this,
|
||||
[&](QString error)
|
||||
{
|
||||
Logger::error() << error << Qt::endl;
|
||||
hasErrors = true;
|
||||
});
|
||||
|
||||
this->autoFinish = false;
|
||||
syncer->sync();
|
||||
/* Actual return code is handled by finishedCmd signal */
|
||||
return 0;
|
||||
}
|
||||
|
24
cli/main.cpp
24
cli/main.cpp
@ -5,13 +5,11 @@
|
||||
#include <QDataStream>
|
||||
#include <QDebug>
|
||||
#include <QProcessEnvironment>
|
||||
#include <QSqlDatabase>
|
||||
#include <QSqlQuery>
|
||||
#include <QSqlError>
|
||||
#include <QMap>
|
||||
#include <QDebug>
|
||||
#include <QSettings>
|
||||
#include <functional>
|
||||
#include <QTimer>
|
||||
#include <exception>
|
||||
#include "encodingdetector.h"
|
||||
#include "pdfprocessor.h"
|
||||
@ -22,10 +20,12 @@
|
||||
#include "commanddelete.h"
|
||||
#include "commandupdate.h"
|
||||
#include "commandsearch.h"
|
||||
#include "commandlist.h"
|
||||
#include "databasefactory.h"
|
||||
#include "logger.h"
|
||||
#include "sandboxedprocessor.h"
|
||||
#include "../shared/common.h"
|
||||
#include "../shared/filescanworker.h"
|
||||
|
||||
void printUsage(QString argv0)
|
||||
{
|
||||
@ -50,6 +50,10 @@ Command *commandFromName(QString name, SqliteDbService &dbService)
|
||||
{
|
||||
return new CommandSearch(dbService);
|
||||
}
|
||||
if(name == "list")
|
||||
{
|
||||
return new CommandList(dbService);
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
@ -77,6 +81,7 @@ int main(int argc, char *argv[])
|
||||
return 1;
|
||||
}
|
||||
qRegisterMetaType<PageData>();
|
||||
qRegisterMetaType<FileScanResult>("FileScanResult");
|
||||
|
||||
QString connectionString = Common::databasePath();
|
||||
DatabaseFactory dbFactory(connectionString);
|
||||
@ -99,16 +104,21 @@ int main(int argc, char *argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
return cmd->handle(args);
|
||||
QObject::connect(cmd, &Command::finishedCmd, [](int retval) { QCoreApplication::exit(retval); });
|
||||
cmd->setArguments(args);
|
||||
QTimer::singleShot(0, cmd, &Command::execute);
|
||||
}
|
||||
catch(const LooqsGeneralException &e)
|
||||
{
|
||||
Logger::error() << "Exception caught, message: " << e.message << Qt::endl;
|
||||
Logger::error() << "Exception caught, message:" << e.message << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger::error() << "Unknown command " << commandName << Qt::endl;
|
||||
Logger::error() << "Unknown command:" << commandName << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
return 1;
|
||||
|
||||
return app.exec();
|
||||
}
|
||||
|
23
gui/gui.pro
23
gui/gui.pro
@ -23,7 +23,8 @@ DEFINES += QT_DEPRECATED_WARNINGS
|
||||
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
|
||||
|
||||
SOURCES += \
|
||||
ipcclient.cpp \
|
||||
ipcpreviewclient.cpp \
|
||||
ipcpreviewworker.cpp \
|
||||
ipcserver.cpp \
|
||||
main.cpp \
|
||||
mainwindow.cpp \
|
||||
@ -31,35 +32,43 @@ SOURCES += \
|
||||
previewgenerator.cpp \
|
||||
previewgeneratormapfunctor.cpp \
|
||||
previewgeneratorpdf.cpp \
|
||||
previewgeneratorplaintext.cpp \
|
||||
previewresult.cpp \
|
||||
previewresultpdf.cpp \
|
||||
previewworker.cpp
|
||||
previewresultplaintext.cpp \
|
||||
renderconfig.cpp \
|
||||
rendertarget.cpp
|
||||
|
||||
HEADERS += \
|
||||
ipc.h \
|
||||
ipcclient.h \
|
||||
ipcpreviewclient.h \
|
||||
ipcpreviewworker.h \
|
||||
ipcserver.h \
|
||||
mainwindow.h \
|
||||
clicklabel.h \
|
||||
previewgenerator.h \
|
||||
previewgeneratormapfunctor.h \
|
||||
previewgeneratorpdf.h \
|
||||
previewgeneratorplaintext.h \
|
||||
previewresult.h \
|
||||
previewresultpdf.h \
|
||||
previewworker.h \
|
||||
renderconfig.h
|
||||
previewresultplaintext.h \
|
||||
renderconfig.h \
|
||||
rendertarget.h
|
||||
|
||||
FORMS += \
|
||||
mainwindow.ui
|
||||
|
||||
INCLUDEPATH += /usr/include/poppler/qt5/
|
||||
LIBS += -lpoppler-qt5
|
||||
|
||||
QT += widgets sql
|
||||
|
||||
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../shared/release/ -lshared
|
||||
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../shared/debug/ -lshared
|
||||
else:unix: LIBS += -L$$OUT_PWD/../shared/ -lshared
|
||||
|
||||
LIBS += -luchardet -lpoppler-qt5 -lquazip5
|
||||
|
||||
INCLUDEPATH += $$PWD/../shared
|
||||
DEPENDPATH += $$PWD/../shared
|
||||
|
||||
@ -68,3 +77,5 @@ else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../shar
|
||||
else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../shared/release/shared.lib
|
||||
else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../shared/debug/shared.lib
|
||||
else:unix: PRE_TARGETDEPS += $$OUT_PWD/../shared/libshared.a
|
||||
|
||||
RESOURCES = ../looqs.svg
|
||||
|
10
gui/ipc.h
10
gui/ipc.h
@ -3,7 +3,13 @@
|
||||
|
||||
enum IPCCommand
|
||||
{
|
||||
DocOpen,
|
||||
FileOpen
|
||||
GeneratePreviews = 23,
|
||||
StopGeneratePreviews,
|
||||
};
|
||||
|
||||
enum IPCReply
|
||||
{
|
||||
FinishedGeneratePreviews,
|
||||
};
|
||||
|
||||
#endif // IPC_H
|
||||
|
@ -1,27 +0,0 @@
|
||||
#include <QDataStream>
|
||||
#include "ipcclient.h"
|
||||
|
||||
IPCClient::IPCClient(QString socketPath)
|
||||
{
|
||||
this->socketPath = socketPath;
|
||||
}
|
||||
|
||||
bool IPCClient::sendCommand(IPCCommand command, QStringList args)
|
||||
{
|
||||
bool result = false;
|
||||
QLocalSocket socket;
|
||||
socket.connectToServer(socketPath);
|
||||
if(socket.isOpen() && socket.isWritable())
|
||||
{
|
||||
QDataStream stream(&socket);
|
||||
stream << command;
|
||||
stream << args;
|
||||
socket.flush();
|
||||
result = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
qDebug() << "Not connected to IPC server";
|
||||
}
|
||||
return result;
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
#ifndef IPCCLIENT_H
|
||||
#define IPCCLIENT_H
|
||||
#include <QLocalSocket>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include "ipc.h"
|
||||
|
||||
class IPCClient
|
||||
{
|
||||
private:
|
||||
QString socketPath;
|
||||
|
||||
public:
|
||||
IPCClient(QString socketPath);
|
||||
bool sendCommand(IPCCommand command, QStringList args);
|
||||
};
|
||||
|
||||
#endif // IPCCLIENT_H
|
130
gui/ipcpreviewclient.cpp
Normal file
130
gui/ipcpreviewclient.cpp
Normal file
@ -0,0 +1,130 @@
|
||||
#include <QLocalSocket>
|
||||
#include <QApplication>
|
||||
#include "ipc.h"
|
||||
#include "ipcpreviewclient.h"
|
||||
#include "previewresultpdf.h"
|
||||
#include "previewresultplaintext.h"
|
||||
|
||||
bool IPCPreviewClient::connect()
|
||||
{
|
||||
if(socket->state() == QLocalSocket::ConnectedState)
|
||||
{
|
||||
socket->disconnectFromServer();
|
||||
if(socket->state() == QLocalSocket::ConnectedState)
|
||||
{
|
||||
socket->waitForDisconnected(100);
|
||||
}
|
||||
}
|
||||
socket->connectToServer(socketPath);
|
||||
socket->waitForConnected(100);
|
||||
return socket->state() == QLocalSocket::ConnectedState;
|
||||
}
|
||||
|
||||
QSharedPointer<PreviewResult> IPCPreviewClient::deserialize(QByteArray &array)
|
||||
{
|
||||
QDataStream stream{&array, QIODevice::ReadOnly};
|
||||
|
||||
PreviewResultType type;
|
||||
stream >> type;
|
||||
if(type == PreviewResultType::PDF)
|
||||
{
|
||||
return PreviewResultPdf::deserialize(array);
|
||||
}
|
||||
if(type == PreviewResultType::PlainText)
|
||||
{
|
||||
return PreviewResultPlainText::deserialize(array);
|
||||
}
|
||||
return QSharedPointer<PreviewResult>(nullptr);
|
||||
}
|
||||
|
||||
IPCPreviewClient::IPCPreviewClient()
|
||||
{
|
||||
this->socket = new QLocalSocket(this);
|
||||
}
|
||||
|
||||
void IPCPreviewClient::setSocketPath(QString socketPath)
|
||||
{
|
||||
this->socketPath = socketPath;
|
||||
}
|
||||
|
||||
void IPCPreviewClient::startGeneration(RenderConfig config, const QVector<RenderTarget> &targets)
|
||||
{
|
||||
this->start(config, targets);
|
||||
}
|
||||
|
||||
void IPCPreviewClient::start(RenderConfig config, const QVector<RenderTarget> &targets)
|
||||
{
|
||||
if(targets.count() == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if(!connect() || !socket->isOpen())
|
||||
{
|
||||
emit error("Could not connect to IPC worker");
|
||||
return;
|
||||
}
|
||||
|
||||
if(socket->isOpen() && socket->isWritable())
|
||||
{
|
||||
QDataStream stream(socket);
|
||||
stream << GeneratePreviews;
|
||||
stream << config;
|
||||
stream << targets;
|
||||
socket->flush();
|
||||
|
||||
int numTarget = 0;
|
||||
if(socket->isOpen() && socket->isReadable() && socket->state() == QLocalSocket::ConnectedState)
|
||||
{
|
||||
do
|
||||
{
|
||||
socket->waitForReadyRead(100);
|
||||
stream.startTransaction();
|
||||
stream >> numTarget;
|
||||
} while(!stream.commitTransaction() && socket->state() == QLocalSocket::ConnectedState);
|
||||
if(numTarget != targets.count())
|
||||
{
|
||||
emit error("IPC Error: Server reports less targets than it should");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
emit error("Error while trying to process previews: " + socket->errorString());
|
||||
return;
|
||||
}
|
||||
|
||||
int processed = 0;
|
||||
++this->currentPreviewGeneration;
|
||||
while(socket->isOpen() && socket->isReadable() && processed < targets.count())
|
||||
{
|
||||
QByteArray array;
|
||||
do
|
||||
{
|
||||
socket->waitForReadyRead(100);
|
||||
stream.startTransaction();
|
||||
stream >> array;
|
||||
} while(!stream.commitTransaction() && socket->state() == QLocalSocket::ConnectedState);
|
||||
emit previewReceived(deserialize(array), this->currentPreviewGeneration);
|
||||
++processed;
|
||||
}
|
||||
if(processed != targets.count())
|
||||
{
|
||||
emit error("IPC worker didn't send enough previews. This is a bug, please report");
|
||||
}
|
||||
}
|
||||
socket->disconnectFromServer();
|
||||
emit finished();
|
||||
}
|
||||
|
||||
void IPCPreviewClient::stopGeneration()
|
||||
{
|
||||
if(!connect() || !socket->isOpen())
|
||||
{
|
||||
emit error("Could not connect to IPC worker");
|
||||
return;
|
||||
}
|
||||
QDataStream stream(socket);
|
||||
stream << StopGeneratePreviews;
|
||||
socket->flush();
|
||||
}
|
37
gui/ipcpreviewclient.h
Normal file
37
gui/ipcpreviewclient.h
Normal file
@ -0,0 +1,37 @@
|
||||
#ifndef IPCPREVIEWCLIENT_H
|
||||
#define IPCPREVIEWCLIENT_H
|
||||
#include <QObject>
|
||||
#include <QLocalSocket>
|
||||
#include "previewresult.h"
|
||||
#include "renderconfig.h"
|
||||
#include "rendertarget.h"
|
||||
|
||||
class IPCPreviewClient : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
unsigned int currentPreviewGeneration = 1;
|
||||
QLocalSocket *socket;
|
||||
QString socketPath;
|
||||
|
||||
bool connect();
|
||||
QSharedPointer<PreviewResult> deserialize(QByteArray &array);
|
||||
|
||||
public:
|
||||
IPCPreviewClient();
|
||||
~IPCPreviewClient()
|
||||
{
|
||||
delete socket;
|
||||
}
|
||||
void setSocketPath(QString socketPath);
|
||||
public slots:
|
||||
void start(RenderConfig config, const QVector<RenderTarget> &targets);
|
||||
void startGeneration(RenderConfig config, const QVector<RenderTarget> &targets);
|
||||
void stopGeneration();
|
||||
signals:
|
||||
void previewReceived(QSharedPointer<PreviewResult> previewResult, unsigned int currentPreviewGeneration);
|
||||
void finished();
|
||||
void error(QString);
|
||||
};
|
||||
|
||||
#endif // IPCPREVIEWCLIENT_H
|
24
gui/ipcpreviewworker.cpp
Normal file
24
gui/ipcpreviewworker.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include <QtConcurrent>
|
||||
#include "ipcpreviewworker.h"
|
||||
#include "previewgeneratormapfunctor.h"
|
||||
IPCPreviewWorker::IPCPreviewWorker()
|
||||
{
|
||||
this->connect(&previewWorkerWatcher, &QFutureWatcher<QByteArray>::resultReadyAt, this,
|
||||
[this](int index) { emit previewGenerated(previewWorkerWatcher.resultAt(index)); });
|
||||
connect(&previewWorkerWatcher, &QFutureWatcher<QByteArray>::finished, this, [this] { emit finished(); });
|
||||
}
|
||||
|
||||
void IPCPreviewWorker::start(RenderConfig config, const QVector<RenderTarget> &targets, QLocalSocket *peer)
|
||||
{
|
||||
stop();
|
||||
auto mapFunctor = PreviewGeneratorMapFunctor();
|
||||
mapFunctor.setRenderConfig(config);
|
||||
|
||||
previewWorkerWatcher.setFuture(QtConcurrent::mapped(targets, mapFunctor));
|
||||
}
|
||||
|
||||
void IPCPreviewWorker::stop()
|
||||
{
|
||||
previewWorkerWatcher.cancel();
|
||||
previewWorkerWatcher.waitForFinished();
|
||||
}
|
24
gui/ipcpreviewworker.h
Normal file
24
gui/ipcpreviewworker.h
Normal file
@ -0,0 +1,24 @@
|
||||
#ifndef IPCPREVIEWWORKER_H
|
||||
#define IPCPREVIEWWORKER_H
|
||||
#include <QLocalSocket>
|
||||
#include <QFutureWatcher>
|
||||
#include "renderconfig.h"
|
||||
#include "rendertarget.h"
|
||||
#include "previewgenerator.h"
|
||||
|
||||
class IPCPreviewWorker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
QFutureWatcher<QByteArray> previewWorkerWatcher;
|
||||
|
||||
public:
|
||||
IPCPreviewWorker();
|
||||
void start(RenderConfig config, const QVector<RenderTarget> &targets, QLocalSocket *peer);
|
||||
void stop();
|
||||
signals:
|
||||
void previewGenerated(QByteArray);
|
||||
void finished();
|
||||
};
|
||||
|
||||
#endif // IPCPREVIEWWORKER_H
|
@ -6,10 +6,20 @@
|
||||
#include <QLocalSocket>
|
||||
#include <QDataStream>
|
||||
#include "ipcserver.h"
|
||||
#include "common.h"
|
||||
#include "databasefactory.h"
|
||||
#include "../shared/logger.h"
|
||||
#include "renderconfig.h"
|
||||
#include "rendertarget.h"
|
||||
#include "ipcpreviewworker.h"
|
||||
|
||||
IpcServer::IpcServer()
|
||||
{
|
||||
/* Only 1, we are doing work for the GUI, not a service for general availability */
|
||||
this->spawningServer.setMaxPendingConnections(1);
|
||||
connect(&this->spawningServer, &QLocalServer::newConnection, this, &IpcServer::spawnerNewConnection);
|
||||
connect(&this->previewWorker, &IPCPreviewWorker::previewGenerated, this, &IpcServer::handlePreviewGenerated);
|
||||
connect(&this->previewWorker, &IPCPreviewWorker::finished, this, [this] { this->currentSocket->flush(); });
|
||||
}
|
||||
|
||||
bool IpcServer::startSpawner(QString socketPath)
|
||||
@ -18,71 +28,46 @@ bool IpcServer::startSpawner(QString socketPath)
|
||||
return this->spawningServer.listen(socketPath);
|
||||
}
|
||||
|
||||
bool IpcServer::docOpen(QString path, int pagenum)
|
||||
{
|
||||
QSettings settings;
|
||||
QString command = settings.value("pdfviewer").toString();
|
||||
if(command != "" && command.contains("%p") && command.contains("%f"))
|
||||
{
|
||||
QStringList splitted = command.split(" ");
|
||||
if(splitted.size() > 1)
|
||||
{
|
||||
QString cmd = splitted[0];
|
||||
QStringList args = splitted.mid(1);
|
||||
args.replaceInStrings("%f", path);
|
||||
args.replaceInStrings("%p", QString::number(pagenum));
|
||||
|
||||
QProcess::startDetached(cmd, args);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IpcServer::fileOpen(QString path)
|
||||
{
|
||||
return QDesktopServices::openUrl(QUrl::fromLocalFile(path));
|
||||
}
|
||||
|
||||
void IpcServer::spawnerNewConnection()
|
||||
{
|
||||
QScopedPointer<QLocalSocket> socket{this->spawningServer.nextPendingConnection()};
|
||||
if(!socket.isNull())
|
||||
QLocalSocket *socket = this->spawningServer.nextPendingConnection();
|
||||
connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
|
||||
this->currentSocket = socket;
|
||||
if(socket != nullptr)
|
||||
{
|
||||
if(!socket->waitForReadyRead())
|
||||
{
|
||||
return;
|
||||
}
|
||||
QDataStream stream(socket.get());
|
||||
QDataStream stream(socket);
|
||||
IPCCommand command;
|
||||
QStringList args;
|
||||
stream >> command;
|
||||
stream >> args;
|
||||
if(args.size() < 1)
|
||||
if(command == GeneratePreviews)
|
||||
{
|
||||
stream << "invalid";
|
||||
return;
|
||||
}
|
||||
if(command == DocOpen)
|
||||
{
|
||||
if(args.size() < 2)
|
||||
RenderConfig renderConfig;
|
||||
QVector<RenderTarget> targets;
|
||||
do
|
||||
{
|
||||
stream << "invalid";
|
||||
return;
|
||||
}
|
||||
docOpen(args[0], args[1].toInt());
|
||||
/* TODO: this is not entirely robust */
|
||||
socket->waitForReadyRead(100);
|
||||
stream.startTransaction();
|
||||
stream >> renderConfig >> targets;
|
||||
} while(!stream.commitTransaction() && socket->state() == QLocalSocket::ConnectedState);
|
||||
|
||||
stream << targets.count();
|
||||
socket->flush();
|
||||
previewWorker.start(renderConfig, targets, socket);
|
||||
}
|
||||
if(command == FileOpen)
|
||||
if(command == StopGeneratePreviews)
|
||||
{
|
||||
if(args.size() < 1)
|
||||
{
|
||||
stream << "invalid";
|
||||
return;
|
||||
}
|
||||
fileOpen(args[0]);
|
||||
previewWorker.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IpcServer::handlePreviewGenerated(QByteArray ba)
|
||||
{
|
||||
QDataStream stream{this->currentSocket};
|
||||
stream << ba;
|
||||
this->currentSocket->flush();
|
||||
}
|
||||
|
@ -3,15 +3,20 @@
|
||||
#include <QString>
|
||||
#include <QLocalServer>
|
||||
#include "ipc.h"
|
||||
#include "filesaver.h"
|
||||
#include "ipcpreviewworker.h"
|
||||
|
||||
class IpcServer : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
IPCPreviewWorker previewWorker;
|
||||
QLocalServer spawningServer;
|
||||
bool docOpen(QString path, int pagenum);
|
||||
bool fileOpen(QString path);
|
||||
QLocalSocket *currentSocket = nullptr;
|
||||
SaveFileResult addFile(QString file);
|
||||
private slots:
|
||||
void spawnerNewConnection();
|
||||
void handlePreviewGenerated(QByteArray ba);
|
||||
|
||||
public:
|
||||
IpcServer();
|
||||
|
126
gui/main.cpp
126
gui/main.cpp
@ -5,54 +5,41 @@
|
||||
#include <QProcess>
|
||||
#include <QDir>
|
||||
#include <QCommandLineParser>
|
||||
#include <QFileInfo>
|
||||
|
||||
#include "mainwindow.h"
|
||||
#include "searchresult.h"
|
||||
#include "previewresultpdf.h"
|
||||
#include "../shared/common.h"
|
||||
#include "../shared/sandboxedprocessor.h"
|
||||
#include "../submodules/exile.h/exile.h"
|
||||
#include "ipcserver.h"
|
||||
|
||||
void enableSandbox(QString socketPath)
|
||||
void enableIpcSandbox()
|
||||
{
|
||||
struct exile_policy *policy = exile_init_policy();
|
||||
struct exile_policy *policy = exile_create_policy();
|
||||
if(policy == NULL)
|
||||
{
|
||||
qCritical() << "Failed to init policy for sandbox";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
QDir dir;
|
||||
dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation));
|
||||
dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
|
||||
policy->namespace_options = EXILE_UNSHARE_USER | EXILE_UNSHARE_MOUNT | EXILE_UNSHARE_NETWORK;
|
||||
policy->no_new_privs = 1;
|
||||
policy->drop_caps = 1;
|
||||
policy->vow_promises =
|
||||
exile_vows_from_str("thread cpath wpath rpath unix stdio prot_exec proc shm fsnotify ioctl error");
|
||||
policy->mount_path_policies_to_chroot = 1;
|
||||
|
||||
std::string appDataLocation = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation).toStdString();
|
||||
std::string cacheDataLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation).toStdString();
|
||||
QString ipcSocketPath = Common::ipcSocketPath();
|
||||
QFileInfo info{ipcSocketPath};
|
||||
QString ipcSocketPathDir = info.absolutePath();
|
||||
std::string stdIpcSocketPath = ipcSocketPathDir.toStdString();
|
||||
|
||||
std::string sockPath = socketPath.toStdString();
|
||||
policy->namespace_options = EXILE_UNSHARE_NETWORK | EXILE_UNSHARE_USER;
|
||||
policy->vow_promises = EXILE_SYSCALL_VOW_THREAD | EXILE_SYSCALL_VOW_CPATH | EXILE_SYSCALL_VOW_WPATH |
|
||||
EXILE_SYSCALL_VOW_RPATH | EXILE_SYSCALL_VOW_UNIX | EXILE_SYSCALL_VOW_STDIO |
|
||||
EXILE_SYSCALL_VOW_PROT_EXEC | EXILE_SYSCALL_VOW_PROC | EXILE_SYSCALL_VOW_SHM |
|
||||
EXILE_SYSCALL_VOW_FSNOTIFY | EXILE_SYSCALL_VOW_IOCTL;
|
||||
|
||||
if(exile_append_path_policy(policy, EXILE_FS_ALLOW_ALL_READ | EXILE_FS_ALLOW_REMOVE_FILE, "/") != 0)
|
||||
{
|
||||
qCritical() << "Failed to append a path to the path policy";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if(exile_append_path_policy(policy, EXILE_FS_ALLOW_ALL_READ | EXILE_FS_ALLOW_ALL_WRITE, appDataLocation.c_str()) !=
|
||||
0)
|
||||
{
|
||||
qCritical() << "Failed to append a path to the path policy";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
if(exile_append_path_policy(policy, EXILE_FS_ALLOW_ALL_READ | EXILE_FS_ALLOW_ALL_WRITE,
|
||||
cacheDataLocation.c_str()) != 0)
|
||||
{
|
||||
qCritical() << "Failed to append a path to the path policy";
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
/* ALLOW_EXEC is needed for fallback, not in landlock mode. It does not allow executing anything though here
|
||||
* due to the vows */
|
||||
exile_append_path_policies(policy, EXILE_FS_ALLOW_ALL_READ | EXILE_FS_ALLOW_EXEC, "/");
|
||||
exile_append_path_policies(policy, EXILE_FS_ALLOW_ALL_READ | EXILE_FS_ALLOW_ALL_WRITE | EXILE_FS_ALLOW_EXEC,
|
||||
stdIpcSocketPath.c_str());
|
||||
int ret = exile_enable_policy(policy);
|
||||
if(ret != 0)
|
||||
{
|
||||
@ -61,32 +48,71 @@ void enableSandbox(QString socketPath)
|
||||
}
|
||||
exile_free_policy(policy);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QString socketPath = "/tmp/looqs-spawner";
|
||||
QString socketPath = Common::ipcSocketPath();
|
||||
if(argc > 1)
|
||||
{
|
||||
QString arg = argv[1];
|
||||
if(arg == "ipc")
|
||||
{
|
||||
Common::setupAppInfo();
|
||||
if(Common::noSandboxModeRequested())
|
||||
{
|
||||
qInfo() << "Launching with no sandbox!" << Qt::endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
enableIpcSandbox();
|
||||
}
|
||||
QApplication a(argc, argv);
|
||||
|
||||
IpcServer *ipcserver = new IpcServer();
|
||||
qDebug() << "Launching IPC Server";
|
||||
if(!ipcserver->startSpawner(socketPath))
|
||||
{
|
||||
qCritical() << "Error failed to spawn";
|
||||
qCritical() << "Error failed to spawn" << Qt::endl;
|
||||
return 1;
|
||||
}
|
||||
qDebug() << "Launched IPC Server";
|
||||
return a.exec();
|
||||
}
|
||||
if(arg == "process")
|
||||
{
|
||||
Common::setupAppInfo();
|
||||
QCoreApplication a(argc, argv);
|
||||
|
||||
QStringList args = a.arguments();
|
||||
if(args.length() < 3)
|
||||
{
|
||||
qDebug() << "Filename is required";
|
||||
return 1;
|
||||
}
|
||||
|
||||
QString file = args.at(2);
|
||||
SandboxedProcessor processor(file);
|
||||
return processor.process();
|
||||
}
|
||||
}
|
||||
QString ipcSocketPath = Common::ipcSocketPath();
|
||||
QFileInfo info{ipcSocketPath};
|
||||
QString ipcSocketPathDir = info.absolutePath();
|
||||
|
||||
QDir dir;
|
||||
if(!dir.mkpath(ipcSocketPathDir))
|
||||
{
|
||||
qCritical() << "Failed to create dir for ipc socket" << Qt::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
QProcess process;
|
||||
QStringList args;
|
||||
args << "ipc";
|
||||
if(!process.startDetached("/proc/self/exe", args))
|
||||
process.setProcessChannelMode(QProcess::ForwardedChannels);
|
||||
|
||||
process.start("/proc/self/exe", args);
|
||||
if(!process.waitForStarted(5000))
|
||||
{
|
||||
QString errorMsg = "Failed to start IPC server";
|
||||
qDebug() << errorMsg;
|
||||
@ -102,17 +128,6 @@ int main(int argc, char *argv[])
|
||||
}
|
||||
parser.parse(appArgs);
|
||||
|
||||
if(!parser.isSet("no-sandbox"))
|
||||
{
|
||||
enableSandbox(socketPath);
|
||||
qInfo() << "Sandbox: on";
|
||||
}
|
||||
else
|
||||
{
|
||||
qInfo() << "Sandbox: off";
|
||||
}
|
||||
// Keep this post sandbox, afterwards does not work (suspect due to threads, but unconfirmed)
|
||||
QApplication a(argc, argv);
|
||||
try
|
||||
{
|
||||
Common::ensureConfigured();
|
||||
@ -123,13 +138,20 @@ int main(int argc, char *argv[])
|
||||
QMessageBox::critical(nullptr, "Error", e.message);
|
||||
return 1;
|
||||
}
|
||||
QApplication a(argc, argv);
|
||||
a.setWindowIcon(QIcon(":/looqs.svg"));
|
||||
QObject::connect(&a, &QApplication::aboutToQuit, &process, &QProcess::kill);
|
||||
|
||||
qRegisterMetaType<QVector<SearchResult>>("QVector<SearchResult>");
|
||||
qRegisterMetaType<QVector<PreviewResultPdf>>("QVector<PreviewResultPdf>");
|
||||
qRegisterMetaType<PreviewResultPdf>("PreviewResultPdf");
|
||||
|
||||
IPCClient client{socketPath};
|
||||
MainWindow w{0, client};
|
||||
w.showMaximized();
|
||||
|
||||
return a.exec();
|
||||
qRegisterMetaType<FileScanResult>("FileScanResult");
|
||||
qRegisterMetaType<RenderConfig>("RenderConfig");
|
||||
qRegisterMetaType<QVector<RenderTarget>>("QVector<RenderTarget>");
|
||||
qRegisterMetaType<QSharedPointer<PreviewResult>>("QSharedPointer<PreviewResult>");
|
||||
MainWindow *w = new MainWindow{0, socketPath};
|
||||
w->showMaximized();
|
||||
int ret = a.exec();
|
||||
process.waitForFinished(1000);
|
||||
return ret;
|
||||
}
|
||||
|
@ -11,27 +11,59 @@
|
||||
#include <QProcess>
|
||||
#include <QComboBox>
|
||||
#include <QtConcurrent/QtConcurrent>
|
||||
#include <QMessageBox>
|
||||
#include <QFileDialog>
|
||||
#include <QScreen>
|
||||
#include <QProgressDialog>
|
||||
#include "mainwindow.h"
|
||||
#include "ui_mainwindow.h"
|
||||
#include "clicklabel.h"
|
||||
#include "../shared/sqlitesearch.h"
|
||||
#include "../shared/looqsgeneralexception.h"
|
||||
#include "../shared/common.h"
|
||||
#include "ipcpreviewclient.h"
|
||||
#include "previewgenerator.h"
|
||||
|
||||
MainWindow::MainWindow(QWidget *parent, IPCClient &client) : QMainWindow(parent), ui(new Ui::MainWindow)
|
||||
MainWindow::MainWindow(QWidget *parent, QString socketPath)
|
||||
: QMainWindow(parent), ui(new Ui::MainWindow), progressDialog(this)
|
||||
{
|
||||
this->progressDialog.cancel(); // because constructing it shows it, quite weird
|
||||
ui->setupUi(this);
|
||||
setWindowTitle(QCoreApplication::applicationName());
|
||||
this->ipcClient = &client;
|
||||
this->ipcPreviewClient.moveToThread(&this->ipcClientThread);
|
||||
this->ipcPreviewClient.setSocketPath(socketPath);
|
||||
|
||||
connect(&ipcPreviewClient, &IPCPreviewClient::previewReceived, this, &MainWindow::previewReceived,
|
||||
Qt::QueuedConnection);
|
||||
connect(&ipcPreviewClient, &IPCPreviewClient::finished, this,
|
||||
[&]
|
||||
{
|
||||
this->ui->previewProcessBar->setValue(this->ui->previewProcessBar->maximum());
|
||||
this->ui->spinPreviewPage->setEnabled(true);
|
||||
});
|
||||
connect(&ipcPreviewClient, &IPCPreviewClient::error, this,
|
||||
[this](QString msg)
|
||||
{
|
||||
qCritical() << msg << Qt::endl;
|
||||
QMessageBox::critical(this, "IPC error", msg);
|
||||
});
|
||||
|
||||
connect(this, &MainWindow::startIpcPreviews, &ipcPreviewClient, &IPCPreviewClient::startGeneration,
|
||||
Qt::QueuedConnection);
|
||||
connect(this, &MainWindow::stopIpcPreviews, &ipcPreviewClient, &IPCPreviewClient::stopGeneration,
|
||||
Qt::QueuedConnection);
|
||||
this->ipcClientThread.start();
|
||||
QSettings settings;
|
||||
|
||||
db = QSqlDatabase::addDatabase("QSQLITE");
|
||||
db.setDatabaseName(Common::databasePath());
|
||||
if(!db.open())
|
||||
{
|
||||
qDebug() << "failed to open database";
|
||||
throw std::runtime_error("Failed to open database");
|
||||
}
|
||||
this->dbFactory = new DatabaseFactory(Common::databasePath());
|
||||
|
||||
db = this->dbFactory->forCurrentThread();
|
||||
this->dbService = new SqliteDbService(*this->dbFactory);
|
||||
this->indexSyncer = new IndexSyncer(*this->dbService);
|
||||
this->indexSyncer->moveToThread(&this->syncerThread);
|
||||
|
||||
indexer = new Indexer(*(this->dbService));
|
||||
indexer->setParent(this);
|
||||
connectSignals();
|
||||
ui->treeResultsList->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
|
||||
ui->tabWidget->setCurrentIndex(0);
|
||||
@ -41,6 +73,33 @@ MainWindow::MainWindow(QWidget *parent, IPCClient &client) : QMainWindow(parent)
|
||||
ui->comboScale->setCurrentText(settings.value("currentScale").toString());
|
||||
previewsPerPage = settings.value("previewsPerPage", 20).toInt();
|
||||
ui->spinPreviewPage->setMinimum(1);
|
||||
|
||||
QStringList indexPaths = settings.value("indexPaths").toStringList();
|
||||
ui->lstPaths->addItems(indexPaths);
|
||||
|
||||
QString ignorePatterns = settings.value("ignorePatterns").toString();
|
||||
ui->txtIgnorePatterns->setText(ignorePatterns);
|
||||
|
||||
ui->spinPreviewPage->setValue(1);
|
||||
ui->spinPreviewPage->setMinimum(1);
|
||||
}
|
||||
|
||||
void MainWindow::addPathToIndex()
|
||||
{
|
||||
QString path = this->ui->txtPathScanAdd->text();
|
||||
QFileInfo fileInfo{path};
|
||||
if(!fileInfo.exists(path))
|
||||
{
|
||||
QMessageBox::critical(this, "Invalid path", "Path does not seem to exist");
|
||||
return;
|
||||
}
|
||||
if(!fileInfo.isReadable())
|
||||
{
|
||||
QMessageBox::critical(this, "Invalid path", "Path cannot be read");
|
||||
return;
|
||||
}
|
||||
this->ui->lstPaths->addItem(path);
|
||||
this->ui->txtPathScanAdd->clear();
|
||||
}
|
||||
|
||||
void MainWindow::connectSignals()
|
||||
@ -60,10 +119,6 @@ void MainWindow::connectSignals()
|
||||
handleSearchError(e.message);
|
||||
}
|
||||
});
|
||||
connect(&previewWorkerWatcher, &QFutureWatcher<QSharedPointer<PreviewResult>>::resultReadyAt, this,
|
||||
[&](int index) { previewReceived(previewWorkerWatcher.resultAt(index)); });
|
||||
connect(&previewWorkerWatcher, &QFutureWatcher<QSharedPointer<PreviewResult>>::progressValueChanged,
|
||||
ui->previewProcessBar, &QProgressBar::setValue);
|
||||
connect(ui->treeResultsList, &QTreeWidget::itemActivated, this, &MainWindow::treeSearchItemActivated);
|
||||
connect(ui->treeResultsList, &QTreeWidget::customContextMenuRequested, this,
|
||||
&MainWindow::showSearchResultsContextMenu);
|
||||
@ -71,24 +126,190 @@ void MainWindow::connectSignals()
|
||||
connect(ui->comboScale, qOverload<int>(&QComboBox::currentIndexChanged), this, &MainWindow::comboScaleChanged);
|
||||
connect(ui->spinPreviewPage, qOverload<int>(&QSpinBox::valueChanged), this,
|
||||
&MainWindow::spinPreviewPageValueChanged);
|
||||
|
||||
connect(ui->btnAddPath, &QPushButton::clicked, this, &MainWindow::addPathToIndex);
|
||||
connect(ui->txtPathScanAdd, &QLineEdit::returnPressed, this, &MainWindow::addPathToIndex);
|
||||
connect(ui->btnStartIndexing, &QPushButton::clicked, this, &MainWindow::startIndexing);
|
||||
|
||||
connect(this->indexer, &Indexer::pathsCountChanged, this,
|
||||
[&](int number)
|
||||
{
|
||||
ui->lblSearchResults->setText("Found paths: " + QString::number(number));
|
||||
ui->lblPathsFoundValue->setText(QString::number(number));
|
||||
ui->previewProcessBar->setMaximum(number);
|
||||
});
|
||||
connect(this->indexer, &Indexer::indexProgress, this,
|
||||
|
||||
[&](int number, unsigned int added, unsigned int skipped, unsigned int failed, unsigned int totalCount)
|
||||
{
|
||||
ui->lblSearchResults->setText("Processed " + QString::number(number) + " files");
|
||||
ui->previewProcessBar->setValue(number);
|
||||
ui->previewProcessBar->setMaximum(totalCount);
|
||||
ui->lblAddedValue->setText(QString::number(added));
|
||||
ui->lblSkippedValue->setText(QString::number(skipped));
|
||||
ui->lblFailedValue->setText(QString::number(failed));
|
||||
});
|
||||
|
||||
connect(this->indexer, &Indexer::finished, this, &MainWindow::finishIndexing);
|
||||
|
||||
connect(ui->lstPaths->selectionModel(), &QItemSelectionModel::selectionChanged, this,
|
||||
[&](const QItemSelection &selected, const QItemSelection &deselected)
|
||||
{ ui->btnDeletePath->setEnabled(this->ui->lstPaths->selectedItems().count() > 0); });
|
||||
|
||||
connect(ui->btnDeletePath, &QPushButton::clicked, this, [&] { qDeleteAll(ui->lstPaths->selectedItems()); });
|
||||
connect(ui->btnChoosePath, &QPushButton::clicked, this,
|
||||
[&]
|
||||
{
|
||||
QFileDialog dialog(nullptr);
|
||||
dialog.setFileMode(QFileDialog::Directory);
|
||||
dialog.setOptions(QFileDialog::ShowDirsOnly);
|
||||
if(dialog.exec())
|
||||
{
|
||||
auto paths = dialog.selectedFiles();
|
||||
if(paths.size() == 1)
|
||||
{
|
||||
ui->lstPaths->addItem(paths[0]);
|
||||
}
|
||||
}
|
||||
});
|
||||
connect(
|
||||
ui->menuAboutAction, &QAction::triggered, this,
|
||||
[this](bool checked)
|
||||
{
|
||||
QString html = "<h2>looqs</h2>";
|
||||
html += "Full-text search with previews for your files<br><br>";
|
||||
html += "Copyright (c) 2018-2022: Albert Schwarzkopf<br><br>";
|
||||
html += QString("Version: %1<br><br>").arg(Common::versionText());
|
||||
html += "Contact: looqs at quitesimple dot org<br><br>";
|
||||
html += "Website: <a href=\"https://quitesimple.org\">https://quitesimple.org</a><br><br>";
|
||||
html +=
|
||||
"Source code: <a "
|
||||
"href=\"https://github.com/quitesimpleorg/looqs\">https://github.com/quitesimpleorg/looqs</a><br><br>";
|
||||
html += "License: GPLv3<br><br><br>";
|
||||
html += "looqs is open source and free of charge in the hope it will be useful. The author(s) do not "
|
||||
"give any warranty. In the unlikely event of any damage, the author(s) cannot be held responsible. "
|
||||
"You are using looqs at your own risk";
|
||||
|
||||
QMessageBox::about(this, "About looqs", html);
|
||||
});
|
||||
connect(ui->menuOpenConfigInTextEditorAction, &QAction::triggered, this,
|
||||
[this](bool checked)
|
||||
{
|
||||
QSettings setting;
|
||||
QDesktopServices::openUrl(setting.fileName());
|
||||
});
|
||||
connect(ui->menuAboutQtAction, &QAction::triggered, this,
|
||||
[this](bool checked) { QMessageBox::aboutQt(this, "About Qt"); });
|
||||
connect(ui->menuSyncIndexAction, &QAction::triggered, this, &MainWindow::startIndexSync);
|
||||
connect(indexSyncer, &IndexSyncer::finished, this,
|
||||
[&](unsigned int totalUpdated, unsigned int totalDeleted, unsigned int totalErrored)
|
||||
{
|
||||
this->progressDialog.cancel();
|
||||
|
||||
QMessageBox::information(
|
||||
this, "Syncing finished",
|
||||
QString("Syncing finished\n\nTotal updated: %1\nTotal deleted: %2\nTotal errors: %3\n")
|
||||
.arg(QString::number(totalUpdated))
|
||||
.arg(QString::number(totalDeleted))
|
||||
.arg(QString::number(totalErrored)));
|
||||
});
|
||||
connect(this, &MainWindow::beginIndexSync, indexSyncer, &IndexSyncer::sync);
|
||||
connect(&this->progressDialog, &QProgressDialog::canceled, indexSyncer, &IndexSyncer::cancel);
|
||||
}
|
||||
|
||||
void MainWindow::startIndexSync()
|
||||
{
|
||||
progressDialog.setWindowTitle("Syncing");
|
||||
progressDialog.setLabelText("Syncing - this might take a moment, please wait");
|
||||
progressDialog.setWindowModality(Qt::ApplicationModal);
|
||||
progressDialog.setMinimum(0);
|
||||
progressDialog.setMaximum(0);
|
||||
progressDialog.setValue(0);
|
||||
progressDialog.open();
|
||||
|
||||
indexSyncer->setKeepGoing(true);
|
||||
indexSyncer->setVerbose(false);
|
||||
indexSyncer->setDryRun(false);
|
||||
indexSyncer->setRemoveDeletedFromIndex(true);
|
||||
|
||||
this->syncerThread.start();
|
||||
|
||||
emit beginIndexSync();
|
||||
}
|
||||
void MainWindow::spinPreviewPageValueChanged(int val)
|
||||
{
|
||||
makePreviews(val);
|
||||
}
|
||||
|
||||
void MainWindow::startIndexing()
|
||||
{
|
||||
if(this->indexer->isRunning())
|
||||
{
|
||||
ui->btnStartIndexing->setEnabled(false);
|
||||
ui->btnStartIndexing->setText("Start indexing");
|
||||
this->indexer->requestCancellation();
|
||||
return;
|
||||
}
|
||||
|
||||
ui->previewsTab->setEnabled(false);
|
||||
ui->resultsTab->setEnabled(false);
|
||||
ui->txtPathScanAdd->setEnabled(false);
|
||||
ui->txtSearch->setEnabled(false);
|
||||
ui->previewProcessBar->setValue(0);
|
||||
ui->previewProcessBar->setVisible(true);
|
||||
|
||||
QVector<QString> paths;
|
||||
QStringList pathSettingsValue;
|
||||
for(int i = 0; i < ui->lstPaths->count(); i++)
|
||||
{
|
||||
QString path = ui->lstPaths->item(i)->text();
|
||||
paths.append(path);
|
||||
pathSettingsValue.append(path);
|
||||
}
|
||||
this->indexer->setTargetPaths(paths);
|
||||
QString ignorePatterns = ui->txtIgnorePatterns->text();
|
||||
this->indexer->setIgnorePattern(ignorePatterns.split(";"));
|
||||
this->indexer->beginIndexing();
|
||||
QSettings settings;
|
||||
settings.setValue("indexPaths", pathSettingsValue);
|
||||
settings.setValue("ignorePatterns", ignorePatterns);
|
||||
ui->btnStartIndexing->setText("Stop indexing");
|
||||
}
|
||||
|
||||
void MainWindow::finishIndexing()
|
||||
{
|
||||
IndexResult result = this->indexer->getResult();
|
||||
|
||||
ui->lblSearchResults->setText("Indexing finished");
|
||||
ui->previewProcessBar->setValue(ui->previewProcessBar->maximum());
|
||||
ui->lblFailedValue->setText(QString::number(result.erroredPaths));
|
||||
ui->lblSkippedValue->setText(QString::number(result.skippedPaths));
|
||||
ui->lblAddedValue->setText(QString::number(result.addedPaths));
|
||||
ui->btnStartIndexing->setEnabled(true);
|
||||
ui->btnStartIndexing->setText("Start indexing");
|
||||
ui->previewsTab->setEnabled(true);
|
||||
ui->resultsTab->setEnabled(true);
|
||||
ui->txtPathScanAdd->setEnabled(true);
|
||||
ui->txtSearch->setEnabled(true);
|
||||
}
|
||||
|
||||
void MainWindow::comboScaleChanged(int i)
|
||||
{
|
||||
QSettings scaleSetting;
|
||||
scaleSetting.setValue("currentScale", ui->comboScale->currentText());
|
||||
makePreviews(ui->spinPreviewPage->value());
|
||||
}
|
||||
|
||||
bool MainWindow::previewTabActive()
|
||||
{
|
||||
return ui->tabWidget->currentIndex() == 1;
|
||||
}
|
||||
|
||||
bool MainWindow::indexerTabActive()
|
||||
{
|
||||
return ui->tabWidget->currentIndex() == 2;
|
||||
}
|
||||
|
||||
void MainWindow::keyPressEvent(QKeyEvent *event)
|
||||
{
|
||||
bool quit =
|
||||
@ -112,30 +333,41 @@ void MainWindow::keyPressEvent(QKeyEvent *event)
|
||||
|
||||
void MainWindow::tabChanged()
|
||||
{
|
||||
if(ui->tabWidget->currentIndex() == 0)
|
||||
{
|
||||
ui->previewProcessBar->hide();
|
||||
}
|
||||
else
|
||||
{
|
||||
if(ui->previewProcessBar->value() > 0)
|
||||
{
|
||||
ui->previewProcessBar->show();
|
||||
}
|
||||
}
|
||||
if(previewTabActive())
|
||||
{
|
||||
if(previewDirty)
|
||||
{
|
||||
makePreviews(ui->spinPreviewPage->value());
|
||||
}
|
||||
ui->previewProcessBar->show();
|
||||
}
|
||||
else
|
||||
{
|
||||
ui->previewProcessBar->hide();
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::previewReceived(QSharedPointer<PreviewResult> preview)
|
||||
void MainWindow::previewReceived(QSharedPointer<PreviewResult> preview, unsigned int previewGeneration)
|
||||
{
|
||||
if(preview->hasPreview())
|
||||
if(previewGeneration < this->currentPreviewGeneration)
|
||||
{
|
||||
return;
|
||||
}
|
||||
this->ui->previewProcessBar->setValue(this->ui->previewProcessBar->value() + 1);
|
||||
if(!preview.isNull() && preview->hasPreview())
|
||||
{
|
||||
QString docPath = preview->getDocumentPath();
|
||||
auto previewPage = preview->getPage();
|
||||
|
||||
ClickLabel *label = dynamic_cast<ClickLabel *>(preview->createPreviewWidget());
|
||||
ui->scrollAreaWidgetContents->layout()->addWidget(label);
|
||||
connect(label, &ClickLabel::leftClick, [this, docPath, previewPage]() { ipcDocOpen(docPath, previewPage); });
|
||||
connect(label, &ClickLabel::leftClick, [this, docPath, previewPage]() { openDocument(docPath, previewPage); });
|
||||
connect(label, &ClickLabel::rightClick,
|
||||
[this, docPath, previewPage]()
|
||||
{
|
||||
@ -157,7 +389,12 @@ void MainWindow::lineEditReturnPressed()
|
||||
ui->lblSearchResults->setText("Invalid paranthesis");
|
||||
return;
|
||||
}
|
||||
if(indexerTabActive())
|
||||
{
|
||||
ui->tabWidget->setCurrentIndex(0);
|
||||
}
|
||||
// TODO: validate q;
|
||||
ui->treeResultsList->clear();
|
||||
ui->lblSearchResults->setText("Searching...");
|
||||
this->ui->txtSearch->setEnabled(false);
|
||||
QFuture<QVector<SearchResult>> searchFuture = QtConcurrent::run(
|
||||
@ -174,10 +411,20 @@ void MainWindow::lineEditReturnPressed()
|
||||
if(addPathSearch)
|
||||
{
|
||||
LooqsQuery filesQuery = LooqsQuery::build(q, TokenType::FILTER_PATH_CONTAINS, false);
|
||||
if(filesQuery.getLimit() == -1)
|
||||
{
|
||||
filesQuery.setLimit(1000);
|
||||
}
|
||||
|
||||
results.append(searcher.search(filesQuery));
|
||||
}
|
||||
if(addContentSearch)
|
||||
{
|
||||
if(this->contentSearchQuery.getLimit() == -1)
|
||||
{
|
||||
this->contentSearchQuery.setLimit(1000);
|
||||
}
|
||||
|
||||
results.append(searcher.search(this->contentSearchQuery));
|
||||
}
|
||||
return results;
|
||||
@ -207,9 +454,12 @@ void MainWindow::handleSearchResults(const QVector<SearchResult> &results)
|
||||
bool exists = pathInfo.exists();
|
||||
if(exists)
|
||||
{
|
||||
if(result.fileData.absPath.endsWith(".pdf"))
|
||||
if(!pathInfo.suffix().contains("htm")) // hack until we can preview them properly...
|
||||
{
|
||||
this->previewableSearchResults.append(result);
|
||||
if(PreviewGenerator::get(pathInfo) != nullptr)
|
||||
{
|
||||
this->previewableSearchResults.append(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
@ -219,12 +469,11 @@ void MainWindow::handleSearchResults(const QVector<SearchResult> &results)
|
||||
}
|
||||
ui->treeResultsList->resizeColumnToContents(0);
|
||||
ui->treeResultsList->resizeColumnToContents(1);
|
||||
ui->treeResultsList->resizeColumnToContents(2);
|
||||
previewDirty = !this->previewableSearchResults.empty();
|
||||
|
||||
int numpages = ceil(static_cast<double>(this->previewableSearchResults.size()) / previewsPerPage);
|
||||
ui->spinPreviewPage->setMinimum(1);
|
||||
ui->spinPreviewPage->setMaximum(numpages);
|
||||
ui->spinPreviewPage->setValue(1);
|
||||
|
||||
if(previewTabActive() && previewDirty)
|
||||
{
|
||||
makePreviews(1);
|
||||
@ -233,19 +482,17 @@ void MainWindow::handleSearchResults(const QVector<SearchResult> &results)
|
||||
QString statusText = "Results: " + QString::number(results.size()) + " files";
|
||||
if(hasDeleted)
|
||||
{
|
||||
statusText += " WARNING: Some files don't exist anymore. No preview available for those. Index out of sync";
|
||||
statusText += " WARNING: Some files are inaccessible. No preview available for those. Index may be out of sync";
|
||||
}
|
||||
ui->lblSearchResults->setText(statusText);
|
||||
}
|
||||
|
||||
void MainWindow::makePreviews(int page)
|
||||
{
|
||||
|
||||
this->previewWorkerWatcher.cancel();
|
||||
this->previewWorkerWatcher.waitForFinished();
|
||||
|
||||
QCoreApplication::processEvents(); // Maybe not necessary anymore, depends on whether it's possible that a slot is
|
||||
// still to be fired.
|
||||
if(this->previewableSearchResults.empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
qDeleteAll(ui->scrollAreaWidgetContents->children());
|
||||
|
||||
ui->scrollAreaWidgetContents->setLayout(new QHBoxLayout());
|
||||
@ -255,7 +502,7 @@ void MainWindow::makePreviews(int page)
|
||||
scaleText.chop(1);
|
||||
|
||||
QVector<QString> wordsToHighlight;
|
||||
QRegularExpression extractor(R"#("([^"]*)"|(\w+))#");
|
||||
QRegularExpression extractor(R"#("([^"]*)"|(\p{L}+))#");
|
||||
for(const Token &token : this->contentSearchQuery.getTokens())
|
||||
{
|
||||
if(token.type == FILTER_CONTENT_CONTAINS)
|
||||
@ -273,13 +520,43 @@ void MainWindow::makePreviews(int page)
|
||||
}
|
||||
}
|
||||
}
|
||||
PreviewWorker worker;
|
||||
int end = previewsPerPage;
|
||||
int begin = page * previewsPerPage - previewsPerPage;
|
||||
this->previewWorkerWatcher.setFuture(worker.generatePreviews(this->previewableSearchResults.mid(begin, end),
|
||||
wordsToHighlight, scaleText.toInt() / 100.));
|
||||
ui->previewProcessBar->setMaximum(this->previewWorkerWatcher.progressMaximum());
|
||||
ui->previewProcessBar->setMinimum(this->previewWorkerWatcher.progressMinimum());
|
||||
if(begin < 0)
|
||||
{
|
||||
// Should not happen actually
|
||||
begin = 0;
|
||||
}
|
||||
|
||||
RenderConfig renderConfig;
|
||||
renderConfig.scaleX = QGuiApplication::primaryScreen()->physicalDotsPerInchX() * (scaleText.toInt() / 100.);
|
||||
renderConfig.scaleY = QGuiApplication::primaryScreen()->physicalDotsPerInchY() * (scaleText.toInt() / 100.);
|
||||
renderConfig.wordsToHighlight = wordsToHighlight;
|
||||
|
||||
QVector<RenderTarget> targets;
|
||||
for(SearchResult &sr : this->previewableSearchResults)
|
||||
{
|
||||
RenderTarget renderTarget;
|
||||
renderTarget.path = sr.fileData.absPath;
|
||||
|
||||
for(unsigned int pagenum : sr.pages)
|
||||
{
|
||||
renderTarget.page = (int)pagenum;
|
||||
targets.append(renderTarget);
|
||||
}
|
||||
}
|
||||
int numpages = ceil(static_cast<double>(targets.size()) / previewsPerPage);
|
||||
ui->spinPreviewPage->setMaximum(numpages);
|
||||
targets = targets.mid(begin, end);
|
||||
|
||||
ui->lblTotalPreviewPagesCount->setText(QString::number(numpages));
|
||||
ui->previewProcessBar->setMaximum(targets.count());
|
||||
ui->previewProcessBar->setMinimum(0);
|
||||
ui->previewProcessBar->setValue(0);
|
||||
ui->previewProcessBar->setVisible(this->previewableSearchResults.size() > 0);
|
||||
++this->currentPreviewGeneration;
|
||||
this->ui->spinPreviewPage->setEnabled(false);
|
||||
emit startIpcPreviews(renderConfig, targets);
|
||||
}
|
||||
|
||||
void MainWindow::handleSearchError(QString error)
|
||||
@ -293,27 +570,39 @@ void MainWindow::createSearchResutlMenu(QMenu &menu, const QFileInfo &fileInfo)
|
||||
[&fileInfo] { QGuiApplication::clipboard()->setText(fileInfo.fileName()); });
|
||||
menu.addAction("Copy full path to clipboard",
|
||||
[&fileInfo] { QGuiApplication::clipboard()->setText(fileInfo.absoluteFilePath()); });
|
||||
menu.addAction("Open containing folder", [this, &fileInfo] { this->ipcFileOpen(fileInfo.absolutePath()); });
|
||||
menu.addAction("Open containing folder", [this, &fileInfo] { this->openFile(fileInfo.absolutePath()); });
|
||||
}
|
||||
|
||||
void MainWindow::ipcDocOpen(QString path, int num)
|
||||
void MainWindow::openDocument(QString path, int num)
|
||||
{
|
||||
QStringList args;
|
||||
args << path;
|
||||
args << QString::number(num);
|
||||
this->ipcClient->sendCommand(DocOpen, args);
|
||||
QSettings settings;
|
||||
QString command = settings.value("pdfviewer").toString();
|
||||
if(path.endsWith(".pdf") && command != "" && command.contains("%p") && command.contains("%f"))
|
||||
{
|
||||
QStringList splitted = command.split(" ");
|
||||
if(splitted.size() > 1)
|
||||
{
|
||||
QString cmd = splitted[0];
|
||||
QStringList args = splitted.mid(1);
|
||||
args.replaceInStrings("%f", path);
|
||||
args.replaceInStrings("%p", QString::number(num));
|
||||
QProcess::startDetached(cmd, args);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::ipcFileOpen(QString path)
|
||||
void MainWindow::openFile(QString path)
|
||||
{
|
||||
QStringList args;
|
||||
args << path;
|
||||
this->ipcClient->sendCommand(FileOpen, args);
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
|
||||
}
|
||||
|
||||
void MainWindow::treeSearchItemActivated(QTreeWidgetItem *item, int i)
|
||||
{
|
||||
ipcFileOpen(item->text(1));
|
||||
openFile(item->text(1));
|
||||
}
|
||||
|
||||
void MainWindow::showSearchResultsContextMenu(const QPoint &point)
|
||||
@ -331,5 +620,11 @@ void MainWindow::showSearchResultsContextMenu(const QPoint &point)
|
||||
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
syncerThread.terminate();
|
||||
ipcClientThread.terminate();
|
||||
delete this->indexSyncer;
|
||||
delete this->dbService;
|
||||
delete this->dbFactory;
|
||||
delete this->indexer;
|
||||
delete ui;
|
||||
}
|
||||
|
@ -9,9 +9,11 @@
|
||||
#include <QFutureWatcher>
|
||||
#include <QSqlDatabase>
|
||||
#include <QLocalSocket>
|
||||
#include "previewworker.h"
|
||||
#include <QProgressDialog>
|
||||
#include "../shared/looqsquery.h"
|
||||
#include "ipcclient.h"
|
||||
#include "../shared/indexsyncer.h"
|
||||
#include "ipcpreviewclient.h"
|
||||
#include "indexer.h"
|
||||
namespace Ui
|
||||
{
|
||||
class MainWindow;
|
||||
@ -22,25 +24,33 @@ class MainWindow : public QMainWindow
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit MainWindow(QWidget *parent, IPCClient &client);
|
||||
explicit MainWindow(QWidget *parent, QString socketPath);
|
||||
~MainWindow();
|
||||
signals:
|
||||
void beginSearch(const QString &query);
|
||||
void startPdfPreviewGeneration(QVector<SearchResult> paths, double scalefactor);
|
||||
|
||||
private:
|
||||
DatabaseFactory *dbFactory;
|
||||
SqliteDbService *dbService;
|
||||
Ui::MainWindow *ui;
|
||||
IPCClient *ipcClient;
|
||||
IPCPreviewClient ipcPreviewClient;
|
||||
QThread ipcClientThread;
|
||||
QThread syncerThread;
|
||||
IndexSyncer *indexSyncer;
|
||||
QProgressDialog progressDialog;
|
||||
|
||||
Indexer *indexer;
|
||||
QFileIconProvider iconProvider;
|
||||
bool previewDirty;
|
||||
QSqlDatabase db;
|
||||
QFutureWatcher<QVector<SearchResult>> searchWatcher;
|
||||
QFutureWatcher<QSharedPointer<PreviewResult>> previewWorkerWatcher;
|
||||
void add(QString path, unsigned int page);
|
||||
QVector<SearchResult> previewableSearchResults;
|
||||
void connectSignals();
|
||||
void makePreviews(int page);
|
||||
bool previewTabActive();
|
||||
bool indexerTabActive();
|
||||
void keyPressEvent(QKeyEvent *event) override;
|
||||
unsigned int processedPdfPreviews;
|
||||
void handleSearchResults(const QVector<SearchResult> &results);
|
||||
@ -48,17 +58,26 @@ class MainWindow : public QMainWindow
|
||||
LooqsQuery contentSearchQuery;
|
||||
int previewsPerPage;
|
||||
void createSearchResutlMenu(QMenu &menu, const QFileInfo &fileInfo);
|
||||
void ipcDocOpen(QString path, int num);
|
||||
void ipcFileOpen(QString path);
|
||||
|
||||
void openDocument(QString path, int num);
|
||||
void openFile(QString path);
|
||||
unsigned int currentPreviewGeneration = 1;
|
||||
private slots:
|
||||
void lineEditReturnPressed();
|
||||
void treeSearchItemActivated(QTreeWidgetItem *item, int i);
|
||||
void showSearchResultsContextMenu(const QPoint &point);
|
||||
void tabChanged();
|
||||
void previewReceived(QSharedPointer<PreviewResult> preview);
|
||||
void previewReceived(QSharedPointer<PreviewResult> preview, unsigned int previewGeneration);
|
||||
void comboScaleChanged(int i);
|
||||
void spinPreviewPageValueChanged(int val);
|
||||
void startIndexing();
|
||||
void finishIndexing();
|
||||
void addPathToIndex();
|
||||
void startIndexSync();
|
||||
|
||||
signals:
|
||||
void startIpcPreviews(RenderConfig config, const QVector<RenderTarget> &targets);
|
||||
void stopIpcPreviews();
|
||||
void beginIndexSync();
|
||||
};
|
||||
|
||||
#endif // MAINWINDOW_H
|
||||
|
@ -7,7 +7,7 @@
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>1221</width>
|
||||
<height>614</height>
|
||||
<height>709</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
@ -27,7 +27,7 @@
|
||||
<enum>QTabWidget::South</enum>
|
||||
</property>
|
||||
<property name="currentIndex">
|
||||
<number>1</number>
|
||||
<number>0</number>
|
||||
</property>
|
||||
<widget class="QWidget" name="resultsTab">
|
||||
<attribute name="title">
|
||||
@ -82,7 +82,7 @@
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>1185</width>
|
||||
<height>324</height>
|
||||
<height>419</height>
|
||||
</rect>
|
||||
</property>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout"/>
|
||||
@ -155,6 +155,13 @@
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="lblTotalPreviewPagesCount">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="horizontalSpacer">
|
||||
<property name="orientation">
|
||||
@ -172,6 +179,171 @@
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QWidget" name="indexerTab">
|
||||
<attribute name="title">
|
||||
<string>Index</string>
|
||||
</attribute>
|
||||
<layout class="QGridLayout" name="gridLayout">
|
||||
<item row="1" column="0">
|
||||
<widget class="QGroupBox" name="groupBoxPaths">
|
||||
<property name="title">
|
||||
<string>Add paths to scan</string>
|
||||
</property>
|
||||
<layout class="QGridLayout" name="gridLayout_2">
|
||||
<item row="1" column="0">
|
||||
<widget class="QLineEdit" name="txtPathScanAdd"/>
|
||||
</item>
|
||||
<item row="3" column="0" colspan="5">
|
||||
<widget class="QListWidget" name="lstPaths"/>
|
||||
</item>
|
||||
<item row="1" column="3">
|
||||
<widget class="QToolButton" name="btnDeletePath">
|
||||
<property name="enabled">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Delete</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="QPushButton" name="btnChoosePath">
|
||||
<property name="text">
|
||||
<string>...</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="2">
|
||||
<widget class="QPushButton" name="btnAddPath">
|
||||
<property name="text">
|
||||
<string>Add</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="5" column="0">
|
||||
<widget class="QLabel" name="label">
|
||||
<property name="text">
|
||||
<string>Ignore patterns, separated by ';'. Example: *.js;*Downloads*</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="9" column="0">
|
||||
<widget class="QGroupBox" name="groupBoxIndexProgress">
|
||||
<property name="contextMenuPolicy">
|
||||
<enum>Qt::PreventContextMenu</enum>
|
||||
</property>
|
||||
<property name="title">
|
||||
<string>Index Progress</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout_4">
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_7">
|
||||
<item>
|
||||
<widget class="QLabel" name="lblPathsFound">
|
||||
<property name="text">
|
||||
<string>Paths found:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="lblPathsFoundValue">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_4">
|
||||
<item>
|
||||
<widget class="QLabel" name="lblAdded">
|
||||
<property name="font">
|
||||
<font>
|
||||
<weight>50</weight>
|
||||
<bold>false</bold>
|
||||
</font>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Added:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="lblAddedValue">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_5">
|
||||
<item>
|
||||
<widget class="QLabel" name="lblSkipped">
|
||||
<property name="font">
|
||||
<font>
|
||||
<weight>50</weight>
|
||||
<bold>false</bold>
|
||||
</font>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Skipped:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="lblSkippedValue">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_6">
|
||||
<item>
|
||||
<widget class="QLabel" name="lblFailed">
|
||||
<property name="font">
|
||||
<font>
|
||||
<weight>50</weight>
|
||||
<bold>false</bold>
|
||||
</font>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Failed:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="lblFailedValue">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="6" column="0">
|
||||
<widget class="QLineEdit" name="txtIgnorePatterns"/>
|
||||
</item>
|
||||
<item row="10" column="0">
|
||||
<widget class="QPushButton" name="btnStartIndexing">
|
||||
<property name="text">
|
||||
<string>Start indexing</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
@ -184,12 +356,13 @@
|
||||
<item>
|
||||
<widget class="QProgressBar" name="previewProcessBar">
|
||||
<property name="value">
|
||||
<number>24</number>
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="statusBar"/>
|
||||
<widget class="QMenuBar" name="menuBar">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
@ -199,8 +372,38 @@
|
||||
<height>35</height>
|
||||
</rect>
|
||||
</property>
|
||||
<widget class="QMenu" name="menulooqs">
|
||||
<property name="title">
|
||||
<string>looqs</string>
|
||||
</property>
|
||||
<addaction name="menuOpenConfigInTextEditorAction"/>
|
||||
<addaction name="menuSyncIndexAction"/>
|
||||
<addaction name="menuAboutAction"/>
|
||||
<addaction name="menuAboutQtAction"/>
|
||||
<addaction name="separator"/>
|
||||
</widget>
|
||||
<addaction name="menulooqs"/>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="statusBar"/>
|
||||
<action name="menuAboutAction">
|
||||
<property name="text">
|
||||
<string>About</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="menuOpenConfigInTextEditorAction">
|
||||
<property name="text">
|
||||
<string>Open config in text editor</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="menuAboutQtAction">
|
||||
<property name="text">
|
||||
<string>About Qt</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="menuSyncIndexAction">
|
||||
<property name="text">
|
||||
<string>Sync index (remove deleted, update existing files)</string>
|
||||
</property>
|
||||
</action>
|
||||
</widget>
|
||||
<layoutdefault spacing="6" margin="11"/>
|
||||
<resources/>
|
||||
|
@ -1 +1,24 @@
|
||||
#include "../shared/common.h"
|
||||
#include "previewgenerator.h"
|
||||
#include "previewgeneratorpdf.h"
|
||||
#include "previewgeneratorplaintext.h"
|
||||
|
||||
static PreviewGenerator *plainTextGenerator = new PreviewGeneratorPlainText();
|
||||
|
||||
static QMap<QString, PreviewGenerator *> generators{
|
||||
{"pdf", new PreviewGeneratorPdf()}, {"txt", plainTextGenerator}, {"md", plainTextGenerator},
|
||||
{"py", plainTextGenerator}, {"java", plainTextGenerator}, {"js", plainTextGenerator},
|
||||
{"cpp", plainTextGenerator}, {"c", plainTextGenerator}, {"sql", plainTextGenerator}};
|
||||
|
||||
PreviewGenerator *PreviewGenerator::get(QFileInfo &info)
|
||||
{
|
||||
PreviewGenerator *result = generators.value(info.suffix(), nullptr);
|
||||
if(result == nullptr)
|
||||
{
|
||||
if(Common::isTextFile(info))
|
||||
{
|
||||
return plainTextGenerator;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
@ -2,16 +2,19 @@
|
||||
#define PREVIEWGENERATOR_H
|
||||
#include <QVector>
|
||||
#include <QSharedPointer>
|
||||
#include <QFileInfo>
|
||||
#include "previewresult.h"
|
||||
#include "renderconfig.h"
|
||||
|
||||
class PreviewGenerator
|
||||
{
|
||||
public:
|
||||
virtual PreviewResult *generate(RenderConfig config, QString documentPath, unsigned int page) = 0;
|
||||
virtual QSharedPointer<PreviewResult> generate(RenderConfig config, QString documentPath, unsigned int page) = 0;
|
||||
virtual ~PreviewGenerator()
|
||||
{
|
||||
}
|
||||
|
||||
static PreviewGenerator *get(QFileInfo &info);
|
||||
};
|
||||
|
||||
#endif // PREVIEWGENERATOR_H
|
||||
|
@ -3,26 +3,6 @@
|
||||
|
||||
PreviewGeneratorMapFunctor::PreviewGeneratorMapFunctor()
|
||||
{
|
||||
generator[GeneratorIndex::PDF] = new PreviewGeneratorPdf();
|
||||
}
|
||||
|
||||
PreviewGenerator *PreviewGeneratorMapFunctor::getGenerator(QString filePath)
|
||||
{
|
||||
/* Dirty, but that's all we have at this point */
|
||||
if(filePath.endsWith(".pdf"))
|
||||
{
|
||||
return generator[GeneratorIndex::PDF];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
PreviewGeneratorMapFunctor::~PreviewGeneratorMapFunctor()
|
||||
{
|
||||
for(int i = GeneratorIndex::PDF; i < GeneratorIndex::LAST_DUMMY; i++)
|
||||
{
|
||||
// delete generator[i];
|
||||
generator[i] = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void PreviewGeneratorMapFunctor::setRenderConfig(RenderConfig config)
|
||||
@ -30,15 +10,15 @@ void PreviewGeneratorMapFunctor::setRenderConfig(RenderConfig config)
|
||||
this->renderConfig = config;
|
||||
}
|
||||
|
||||
QSharedPointer<PreviewResult> PreviewGeneratorMapFunctor::operator()(const QSharedPointer<PreviewResult> &renderResult)
|
||||
QByteArray PreviewGeneratorMapFunctor::operator()(const RenderTarget &renderTarget)
|
||||
{
|
||||
PreviewGenerator *previewGenerator = getGenerator(renderResult->getDocumentPath());
|
||||
QFileInfo info{renderTarget.path};
|
||||
PreviewGenerator *previewGenerator = PreviewGenerator::get(info);
|
||||
if(previewGenerator == nullptr)
|
||||
{
|
||||
return QSharedPointer<PreviewResult>();
|
||||
return QByteArray{};
|
||||
}
|
||||
auto preview =
|
||||
previewGenerator->generate(this->renderConfig, renderResult->getDocumentPath(), renderResult->getPage());
|
||||
auto preview = previewGenerator->generate(this->renderConfig, renderTarget.path, renderTarget.page);
|
||||
|
||||
return QSharedPointer<PreviewResult>(preview);
|
||||
return preview->serialize();
|
||||
}
|
||||
|
@ -2,8 +2,9 @@
|
||||
#define PREVIEWGENERATORMAPFUNCTOR_H
|
||||
|
||||
#include "renderconfig.h"
|
||||
#include "previewgenerator.h"
|
||||
#include "rendertarget.h"
|
||||
|
||||
#include "previewgenerator.h"
|
||||
class PreviewGeneratorMapFunctor
|
||||
{
|
||||
|
||||
@ -14,19 +15,15 @@ class PreviewGeneratorMapFunctor
|
||||
LAST_DUMMY
|
||||
};
|
||||
RenderConfig renderConfig;
|
||||
PreviewGenerator *generator[LAST_DUMMY];
|
||||
PreviewGenerator *getGenerator(QString filePath);
|
||||
|
||||
public:
|
||||
typedef QSharedPointer<PreviewResult> result_type;
|
||||
typedef QByteArray result_type;
|
||||
|
||||
PreviewGeneratorMapFunctor();
|
||||
|
||||
~PreviewGeneratorMapFunctor();
|
||||
|
||||
void setRenderConfig(RenderConfig config);
|
||||
|
||||
QSharedPointer<PreviewResult> operator()(const QSharedPointer<PreviewResult> &renderResult);
|
||||
QByteArray operator()(const RenderTarget &renderTarget);
|
||||
};
|
||||
|
||||
#endif // PREVIEWGENERATORMAPFUNCTOR_H
|
||||
|
@ -1,6 +1,5 @@
|
||||
#include <QMutexLocker>
|
||||
#include <QPainter>
|
||||
|
||||
#include "previewgeneratorpdf.h"
|
||||
|
||||
static QMutex cacheMutex;
|
||||
@ -24,18 +23,18 @@ Poppler::Document *PreviewGeneratorPdf::document(QString path)
|
||||
return result;
|
||||
}
|
||||
|
||||
PreviewResult *PreviewGeneratorPdf::generate(RenderConfig config, QString documentPath, unsigned int page)
|
||||
QSharedPointer<PreviewResult> PreviewGeneratorPdf::generate(RenderConfig config, QString documentPath,
|
||||
unsigned int page)
|
||||
{
|
||||
PreviewResultPdf *result = new PreviewResultPdf(documentPath, page);
|
||||
|
||||
Poppler::Document *doc = document(documentPath);
|
||||
if(doc == nullptr)
|
||||
{
|
||||
return result;
|
||||
return QSharedPointer<PreviewResult>(result);
|
||||
}
|
||||
if(doc->isLocked())
|
||||
{
|
||||
return result;
|
||||
return QSharedPointer<PreviewResult>(result);
|
||||
}
|
||||
int p = (int)page - 1;
|
||||
if(p < 0)
|
||||
@ -55,5 +54,5 @@ PreviewResult *PreviewGeneratorPdf::generate(RenderConfig config, QString docume
|
||||
}
|
||||
}
|
||||
result->previewImage = img;
|
||||
return result;
|
||||
return QSharedPointer<PreviewResult>(result);
|
||||
}
|
||||
|
@ -13,7 +13,7 @@ class PreviewGeneratorPdf : public PreviewGenerator
|
||||
public:
|
||||
using PreviewGenerator::PreviewGenerator;
|
||||
|
||||
PreviewResult *generate(RenderConfig config, QString documentPath, unsigned int page);
|
||||
QSharedPointer<PreviewResult> generate(RenderConfig config, QString documentPath, unsigned int page);
|
||||
|
||||
~PreviewGeneratorPdf()
|
||||
{
|
||||
|
90
gui/previewgeneratorplaintext.cpp
Normal file
90
gui/previewgeneratorplaintext.cpp
Normal file
@ -0,0 +1,90 @@
|
||||
#include <QTextStream>
|
||||
|
||||
#include "previewgeneratorplaintext.h"
|
||||
#include "previewresultplaintext.h"
|
||||
|
||||
QSharedPointer<PreviewResult> PreviewGeneratorPlainText::generate(RenderConfig config, QString documentPath,
|
||||
unsigned int page)
|
||||
{
|
||||
PreviewResultPlainText *result = new PreviewResultPlainText(documentPath, page);
|
||||
QFile file(documentPath);
|
||||
if(!file.open(QFile::ReadOnly | QFile::Text))
|
||||
{
|
||||
return QSharedPointer<PreviewResultPlainText>(result);
|
||||
}
|
||||
QTextStream in(&file);
|
||||
|
||||
QString resulText = "";
|
||||
QString content = in.readAll();
|
||||
QMap<int, QString> snippet;
|
||||
|
||||
int coveredRange = 0;
|
||||
|
||||
int lastWordPos = 0;
|
||||
QHash<QString, int> countmap;
|
||||
|
||||
const unsigned int maxSnippets = 7;
|
||||
unsigned int currentSnippets = 0;
|
||||
for(QString &word : config.wordsToHighlight)
|
||||
{
|
||||
|
||||
int lastPos = 0;
|
||||
int index = content.indexOf(word, lastPos, Qt::CaseInsensitive);
|
||||
while(index != -1 && currentSnippets < maxSnippets)
|
||||
{
|
||||
countmap[word] = countmap.value(word, 0) + 1;
|
||||
|
||||
if(index >= lastWordPos && index <= coveredRange)
|
||||
{
|
||||
break;
|
||||
}
|
||||
int begin = index - 50;
|
||||
if(begin < 0)
|
||||
{
|
||||
begin = 0;
|
||||
}
|
||||
int after = index + 50;
|
||||
if(after > content.size())
|
||||
{
|
||||
after = content.size();
|
||||
}
|
||||
|
||||
snippet[index] = "...<br>" + content.mid(begin, after) + "...<br>";
|
||||
coveredRange = after;
|
||||
lastPos = index;
|
||||
|
||||
index = content.indexOf(word, lastPos + 1, Qt::CaseInsensitive);
|
||||
++currentSnippets;
|
||||
}
|
||||
lastWordPos = lastPos;
|
||||
}
|
||||
|
||||
auto i = snippet.constBegin();
|
||||
while(i != snippet.constEnd())
|
||||
{
|
||||
resulText.append(i.value());
|
||||
++i;
|
||||
}
|
||||
|
||||
for(QString &word : config.wordsToHighlight)
|
||||
{
|
||||
resulText.replace(word, "<span style=\"background-color: yellow;\">" + word + "</span>", Qt::CaseInsensitive);
|
||||
}
|
||||
|
||||
QFileInfo info{documentPath};
|
||||
|
||||
QString header = "<b>" + info.fileName() + "</b> ";
|
||||
for(QString &word : config.wordsToHighlight)
|
||||
{
|
||||
header += word + ": " + QString::number(countmap[word]) + " ";
|
||||
}
|
||||
if(currentSnippets == maxSnippets)
|
||||
{
|
||||
header += "(truncated)";
|
||||
}
|
||||
|
||||
header += "<hr>";
|
||||
|
||||
result->setText(header + resulText.replace("\n", "<br>").mid(0, 1000));
|
||||
return QSharedPointer<PreviewResultPlainText>(result);
|
||||
}
|
12
gui/previewgeneratorplaintext.h
Normal file
12
gui/previewgeneratorplaintext.h
Normal file
@ -0,0 +1,12 @@
|
||||
#ifndef PREVIEWGENERATORPLAINTEXT_H
|
||||
#define PREVIEWGENERATORPLAINTEXT_H
|
||||
#include "previewgenerator.h"
|
||||
|
||||
class PreviewGeneratorPlainText : public PreviewGenerator
|
||||
{
|
||||
public:
|
||||
using PreviewGenerator::PreviewGenerator;
|
||||
QSharedPointer<PreviewResult> generate(RenderConfig config, QString documentPath, unsigned int page);
|
||||
};
|
||||
|
||||
#endif // PREVIEWGENERATORPLAINTEXT_H
|
@ -1,5 +1,4 @@
|
||||
#include "previewresult.h"
|
||||
|
||||
PreviewResult::PreviewResult()
|
||||
{
|
||||
}
|
||||
@ -33,3 +32,11 @@ unsigned int PreviewResult::getPage() const
|
||||
{
|
||||
return this->page;
|
||||
}
|
||||
|
||||
QByteArray PreviewResult::serialize() const
|
||||
{
|
||||
QByteArray result;
|
||||
QDataStream stream{&result, QIODevice::WriteOnly};
|
||||
stream << 0 << this->documentPath << this->page;
|
||||
return result;
|
||||
}
|
||||
|
@ -2,6 +2,12 @@
|
||||
#define PREVIEWRESULT_H
|
||||
#include "clicklabel.h"
|
||||
|
||||
enum PreviewResultType
|
||||
{
|
||||
PDF = 1,
|
||||
PlainText
|
||||
};
|
||||
|
||||
class PreviewResult
|
||||
{
|
||||
protected:
|
||||
@ -17,6 +23,7 @@ class PreviewResult
|
||||
virtual bool hasPreview();
|
||||
QString getDocumentPath() const;
|
||||
unsigned int getPage() const;
|
||||
virtual QByteArray serialize() const;
|
||||
};
|
||||
|
||||
#endif // PREVIEWRESULT_H
|
||||
|
@ -1,5 +1,4 @@
|
||||
#include "previewresultpdf.h"
|
||||
|
||||
PreviewResultPdf::PreviewResultPdf(const PreviewResult &o)
|
||||
{
|
||||
this->documentPath = o.getDocumentPath();
|
||||
@ -19,3 +18,27 @@ bool PreviewResultPdf::hasPreview()
|
||||
bool result = !this->previewImage.isNull();
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray PreviewResultPdf::serialize() const
|
||||
{
|
||||
QByteArray result;
|
||||
QDataStream stream{&result, QIODevice::WriteOnly};
|
||||
PreviewResultType type = PreviewResultType::PDF;
|
||||
stream << type << this->documentPath << this->page << this->previewImage;
|
||||
return result;
|
||||
}
|
||||
|
||||
QSharedPointer<PreviewResultPdf> PreviewResultPdf::deserialize(QByteArray &ba)
|
||||
{
|
||||
PreviewResultPdf *result = new PreviewResultPdf();
|
||||
PreviewResultType type;
|
||||
|
||||
QDataStream stream{&ba, QIODevice::ReadOnly};
|
||||
stream >> type;
|
||||
if(type != PreviewResultType::PDF)
|
||||
{
|
||||
throw std::runtime_error("Invalid byte array: Not a pdf preview");
|
||||
}
|
||||
stream >> result->documentPath >> result->page >> result->previewImage;
|
||||
return QSharedPointer<PreviewResultPdf>(result);
|
||||
}
|
||||
|
@ -12,6 +12,10 @@ class PreviewResultPdf : public PreviewResult
|
||||
|
||||
QWidget *createPreviewWidget() override;
|
||||
bool hasPreview() override;
|
||||
|
||||
QByteArray serialize() const;
|
||||
|
||||
static QSharedPointer<PreviewResultPdf> deserialize(QByteArray &ba);
|
||||
};
|
||||
|
||||
#endif // PREVIEWRESULTPDF_H
|
||||
|
54
gui/previewresultplaintext.cpp
Normal file
54
gui/previewresultplaintext.cpp
Normal file
@ -0,0 +1,54 @@
|
||||
#include "previewresultplaintext.h"
|
||||
|
||||
PreviewResultPlainText::PreviewResultPlainText(const PreviewResult &o)
|
||||
{
|
||||
this->documentPath = o.getDocumentPath();
|
||||
this->page = o.getPage();
|
||||
}
|
||||
|
||||
QWidget *PreviewResultPlainText::createPreviewWidget()
|
||||
{
|
||||
|
||||
ClickLabel *label = new ClickLabel();
|
||||
label->setText(this->text);
|
||||
label->setToolTip(getDocumentPath());
|
||||
label->setStyleSheet("border: 1px solid black");
|
||||
label->setMaximumWidth(768);
|
||||
label->setMaximumHeight(512);
|
||||
label->setTextFormat(Qt::RichText);
|
||||
return label;
|
||||
}
|
||||
|
||||
bool PreviewResultPlainText::hasPreview()
|
||||
{
|
||||
return !text.isEmpty();
|
||||
}
|
||||
|
||||
void PreviewResultPlainText::setText(QString text)
|
||||
{
|
||||
this->text = text;
|
||||
}
|
||||
|
||||
QByteArray PreviewResultPlainText::serialize() const
|
||||
{
|
||||
QByteArray result;
|
||||
QDataStream stream{&result, QIODevice::WriteOnly};
|
||||
PreviewResultType type = PreviewResultType::PlainText;
|
||||
stream << type << this->documentPath << this->page << this->text;
|
||||
return result;
|
||||
}
|
||||
|
||||
QSharedPointer<PreviewResultPlainText> PreviewResultPlainText::deserialize(QByteArray &ba)
|
||||
{
|
||||
PreviewResultPlainText *result = new PreviewResultPlainText();
|
||||
PreviewResultType type;
|
||||
|
||||
QDataStream stream{&ba, QIODevice::ReadOnly};
|
||||
stream >> type;
|
||||
if(type != PreviewResultType::PlainText)
|
||||
{
|
||||
throw std::runtime_error("Invalid byte array: Not a pdf preview");
|
||||
}
|
||||
stream >> result->documentPath >> result->page >> result->text;
|
||||
return QSharedPointer<PreviewResultPlainText>(result);
|
||||
}
|
23
gui/previewresultplaintext.h
Normal file
23
gui/previewresultplaintext.h
Normal file
@ -0,0 +1,23 @@
|
||||
#ifndef PREVIEWRESULTPLAINTEXT_H
|
||||
#define PREVIEWRESULTPLAINTEXT_H
|
||||
#include "previewresult.h"
|
||||
|
||||
class PreviewResultPlainText : public PreviewResult
|
||||
{
|
||||
private:
|
||||
QString text;
|
||||
|
||||
public:
|
||||
using PreviewResult::PreviewResult;
|
||||
PreviewResultPlainText(const PreviewResult &o);
|
||||
|
||||
QWidget *createPreviewWidget() override;
|
||||
bool hasPreview() override;
|
||||
|
||||
void setText(QString text);
|
||||
|
||||
QByteArray serialize() const;
|
||||
static QSharedPointer<PreviewResultPlainText> deserialize(QByteArray &ba);
|
||||
};
|
||||
|
||||
#endif // PREVIEWRESULTPLAINTEXT_H
|
@ -1,39 +0,0 @@
|
||||
#include <QApplication>
|
||||
#include <QScreen>
|
||||
#include <QScopedPointer>
|
||||
#include <QMutexLocker>
|
||||
#include <QtConcurrent/QtConcurrent>
|
||||
#include <QtConcurrent/QtConcurrentMap>
|
||||
#include <atomic>
|
||||
#include "previewworker.h"
|
||||
|
||||
PreviewWorker::PreviewWorker()
|
||||
{
|
||||
}
|
||||
|
||||
QFuture<QSharedPointer<PreviewResult>> PreviewWorker::generatePreviews(const QVector<SearchResult> paths,
|
||||
QVector<QString> wordsToHighlight,
|
||||
double scalefactor)
|
||||
{
|
||||
QVector<QSharedPointer<PreviewResult>> previews;
|
||||
|
||||
for(const SearchResult &sr : paths)
|
||||
{
|
||||
for(unsigned int page : sr.pages)
|
||||
{
|
||||
QSharedPointer<PreviewResult> ptr =
|
||||
QSharedPointer<PreviewResult>(new PreviewResult{sr.fileData.absPath, page});
|
||||
previews.append(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
RenderConfig renderConfig;
|
||||
renderConfig.scaleX = QGuiApplication::primaryScreen()->physicalDotsPerInchX() * scalefactor;
|
||||
renderConfig.scaleY = QGuiApplication::primaryScreen()->physicalDotsPerInchY() * scalefactor;
|
||||
renderConfig.wordsToHighlight = wordsToHighlight;
|
||||
|
||||
auto mapFunctor = new PreviewGeneratorMapFunctor();
|
||||
mapFunctor->setRenderConfig(renderConfig);
|
||||
|
||||
return QtConcurrent::mapped(previews, *mapFunctor);
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
#ifndef PREVIEWWORKER_H
|
||||
#define PREVIEWWORKER_H
|
||||
#include <QObject>
|
||||
#include <QImage>
|
||||
#include <QHash>
|
||||
#include <QThread>
|
||||
#include <QMutex>
|
||||
#include <QWaitCondition>
|
||||
#include <QMutex>
|
||||
#include <QFuture>
|
||||
#include "previewresultpdf.h"
|
||||
#include "searchresult.h"
|
||||
#include "previewgenerator.h"
|
||||
#include "previewworker.h"
|
||||
#include "previewgeneratorpdf.h"
|
||||
#include "previewgeneratormapfunctor.h"
|
||||
|
||||
class PreviewWorker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
PreviewWorker();
|
||||
QSharedPointer<PreviewGenerator> createGenerator(QString path);
|
||||
|
||||
QFuture<QSharedPointer<PreviewResult>> generatePreviews(const QVector<SearchResult> paths,
|
||||
QVector<QString> wordsToHighlight, double scalefactor);
|
||||
};
|
||||
|
||||
#endif // PREVIEWWORKER_H
|
17
gui/renderconfig.cpp
Normal file
17
gui/renderconfig.cpp
Normal file
@ -0,0 +1,17 @@
|
||||
#include "renderconfig.h"
|
||||
|
||||
QDataStream &operator<<(QDataStream &out, const RenderConfig &rc)
|
||||
{
|
||||
out << rc.scaleX;
|
||||
out << rc.scaleY;
|
||||
out << rc.wordsToHighlight;
|
||||
return out;
|
||||
}
|
||||
|
||||
QDataStream &operator>>(QDataStream &in, RenderConfig &rc)
|
||||
{
|
||||
in >> rc.scaleX;
|
||||
in >> rc.scaleY;
|
||||
in >> rc.wordsToHighlight;
|
||||
return in;
|
||||
}
|
@ -1,12 +1,17 @@
|
||||
#ifndef RENDERCONFIG_H
|
||||
#define RENDERCONFIG_H
|
||||
#include <QVector>
|
||||
#include <QDataStream>
|
||||
|
||||
struct RenderConfig
|
||||
{
|
||||
double scaleX = 50 / 100.;
|
||||
double scaleY = scaleX;
|
||||
QVector<QString> wordsToHighlight;
|
||||
friend QDataStream &operator<<(QDataStream &out, const RenderConfig &rc);
|
||||
friend QDataStream &operator>>(QDataStream &in, RenderConfig &rc);
|
||||
};
|
||||
|
||||
QDataStream &operator<<(QDataStream &out, const RenderConfig &rc);
|
||||
QDataStream &operator>>(QDataStream &in, RenderConfig &rc);
|
||||
#endif // RENDERCONFIG_H
|
||||
|
14
gui/rendertarget.cpp
Normal file
14
gui/rendertarget.cpp
Normal file
@ -0,0 +1,14 @@
|
||||
#include <QDataStream>
|
||||
|
||||
#include "rendertarget.h"
|
||||
QDataStream &operator<<(QDataStream &out, const RenderTarget &rc)
|
||||
{
|
||||
out << rc.path << rc.page;
|
||||
return out;
|
||||
}
|
||||
|
||||
QDataStream &operator>>(QDataStream &in, RenderTarget &rc)
|
||||
{
|
||||
in >> rc.path >> rc.page;
|
||||
return in;
|
||||
}
|
15
gui/rendertarget.h
Normal file
15
gui/rendertarget.h
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef RENDERTARGET_H
|
||||
#define RENDERTARGET_H
|
||||
#include <QString>
|
||||
struct RenderTarget
|
||||
{
|
||||
public:
|
||||
QString path;
|
||||
int page;
|
||||
friend QDataStream &operator<<(QDataStream &out, const RenderTarget &rc);
|
||||
friend QDataStream &operator>>(QDataStream &in, RenderTarget &rc);
|
||||
};
|
||||
|
||||
QDataStream &operator<<(QDataStream &out, const RenderTarget &rc);
|
||||
QDataStream &operator>>(QDataStream &in, RenderTarget &rc);
|
||||
#endif // RENDERTARGET_H
|
9
looqs.desktop
Normal file
9
looqs.desktop
Normal file
@ -0,0 +1,9 @@
|
||||
[Desktop Entry]
|
||||
Name=looqs
|
||||
Exec=looqs-gui
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Icon=looqs
|
||||
StartupWMClass=looqs
|
||||
Comment=FTS desktop search with previews
|
||||
Categories=Qt;Utility;
|
21
looqs.svg
Normal file
21
looqs.svg
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 13 KiB |
@ -7,15 +7,23 @@
|
||||
#include <QSqlError>
|
||||
#include <QTextStream>
|
||||
#include <QDebug>
|
||||
#include <QMimeDatabase>
|
||||
#include "looqsgeneralexception.h"
|
||||
#include "common.h"
|
||||
#include "dbmigrator.h"
|
||||
#include "databasefactory.h"
|
||||
#include "logger.h"
|
||||
|
||||
#define SETTINGS_KEY_DBPATH "dbpath"
|
||||
#define SETTINGS_KEY_FIRSTRUN "firstrun"
|
||||
#define SETTINGS_KEY_IPCSOCKETPATH "ipcsocketpath"
|
||||
#define SETTINGS_KEY_PDFVIEWER "pdfviewer"
|
||||
#define SETTINGS_KEY_EXCLUDEDPATHS "excludedpaths"
|
||||
#define SETTINGS_KEY_MOUNTPATHS "mountpaths"
|
||||
|
||||
inline void initResources()
|
||||
{
|
||||
Q_INIT_RESOURCE(create);
|
||||
Q_INIT_RESOURCE(migrations);
|
||||
}
|
||||
|
||||
bool Common::initSqliteDatabase(QString path)
|
||||
@ -28,31 +36,58 @@ bool Common::initSqliteDatabase(QString path)
|
||||
return false;
|
||||
}
|
||||
initResources();
|
||||
QFile file(":./create.sql");
|
||||
if(!file.open(QIODevice::ReadOnly))
|
||||
{
|
||||
qDebug() << "Failed to load SQL creation script from embedded resource";
|
||||
return false;
|
||||
}
|
||||
QTextStream stream(&file);
|
||||
db.transaction();
|
||||
while(!stream.atEnd())
|
||||
{
|
||||
QString sql = stream.readLine();
|
||||
QSqlQuery sqlQuery;
|
||||
if(!sqlQuery.exec(sql))
|
||||
{
|
||||
qDebug() << "Failed to execute sql statement while initializing database: " << sqlQuery.lastError();
|
||||
db.rollback();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
db.commit();
|
||||
DBMigrator migrator{db};
|
||||
migrator.performMigrations();
|
||||
db.close();
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
QString Common::findInPath(QString needle)
|
||||
{
|
||||
QStringList results;
|
||||
QString pathVar = QProcessEnvironment::systemEnvironment().value("PATH", "/usr/bin/:/bin/:");
|
||||
QStringList paths = pathVar.split(":");
|
||||
for(const QString &path : paths)
|
||||
{
|
||||
// TODO: can pass ../ but so be it for now.
|
||||
|
||||
QFileInfo info{path + "/" + needle};
|
||||
if(info.exists())
|
||||
{
|
||||
return info.absoluteFilePath();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
void Common::setPdfViewer()
|
||||
{
|
||||
QString value;
|
||||
|
||||
/* TODO: well, we should query this probably from xdg*/
|
||||
QString okularPath = findInPath("okular");
|
||||
QString evincePath = findInPath("evince");
|
||||
QString qpdfviewPath = findInPath("qpdfview");
|
||||
|
||||
if(okularPath != "")
|
||||
{
|
||||
value = okularPath + " %f -p %p";
|
||||
}
|
||||
else if(evincePath != "")
|
||||
{
|
||||
value = evincePath + "-i %p %f";
|
||||
}
|
||||
else if(qpdfviewPath != "")
|
||||
{
|
||||
value = qpdfviewPath + "%f#%p";
|
||||
}
|
||||
|
||||
QSettings settings;
|
||||
if(value != "")
|
||||
{
|
||||
settings.setValue(SETTINGS_KEY_PDFVIEWER, value);
|
||||
}
|
||||
}
|
||||
void Common::ensureConfigured()
|
||||
{
|
||||
QSettings settings;
|
||||
@ -73,8 +108,10 @@ void Common::ensureConfigured()
|
||||
{
|
||||
throw LooqsGeneralException("Failed to initialize sqlite database");
|
||||
}
|
||||
|
||||
settings.setValue(SETTINGS_KEY_FIRSTRUN, false);
|
||||
settings.setValue(SETTINGS_KEY_DBPATH, dbpath);
|
||||
setPdfViewer();
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -84,6 +121,21 @@ void Common::ensureConfigured()
|
||||
{
|
||||
throw LooqsGeneralException("Database " + dbpath + " was not found");
|
||||
}
|
||||
DatabaseFactory factory{dbpath};
|
||||
auto db = factory.forCurrentThread();
|
||||
DBMigrator migrator{db};
|
||||
if(migrator.migrationNeeded())
|
||||
{
|
||||
QFile out;
|
||||
out.open(stderr, QIODevice::WriteOnly);
|
||||
Logger migrationLogger{&out};
|
||||
migrationLogger << "Database is being upgraded, please be patient..." << Qt::endl;
|
||||
QObject::connect(&migrator, &DBMigrator::migrationDone,
|
||||
[&migrationLogger](uint32_t migration)
|
||||
{ migrationLogger << "Progress: Successfully migrated to: " << migration << Qt::endl; });
|
||||
migrator.performMigrations();
|
||||
migrationLogger << "Database upgraded successfully" << Qt::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -96,7 +148,7 @@ void Common::setupAppInfo()
|
||||
|
||||
QString Common::databasePath()
|
||||
{
|
||||
QString env = QProcessEnvironment::systemEnvironment().value("QSS_DB_OVERRIDE");
|
||||
QString env = QProcessEnvironment::systemEnvironment().value("LOOQS_DB_OVERRIDE");
|
||||
if(env == "")
|
||||
{
|
||||
QSettings settings;
|
||||
@ -104,3 +156,92 @@ QString Common::databasePath()
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
bool Common::noSandboxModeRequested()
|
||||
{
|
||||
QString env = getenv("LOOQS_DISABLE_SANDBOX");
|
||||
if(env == "1")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
QString Common::ipcSocketPath()
|
||||
{
|
||||
return "/tmp/.looqs/looqs-ipc-socket";
|
||||
|
||||
/* May not a good idea to set it in the settings and probably nobody would ever bother to change it anyway */
|
||||
// QSettings settings;
|
||||
// return settings.value(SETTINGS_KEY_IPCSOCKETPATH, "/tmp/.looqs/looqs-ipc-socket").toString();
|
||||
}
|
||||
|
||||
static QStringList excludedPaths = {"/proc", "/sys", "/dev", "/tmp", "/var/run", "/run"};
|
||||
|
||||
QStringList Common::excludedPaths()
|
||||
{
|
||||
static int ran = false;
|
||||
if(!ran)
|
||||
{
|
||||
QSettings settings;
|
||||
QStringList userExcludedPaths = settings.value(SETTINGS_KEY_EXCLUDEDPATHS).toStringList();
|
||||
ran = true;
|
||||
::excludedPaths.append(userExcludedPaths);
|
||||
}
|
||||
return ::excludedPaths;
|
||||
}
|
||||
|
||||
QStringList Common::mountPaths()
|
||||
{
|
||||
static int ran = false;
|
||||
static QStringList mountPaths;
|
||||
if(!ran)
|
||||
{
|
||||
QSettings settings;
|
||||
mountPaths = settings.value(SETTINGS_KEY_MOUNTPATHS, QStringList{"/media", "/mnt"}).toStringList();
|
||||
ran = true;
|
||||
}
|
||||
return mountPaths;
|
||||
}
|
||||
|
||||
bool Common::isMountPath(QString path)
|
||||
{
|
||||
QStringList mountPaths = Common::mountPaths();
|
||||
for(QString &mountPath : mountPaths)
|
||||
{
|
||||
if(path.startsWith(mountPath))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Common::isTextFile(QFileInfo fileInfo)
|
||||
{
|
||||
/* TODO: This is not sandboxed yet ... */
|
||||
QMimeDatabase mimeDatabase;
|
||||
QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileInfo);
|
||||
if(mimeType.name().startsWith("text/"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
for(QString &str : mimeType.allAncestors())
|
||||
{
|
||||
if(str.startsWith("text/"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
QString Common::versionText()
|
||||
{
|
||||
QString commitid = GIT_COMMIT_ID;
|
||||
QString tag = GIT_TAG;
|
||||
return tag + " (" + commitid + ") built " + __DATE__ + " " + __TIME__;
|
||||
}
|
||||
|
@ -1,12 +1,21 @@
|
||||
#ifndef COMMON_H
|
||||
#define COMMON_H
|
||||
#include <QCoreApplication>
|
||||
|
||||
#include <QFileInfo>
|
||||
namespace Common
|
||||
{
|
||||
void setupAppInfo();
|
||||
QString databasePath();
|
||||
QString ipcSocketPath();
|
||||
void setPdfViewer();
|
||||
QString findInPath(QString needle);
|
||||
bool initSqliteDatabase(QString path);
|
||||
void ensureConfigured();
|
||||
QStringList excludedPaths();
|
||||
QStringList mountPaths();
|
||||
bool isTextFile(QFileInfo fileInfo);
|
||||
bool isMountPath(QString path);
|
||||
bool noSandboxModeRequested();
|
||||
QString versionText();
|
||||
} // namespace Common
|
||||
#endif
|
||||
|
1
shared/concurrentqueue.cpp
Normal file
1
shared/concurrentqueue.cpp
Normal file
@ -0,0 +1 @@
|
||||
#include "concurrentqueue.h"
|
66
shared/concurrentqueue.h
Normal file
66
shared/concurrentqueue.h
Normal file
@ -0,0 +1,66 @@
|
||||
#ifndef CONCURRENTQUEUE_H
|
||||
#define CONCURRENTQUEUE_H
|
||||
#include <QList>
|
||||
#include <QMutex>
|
||||
#include <QSemaphore>
|
||||
#define QUEUE_SIZE 10000
|
||||
template <class T> class ConcurrentQueue : protected QList<T>
|
||||
{
|
||||
protected:
|
||||
QMutex mutex;
|
||||
|
||||
QSemaphore avail{QUEUE_SIZE};
|
||||
|
||||
public:
|
||||
void enqueue(const T &t)
|
||||
{
|
||||
avail.acquire(1);
|
||||
QMutexLocker locker(&mutex);
|
||||
QList<T>::append(t);
|
||||
}
|
||||
|
||||
QVector<T> dequeue(int batchsize)
|
||||
{
|
||||
avail.release(batchsize);
|
||||
// TODO: this sucks
|
||||
QVector<T> result;
|
||||
QMutexLocker locker(&mutex);
|
||||
for(int i = 0; i < batchsize; i++)
|
||||
{
|
||||
result.append(QList<T>::takeFirst());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void enqueue(const QVector<T> &t)
|
||||
{
|
||||
QList<T> tmp(t.begin(), t.end());
|
||||
avail.acquire(t.size());
|
||||
QMutexLocker locker(&mutex);
|
||||
QList<T>::append(tmp);
|
||||
}
|
||||
|
||||
unsigned int remaining()
|
||||
{
|
||||
return QUEUE_SIZE - avail.available();
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
QMutexLocker locker(&mutex);
|
||||
QList<T>::clear();
|
||||
avail.release(QUEUE_SIZE);
|
||||
}
|
||||
|
||||
bool dequeue(T &result)
|
||||
{
|
||||
QMutexLocker locker(&mutex);
|
||||
if(QList<T>::isEmpty())
|
||||
return false;
|
||||
avail.release(1);
|
||||
result = QList<T>::takeFirst();
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // CONCURRENTQUEUE_H
|
@ -1,5 +0,0 @@
|
||||
<!DOCTYPE RCC><RCC version="1.0">
|
||||
<qresource>
|
||||
<file>create.sql</file>
|
||||
</qresource>
|
||||
</RCC>
|
@ -1,6 +1,7 @@
|
||||
#include <QThread>
|
||||
#include "databasefactory.h"
|
||||
#include "logger.h"
|
||||
#include "looqsgeneralexception.h"
|
||||
DatabaseFactory::DatabaseFactory(QString connectionString)
|
||||
{
|
||||
this->connectionString = connectionString;
|
||||
@ -11,7 +12,7 @@ static QThreadStorage<QSqlDatabase> dbStore;
|
||||
QSqlDatabase DatabaseFactory::createNew()
|
||||
{
|
||||
static int counter = 0;
|
||||
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "QSS" + QString::number(counter++));
|
||||
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "LOOQS" + QString::number(counter++));
|
||||
db.setDatabaseName(this->connectionString);
|
||||
if(!db.open())
|
||||
{
|
||||
@ -28,7 +29,7 @@ QSqlDatabase DatabaseFactory::forCurrentThread()
|
||||
return dbStore.localData();
|
||||
}
|
||||
QSqlDatabase db =
|
||||
QSqlDatabase::addDatabase("QSQLITE", "QSS" + QString::number((quint64)QThread::currentThread(), 16));
|
||||
QSqlDatabase::addDatabase("QSQLITE", "LOOQS" + QString::number((quint64)QThread::currentThread(), 16));
|
||||
db.setDatabaseName(this->connectionString);
|
||||
if(!db.open())
|
||||
{
|
@ -2,7 +2,6 @@
|
||||
#define DATABASEFACTORY_H
|
||||
#include <QSqlDatabase>
|
||||
#include <QThreadStorage>
|
||||
#include "utils.h"
|
||||
class DatabaseFactory
|
||||
{
|
||||
private:
|
85
shared/dbmigrator.cpp
Normal file
85
shared/dbmigrator.cpp
Normal file
@ -0,0 +1,85 @@
|
||||
#include <QDirIterator>
|
||||
#include <QSqlQuery>
|
||||
#include <QSqlError>
|
||||
#include <QTextStream>
|
||||
#include <QDebug>
|
||||
#include "dbmigrator.h"
|
||||
#include "looqsgeneralexception.h"
|
||||
|
||||
DBMigrator::DBMigrator(QSqlDatabase &db)
|
||||
{
|
||||
Q_INIT_RESOURCE(migrations);
|
||||
this->db = &db;
|
||||
}
|
||||
|
||||
DBMigrator::~DBMigrator()
|
||||
{
|
||||
Q_CLEANUP_RESOURCE(migrations);
|
||||
}
|
||||
|
||||
QStringList DBMigrator::getMigrationFilenames()
|
||||
{
|
||||
QStringList result;
|
||||
QDirIterator it(":/looqs-migrations/");
|
||||
while(it.hasNext())
|
||||
{
|
||||
result.append(it.next());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
uint32_t DBMigrator::currentRevision()
|
||||
{
|
||||
QSqlQuery dbquery(*db);
|
||||
dbquery.exec("PRAGMA user_version;");
|
||||
if(!dbquery.next())
|
||||
{
|
||||
throw new LooqsGeneralException("Failed to query current db revision");
|
||||
}
|
||||
uint32_t result = dbquery.value(0).toUInt();
|
||||
return result;
|
||||
}
|
||||
|
||||
bool DBMigrator::migrationNeeded()
|
||||
{
|
||||
QStringList migrations = getMigrationFilenames();
|
||||
uint32_t currentRev = currentRevision();
|
||||
|
||||
return currentRev < static_cast<uint32_t>(migrations.size());
|
||||
}
|
||||
|
||||
void DBMigrator::performMigrations()
|
||||
{
|
||||
QStringList migrations = getMigrationFilenames();
|
||||
uint32_t currentRev = currentRevision();
|
||||
uint32_t targetRev = (migrations.size());
|
||||
|
||||
for(uint32_t i = currentRev + 1; i <= targetRev; i++)
|
||||
{
|
||||
QString fileName = QString(":/looqs-migrations/%1.sql").arg(i);
|
||||
QFile file{fileName};
|
||||
if(!file.open(QIODevice::ReadOnly))
|
||||
{
|
||||
throw LooqsGeneralException("Migration: Failed to find required revision file");
|
||||
}
|
||||
QTextStream stream(&file);
|
||||
db->transaction();
|
||||
while(!stream.atEnd())
|
||||
{
|
||||
QString sql = stream.readLine();
|
||||
QSqlQuery sqlQuery{*db};
|
||||
if(!sqlQuery.exec(sql))
|
||||
{
|
||||
|
||||
db->rollback();
|
||||
throw LooqsGeneralException("Failed to execute sql statement while initializing database: " +
|
||||
sqlQuery.lastError().text());
|
||||
}
|
||||
}
|
||||
QSqlQuery updateVersion{*db};
|
||||
updateVersion.exec(QString("PRAGMA user_version=%1;").arg(i));
|
||||
db->commit();
|
||||
emit migrationDone(i);
|
||||
}
|
||||
emit done();
|
||||
}
|
24
shared/dbmigrator.h
Normal file
24
shared/dbmigrator.h
Normal file
@ -0,0 +1,24 @@
|
||||
#ifndef DBMIGRATOR_H
|
||||
#define DBMIGRATOR_H
|
||||
#include <QStringList>
|
||||
#include <QSqlDatabase>
|
||||
#include <QObject>
|
||||
class DBMigrator : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
QSqlDatabase *db;
|
||||
|
||||
public:
|
||||
DBMigrator(QSqlDatabase &db);
|
||||
~DBMigrator();
|
||||
uint32_t currentRevision();
|
||||
void performMigrations();
|
||||
QStringList getMigrationFilenames();
|
||||
bool migrationNeeded();
|
||||
signals:
|
||||
void migrationDone(uint32_t);
|
||||
void done();
|
||||
};
|
||||
|
||||
#endif // DBMIGRATOR_H
|
62
shared/dirscanworker.cpp
Normal file
62
shared/dirscanworker.cpp
Normal file
@ -0,0 +1,62 @@
|
||||
#include <QThread>
|
||||
#include "dirscanworker.h"
|
||||
#include "logger.h"
|
||||
DirScanWorker::DirScanWorker(ConcurrentQueue<QString> &queue, ConcurrentQueue<QString> &resultQueue,
|
||||
QStringList ignorePattern, unsigned int progressReportThreshold,
|
||||
std::atomic<bool> &stopToken)
|
||||
{
|
||||
this->queue = &queue;
|
||||
this->resultQueue = &resultQueue;
|
||||
this->wildcardMatcher.setPatterns(ignorePattern);
|
||||
this->progressReportThreshold = progressReportThreshold;
|
||||
this->stopToken = &stopToken;
|
||||
setAutoDelete(false);
|
||||
}
|
||||
|
||||
void DirScanWorker::run()
|
||||
{
|
||||
unsigned int currentProgress = 0;
|
||||
QString path;
|
||||
/* TODO: if we have e. g. only one path, then only one thread will scan this path.
|
||||
*
|
||||
* Thus, we must resubmit to the queue directories so other threads can help
|
||||
the current one (requires a new logic for threads in ParallelDirScanner). Alterantively,
|
||||
start new DirScanWorkers ourselves here... */
|
||||
while(queue->dequeue(path))
|
||||
{
|
||||
if(wildcardMatcher.match(path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
QDirIterator iterator(path, QStringList{}, QDir::Files, QDirIterator::Subdirectories);
|
||||
while(iterator.hasNext())
|
||||
{
|
||||
QString entry = iterator.next();
|
||||
if(wildcardMatcher.match(entry))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
this->results.append(entry);
|
||||
++currentProgress;
|
||||
if(currentProgress == progressReportThreshold)
|
||||
{
|
||||
if(this->stopToken->load(std::memory_order_relaxed))
|
||||
{
|
||||
Logger::info() << "Received cancel request" << Qt::endl;
|
||||
this->results.clear();
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
|
||||
this->resultQueue->enqueue(this->results);
|
||||
emit progress(results.length());
|
||||
currentProgress = 0;
|
||||
this->results.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
this->resultQueue->enqueue(this->results);
|
||||
emit progress(results.length());
|
||||
this->results.clear();
|
||||
emit finished();
|
||||
}
|
32
shared/dirscanworker.h
Normal file
32
shared/dirscanworker.h
Normal file
@ -0,0 +1,32 @@
|
||||
#ifndef DIRSCANWORKER_H
|
||||
#define DIRSCANWORKER_H
|
||||
#include <QObject>
|
||||
#include <QRunnable>
|
||||
#include <QDirIterator>
|
||||
#include "concurrentqueue.h"
|
||||
#include "wildcardmatcher.h"
|
||||
class DirScanWorker : public QObject, public QRunnable
|
||||
{
|
||||
Q_OBJECT
|
||||
protected:
|
||||
unsigned int progressReportThreshold = 1000;
|
||||
ConcurrentQueue<QString> *queue = nullptr;
|
||||
ConcurrentQueue<QString> *resultQueue = nullptr;
|
||||
|
||||
WildcardMatcher wildcardMatcher;
|
||||
QVector<QString> results;
|
||||
|
||||
std::atomic<bool> *stopToken;
|
||||
|
||||
public:
|
||||
DirScanWorker(ConcurrentQueue<QString> &queue, ConcurrentQueue<QString> &resultQueue, QStringList ignorePattern,
|
||||
unsigned int progressReportThreshold, std::atomic<bool> &stopToken);
|
||||
|
||||
void run() override;
|
||||
|
||||
signals:
|
||||
void progress(unsigned int);
|
||||
void finished();
|
||||
};
|
||||
|
||||
#endif // DIRSCANWORKER_H
|
@ -6,7 +6,6 @@
|
||||
#include "filesaver.h"
|
||||
#include "processor.h"
|
||||
#include "pdfprocessor.h"
|
||||
#include "commandadd.h"
|
||||
#include "defaulttextprocessor.h"
|
||||
#include "tagstripperprocessor.h"
|
||||
#include "nothingprocessor.h"
|
||||
@ -24,6 +23,7 @@ SaveFileResult FileSaver::addFile(QString path)
|
||||
{
|
||||
QFileInfo info(path);
|
||||
QString absPath = info.absoluteFilePath();
|
||||
|
||||
auto mtime = info.lastModified().toSecsSinceEpoch();
|
||||
if(this->dbService->fileExistsInDatabase(absPath, mtime))
|
||||
{
|
||||
@ -85,7 +85,7 @@ int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFile
|
||||
}
|
||||
else if(result == OK)
|
||||
{
|
||||
Logger::info() << "Added" << path << Qt::endl;
|
||||
Logger::info() << "Saved" << path << Qt::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -96,14 +96,28 @@ int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFile
|
||||
SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
|
||||
{
|
||||
QVector<PageData> pageData;
|
||||
QString absPath = fileInfo.absoluteFilePath();
|
||||
QString canonicalPath = fileInfo.canonicalFilePath();
|
||||
|
||||
int status = -1;
|
||||
|
||||
if(!fileInfo.exists())
|
||||
{
|
||||
return NOTFOUND;
|
||||
}
|
||||
|
||||
if(fileInfo.isFile())
|
||||
{
|
||||
for(QString &excludedPath : this->excludedPaths)
|
||||
{
|
||||
if(canonicalPath.startsWith(excludedPath))
|
||||
{
|
||||
return SKIPPED;
|
||||
}
|
||||
}
|
||||
|
||||
QProcess process;
|
||||
QStringList args;
|
||||
args << "process" << absPath;
|
||||
args << "process" << canonicalPath;
|
||||
process.setProcessChannelMode(QProcess::ForwardedErrorChannel);
|
||||
process.start("/proc/self/exe", args);
|
||||
process.waitForStarted();
|
||||
@ -125,9 +139,9 @@ SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
|
||||
pageData.append(pd);
|
||||
}
|
||||
status = process.exitCode();
|
||||
if(status != 0)
|
||||
if(status != 0 && status != NOTHING_PROCESSED)
|
||||
{
|
||||
Logger::error() << "Error while processing" << absPath << ":"
|
||||
Logger::error() << "FileSaver::saveFile(): Error while processing" << canonicalPath << ":"
|
||||
<< "Exit code " << status << Qt::endl;
|
||||
|
||||
return PROCESSFAIL;
|
||||
@ -137,7 +151,7 @@ SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
|
||||
// Could happen if a file corrupted for example
|
||||
if(pageData.isEmpty() && status != NOTHING_PROCESSED)
|
||||
{
|
||||
Logger::error() << "Could not get any content for " << absPath << Qt::endl;
|
||||
Logger::error() << "Could not get any content for " << canonicalPath << Qt::endl;
|
||||
}
|
||||
|
||||
return this->dbService->saveFile(fileInfo, pageData);
|
@ -2,29 +2,25 @@
|
||||
#define FILESAVER_H
|
||||
#include <QSqlDatabase>
|
||||
#include <QFileInfo>
|
||||
#include "command.h"
|
||||
#include "pagedata.h"
|
||||
#include "filedata.h"
|
||||
#include "sqlitedbservice.h"
|
||||
|
||||
#include "common.h"
|
||||
class FileSaver
|
||||
{
|
||||
private:
|
||||
SqliteDbService *dbService;
|
||||
|
||||
protected:
|
||||
SaveFileResult addFile(QString path);
|
||||
SaveFileResult updateFile(QString path);
|
||||
QStringList excludedPaths = Common::excludedPaths();
|
||||
|
||||
public:
|
||||
FileSaver(SqliteDbService &dbService);
|
||||
SaveFileResult addFile(QString path);
|
||||
SaveFileResult updateFile(QString path);
|
||||
SaveFileResult saveFile(const QFileInfo &fileInfo);
|
||||
int processFiles(const QVector<QString> paths, std::function<SaveFileResult(QString path)> saverFunc,
|
||||
bool keepGoing, bool verbose);
|
||||
int addFiles(const QVector<QString> paths, bool keepGoing, bool verbose);
|
||||
int updateFiles(const QVector<QString> paths, bool keepGoing, bool verbose);
|
||||
|
||||
;
|
||||
};
|
||||
|
||||
#endif // FILESAVER_H
|
36
shared/filescanworker.cpp
Normal file
36
shared/filescanworker.cpp
Normal file
@ -0,0 +1,36 @@
|
||||
#include "filescanworker.h"
|
||||
#include "logger.h"
|
||||
FileScanWorker::FileScanWorker(SqliteDbService &db, ConcurrentQueue<QString> &queue, int batchsize,
|
||||
std::atomic<bool> &stopToken)
|
||||
{
|
||||
this->dbService = &db;
|
||||
this->queue = &queue;
|
||||
this->batchsize = batchsize;
|
||||
this->stopToken = &stopToken;
|
||||
}
|
||||
|
||||
void FileScanWorker::run()
|
||||
{
|
||||
FileSaver saver{*this->dbService};
|
||||
auto paths = queue->dequeue(batchsize);
|
||||
for(QString &path : paths)
|
||||
{
|
||||
SaveFileResult sfr;
|
||||
try
|
||||
{
|
||||
sfr = saver.addFile(path);
|
||||
}
|
||||
catch(std::exception &e)
|
||||
{
|
||||
Logger::error() << e.what();
|
||||
sfr = PROCESSFAIL; // well...
|
||||
}
|
||||
emit result({path, sfr});
|
||||
if(stopToken->load(std::memory_order_relaxed)) // TODO: relaxed should suffice here, but recheck
|
||||
{
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
}
|
||||
emit finished();
|
||||
}
|
29
shared/filescanworker.h
Normal file
29
shared/filescanworker.h
Normal file
@ -0,0 +1,29 @@
|
||||
#ifndef FILESCANWORKER_H
|
||||
#define FILESCANWORKER_H
|
||||
#include <QString>
|
||||
#include <QObject>
|
||||
#include <QtConcurrent>
|
||||
#include <utility>
|
||||
#include "paralleldirscanner.h"
|
||||
#include "filesaver.h"
|
||||
|
||||
typedef std::pair<QString, SaveFileResult> FileScanResult;
|
||||
|
||||
class FileScanWorker : public QObject, public QRunnable
|
||||
{
|
||||
Q_OBJECT
|
||||
protected:
|
||||
SqliteDbService *dbService;
|
||||
ConcurrentQueue<QString> *queue;
|
||||
int batchsize;
|
||||
std::atomic<bool> *stopToken;
|
||||
|
||||
public:
|
||||
FileScanWorker(SqliteDbService &db, ConcurrentQueue<QString> &queue, int batchsize, std::atomic<bool> &stopToken);
|
||||
void run() override;
|
||||
signals:
|
||||
void result(FileScanResult);
|
||||
void finished();
|
||||
};
|
||||
|
||||
#endif // FILESCANWORKER_H
|
160
shared/indexer.cpp
Normal file
160
shared/indexer.cpp
Normal file
@ -0,0 +1,160 @@
|
||||
#include "indexer.h"
|
||||
#include "logger.h"
|
||||
#include "wildcardmatcher.h"
|
||||
|
||||
Indexer::Indexer(SqliteDbService &db)
|
||||
{
|
||||
dirScanner = QSharedPointer<ParallelDirScanner>(new ParallelDirScanner());
|
||||
connect(dirScanner.data(), &ParallelDirScanner::scanComplete, this, &Indexer::dirScanFinished);
|
||||
connect(dirScanner.data(), &ParallelDirScanner::progress, this, &Indexer::dirScanProgress);
|
||||
this->db = &db;
|
||||
}
|
||||
|
||||
void Indexer::beginIndexing()
|
||||
{
|
||||
this->runningWorkers = 0;
|
||||
this->currentScanProcessedCount = 0;
|
||||
this->currentIndexResult = IndexResult();
|
||||
this->currentIndexResult.begin = QDateTime::currentDateTime();
|
||||
QVector<QString> dirs;
|
||||
|
||||
WildcardMatcher wildcardMatcher;
|
||||
wildcardMatcher.setPatterns(this->ignorePattern);
|
||||
for(QString &path : this->pathsToScan)
|
||||
{
|
||||
if(wildcardMatcher.match(path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
QFileInfo info{path};
|
||||
if(info.isDir())
|
||||
{
|
||||
dirs.append(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
this->filePathTargetsQueue.enqueue(path);
|
||||
}
|
||||
}
|
||||
|
||||
if(!dirs.empty())
|
||||
{
|
||||
this->dirScanner->setPaths(dirs);
|
||||
this->dirScanner->setIgnorePatterns(this->ignorePattern);
|
||||
|
||||
this->dirScanner->scan();
|
||||
}
|
||||
|
||||
this->workerCancellationToken.store(false, std::memory_order_seq_cst);
|
||||
launchWorker(this->filePathTargetsQueue, this->filePathTargetsQueue.remaining());
|
||||
}
|
||||
|
||||
void Indexer::setIgnorePattern(QStringList ignorePattern)
|
||||
{
|
||||
this->ignorePattern = ignorePattern;
|
||||
}
|
||||
|
||||
void Indexer::setTargetPaths(QVector<QString> pathsToScan)
|
||||
{
|
||||
this->pathsToScan = pathsToScan;
|
||||
}
|
||||
|
||||
void Indexer::setVerbose(bool verbose)
|
||||
{
|
||||
this->verbose = verbose;
|
||||
}
|
||||
|
||||
void Indexer::setKeepGoing(bool keepGoing)
|
||||
{
|
||||
this->keepGoing = keepGoing;
|
||||
}
|
||||
|
||||
void Indexer::requestCancellation()
|
||||
{
|
||||
this->dirScanner->cancel();
|
||||
this->workerCancellationToken.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
IndexResult Indexer::getResult()
|
||||
{
|
||||
return this->currentIndexResult;
|
||||
}
|
||||
|
||||
void Indexer::dirScanFinished()
|
||||
{
|
||||
Logger::info() << "Dir scan finished" << Qt::endl;
|
||||
if(!isRunning())
|
||||
{
|
||||
emit finished();
|
||||
}
|
||||
}
|
||||
|
||||
void Indexer::launchWorker(ConcurrentQueue<QString> &queue, int batchsize)
|
||||
{
|
||||
FileScanWorker *runnable = new FileScanWorker(*this->db, queue, batchsize, this->workerCancellationToken);
|
||||
connect(runnable, &FileScanWorker::result, this, &Indexer::processFileScanResult);
|
||||
connect(runnable, &FileScanWorker::finished, this, &Indexer::processFinishedWorker);
|
||||
++this->runningWorkers;
|
||||
QThreadPool::globalInstance()->start(runnable);
|
||||
}
|
||||
|
||||
void Indexer::dirScanProgress(int current, int total)
|
||||
{
|
||||
launchWorker(this->dirScanner->getResults(), current);
|
||||
emit pathsCountChanged(total);
|
||||
}
|
||||
|
||||
void Indexer::processFileScanResult(FileScanResult result)
|
||||
{
|
||||
if(result.second == DBFAIL || result.second == PROCESSFAIL || result.second == NOTFOUND)
|
||||
{
|
||||
this->currentIndexResult.results.append(result);
|
||||
if(!keepGoing)
|
||||
{
|
||||
this->requestCancellation();
|
||||
emit finished();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(verbose)
|
||||
{
|
||||
this->currentIndexResult.results.append(result);
|
||||
}
|
||||
}
|
||||
|
||||
if(result.second == OK)
|
||||
{
|
||||
++this->currentIndexResult.addedPaths;
|
||||
}
|
||||
else if(result.second == SKIPPED)
|
||||
{
|
||||
++this->currentIndexResult.skippedPaths;
|
||||
}
|
||||
else
|
||||
{
|
||||
++this->currentIndexResult.erroredPaths;
|
||||
}
|
||||
|
||||
if(currentScanProcessedCount++ == progressReportThreshold)
|
||||
{
|
||||
emit indexProgress(this->currentIndexResult.total(), this->currentIndexResult.addedPaths,
|
||||
this->currentIndexResult.skippedPaths, this->currentIndexResult.erroredPaths,
|
||||
this->dirScanner->pathCount());
|
||||
currentScanProcessedCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool Indexer::isRunning()
|
||||
{
|
||||
return this->runningWorkers > 0 || this->dirScanner->isRunning();
|
||||
}
|
||||
void Indexer::processFinishedWorker()
|
||||
{
|
||||
--this->runningWorkers;
|
||||
if(!isRunning())
|
||||
{
|
||||
emit finished();
|
||||
}
|
||||
}
|
92
shared/indexer.h
Normal file
92
shared/indexer.h
Normal file
@ -0,0 +1,92 @@
|
||||
#ifndef INDEXER_H
|
||||
#define INDEXER_H
|
||||
#include <QVector>
|
||||
#include <QObject>
|
||||
#include "sqlitedbservice.h"
|
||||
#include "paralleldirscanner.h"
|
||||
#include "filescanworker.h"
|
||||
|
||||
class IndexResult
|
||||
{
|
||||
public:
|
||||
QDateTime begin;
|
||||
QDateTime end;
|
||||
QVector<FileScanResult> results;
|
||||
|
||||
unsigned int addedPaths = 0;
|
||||
unsigned int skippedPaths = 0;
|
||||
unsigned int erroredPaths = 0;
|
||||
|
||||
unsigned int total()
|
||||
{
|
||||
return addedPaths + skippedPaths + erroredPaths;
|
||||
}
|
||||
|
||||
QVector<QString> failedPaths() const
|
||||
{
|
||||
QVector<QString> result;
|
||||
std::for_each(results.begin(), results.end(),
|
||||
[&result](FileScanResult res)
|
||||
{
|
||||
if(res.second == DBFAIL || res.second == PROCESSFAIL || res.second == NOTFOUND)
|
||||
{
|
||||
result.append(res.first);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
class Indexer : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
protected:
|
||||
bool verbose = false;
|
||||
bool keepGoing = true;
|
||||
SqliteDbService *db;
|
||||
|
||||
int progressReportThreshold = 50;
|
||||
int currentScanProcessedCount = 0;
|
||||
int runningWorkers = 0;
|
||||
|
||||
QVector<QString> pathsToScan;
|
||||
QSharedPointer<ParallelDirScanner> dirScanner;
|
||||
|
||||
QStringList ignorePattern;
|
||||
|
||||
/* Those path pointing to files not directories */
|
||||
ConcurrentQueue<QString> filePathTargetsQueue;
|
||||
|
||||
std::atomic<bool> workerCancellationToken;
|
||||
IndexResult currentIndexResult;
|
||||
void launchWorker(ConcurrentQueue<QString> &queue, int batchsize);
|
||||
|
||||
public:
|
||||
bool isRunning();
|
||||
|
||||
void beginIndexing();
|
||||
void setIgnorePattern(QStringList ignorePattern);
|
||||
void setTargetPaths(QVector<QString> pathsToScan);
|
||||
void setVerbose(bool verbose);
|
||||
void setKeepGoing(bool keepGoing);
|
||||
|
||||
void requestCancellation();
|
||||
|
||||
Indexer(SqliteDbService &db);
|
||||
IndexResult getResult();
|
||||
|
||||
public slots:
|
||||
void dirScanFinished();
|
||||
void dirScanProgress(int current, int total);
|
||||
void processFileScanResult(FileScanResult result);
|
||||
void processFinishedWorker();
|
||||
|
||||
signals:
|
||||
void pathsCountChanged(int total);
|
||||
void fileScanResult(FileScanResult *result);
|
||||
void indexProgress(unsigned int processedFiles, unsigned int added, unsigned int skipped, unsigned int failed,
|
||||
unsigned int totalPaths);
|
||||
void finished();
|
||||
};
|
||||
|
||||
#endif // INDEXER_H
|
134
shared/indexsyncer.cpp
Normal file
134
shared/indexsyncer.cpp
Normal file
@ -0,0 +1,134 @@
|
||||
#include <QDateTime>
|
||||
#include "filesaver.h"
|
||||
#include "indexsyncer.h"
|
||||
|
||||
IndexSyncer::IndexSyncer(SqliteDbService &dbService)
|
||||
{
|
||||
this->dbService = &dbService;
|
||||
}
|
||||
|
||||
void IndexSyncer::setDryRun(bool dryRun)
|
||||
{
|
||||
this->dryRun = dryRun;
|
||||
}
|
||||
|
||||
void IndexSyncer::setVerbose(bool verbose)
|
||||
{
|
||||
this->verbose = verbose;
|
||||
}
|
||||
|
||||
void IndexSyncer::setKeepGoing(bool keepGoing)
|
||||
{
|
||||
this->keepGoing = keepGoing;
|
||||
}
|
||||
|
||||
void IndexSyncer::setRemoveDeletedFromIndex(bool removeDeletedFromIndex)
|
||||
{
|
||||
this->removeDeletedFromIndex = removeDeletedFromIndex;
|
||||
}
|
||||
|
||||
void IndexSyncer::setPattern(QString pattern)
|
||||
{
|
||||
this->pattern = pattern;
|
||||
}
|
||||
|
||||
void IndexSyncer::sync()
|
||||
{
|
||||
this->stopToken.store(false, std::memory_order_relaxed);
|
||||
FileSaver saver(*this->dbService);
|
||||
QVector<FileData> files;
|
||||
int offset = 0;
|
||||
int limit = 10000;
|
||||
unsigned int processedRows = dbService->getFiles(files, pattern, offset, limit);
|
||||
|
||||
unsigned int totalUpdatesFilesCount = 0;
|
||||
unsigned int totalDeletedFilesCount = 0;
|
||||
unsigned int totalErroredFilesCount = 0;
|
||||
|
||||
while(processedRows > 0)
|
||||
{
|
||||
QVector<QString> filePathsToUpdate;
|
||||
for(FileData &fileData : files)
|
||||
{
|
||||
if(processedRows % 100 == 0 && this->stopToken.load(std::memory_order_relaxed))
|
||||
{
|
||||
emit finished(totalUpdatesFilesCount, totalDeletedFilesCount, totalErroredFilesCount);
|
||||
return;
|
||||
}
|
||||
if(Common::isMountPath(fileData.absPath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
QFileInfo fileInfo(fileData.absPath);
|
||||
if(fileInfo.exists())
|
||||
{
|
||||
if(fileInfo.isFile())
|
||||
{
|
||||
if(fileInfo.lastModified().toSecsSinceEpoch() != fileData.mtime)
|
||||
{
|
||||
if(!dryRun)
|
||||
{
|
||||
filePathsToUpdate.append(fileData.absPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
emit updatedDryRun(fileData.absPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(this->removeDeletedFromIndex)
|
||||
{
|
||||
if(!dryRun)
|
||||
{
|
||||
if(!this->dbService->deleteFile(fileData.absPath))
|
||||
{
|
||||
emit error("Error: Failed to delete " + fileData.absPath + " from the index");
|
||||
if(!this->keepGoing)
|
||||
{
|
||||
emit finished(totalUpdatesFilesCount, totalDeletedFilesCount, totalErroredFilesCount);
|
||||
return;
|
||||
}
|
||||
}
|
||||
emit removed(fileData.absPath);
|
||||
++totalDeletedFilesCount;
|
||||
}
|
||||
else
|
||||
{
|
||||
emit removedDryRun(fileData.absPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int updatedFilesCount = saver.updateFiles(filePathsToUpdate, keepGoing, verbose);
|
||||
unsigned int shouldHaveUpdatedCount = static_cast<unsigned int>(filePathsToUpdate.size());
|
||||
if(updatedFilesCount != shouldHaveUpdatedCount)
|
||||
{
|
||||
|
||||
totalErroredFilesCount += (shouldHaveUpdatedCount - updatedFilesCount);
|
||||
if(!keepGoing)
|
||||
{
|
||||
QString errorMsg = QString("Failed to update all files selected for updating in this batch. Updated") +
|
||||
updatedFilesCount + "out of" + shouldHaveUpdatedCount + "selected for updating";
|
||||
emit error(errorMsg);
|
||||
emit finished(totalUpdatesFilesCount, totalDeletedFilesCount, totalErroredFilesCount);
|
||||
}
|
||||
}
|
||||
offset += limit;
|
||||
files.clear();
|
||||
totalUpdatesFilesCount += updatedFilesCount;
|
||||
|
||||
processedRows = this->dbService->getFiles(files, pattern, offset, limit);
|
||||
}
|
||||
|
||||
emit finished(totalUpdatesFilesCount, totalDeletedFilesCount, totalErroredFilesCount);
|
||||
}
|
||||
|
||||
void IndexSyncer::cancel()
|
||||
{
|
||||
this->stopToken.store(true, std::memory_order_seq_cst);
|
||||
}
|
39
shared/indexsyncer.h
Normal file
39
shared/indexsyncer.h
Normal file
@ -0,0 +1,39 @@
|
||||
#ifndef INDEXSYNCER_H
|
||||
#define INDEXSYNCER_H
|
||||
#include "sqlitedbservice.h"
|
||||
|
||||
class IndexSyncer : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
SqliteDbService *dbService = nullptr;
|
||||
bool keepGoing = true;
|
||||
bool removeDeletedFromIndex = true;
|
||||
bool dryRun = false;
|
||||
bool verbose = false;
|
||||
QString pattern;
|
||||
|
||||
std::atomic<bool> stopToken{false};
|
||||
|
||||
public:
|
||||
IndexSyncer(SqliteDbService &dbService);
|
||||
|
||||
public slots:
|
||||
void sync();
|
||||
void cancel();
|
||||
void setDryRun(bool dryRun);
|
||||
void setVerbose(bool verbose);
|
||||
void setKeepGoing(bool keepGoing);
|
||||
void setRemoveDeletedFromIndex(bool removeDeletedFromIndex);
|
||||
void setPattern(QString pattern);
|
||||
|
||||
signals:
|
||||
void error(QString error);
|
||||
void removed(QString path);
|
||||
void removedDryRun(QString path);
|
||||
void updatedDryRun(QString path);
|
||||
void updated(QString path);
|
||||
void finished(unsigned int totalUpdated, unsigned int totalDeleted, unsigned int totalErrored);
|
||||
};
|
||||
|
||||
#endif // INDEXSYNCER_H
|
@ -169,6 +169,10 @@ void LooqsQuery::addToken(Token t)
|
||||
* TODO: It's a bit ugly still*/
|
||||
LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, bool mergeLoneWords)
|
||||
{
|
||||
if(expression.isEmpty())
|
||||
{
|
||||
return LooqsQuery{};
|
||||
}
|
||||
if(!checkParanthesis(expression))
|
||||
{
|
||||
throw LooqsGeneralException("Invalid paranthesis");
|
||||
@ -176,8 +180,9 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
|
||||
|
||||
QStringList loneWords;
|
||||
LooqsQuery result;
|
||||
QRegularExpression rx("((?<filtername>(\\.|\\w)+):(?<args>\\((?<innerargs>[^\\)]+)\\)|([\\w,])+)|(?<boolean>AND|OR)"
|
||||
"|(?<negation>!)|(?<bracket>\\(|\\))|(?<loneword>\\w+))");
|
||||
QRegularExpression rx(
|
||||
"((?<filtername>(\\.|\\w)+):(?<args>\\((?<innerargs>[^\\)]+)\\)|([\\p{L},])+)|(?<boolean>AND|OR)"
|
||||
"|(?<negation>!)|(?<bracket>\\(|\\))|(?<loneword>[\"\\p{L}]+))");
|
||||
QRegularExpressionMatchIterator i = rx.globalMatch(expression);
|
||||
auto previousWasBool = [&result] { return !result.tokens.empty() && ((result.tokens.last().type & BOOL) == BOOL); };
|
||||
auto previousWas = [&result](TokenType t) { return !result.tokens.empty() && (result.tokens.last().type == t); };
|
||||
@ -216,19 +221,8 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
|
||||
{
|
||||
throw LooqsGeneralException("Can't have two negations following each other");
|
||||
}
|
||||
if(!previousWasBool())
|
||||
{
|
||||
result.addToken(Token(BOOL_AND)); // Implicit and, our default operation
|
||||
}
|
||||
result.addToken(Token(NEGATION));
|
||||
}
|
||||
if(!result.tokens.isEmpty() && !previousWasBool() && !previousWas(NEGATION) && !previousWas(BRACKET_OPEN) &&
|
||||
bracket != ")")
|
||||
{
|
||||
// the current token isn't a negation, isn't a boolean. Thus, implicit AND is required
|
||||
result.addToken(Token(BOOL_AND));
|
||||
}
|
||||
|
||||
if(bracket != "")
|
||||
{
|
||||
if(bracket == "(")
|
||||
@ -255,7 +249,7 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
|
||||
|
||||
if(filtername != "")
|
||||
{
|
||||
TokenType tokenType;
|
||||
TokenType tokenType = WORD;
|
||||
QString value = m.captured("innerargs");
|
||||
if(value == "")
|
||||
{
|
||||
@ -266,15 +260,15 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
|
||||
throw LooqsGeneralException("value cannot be empty for filters");
|
||||
}
|
||||
|
||||
if(filtername == "path.contains")
|
||||
if(filtername == "p" || filtername == "path.contains")
|
||||
{
|
||||
tokenType = FILTER_PATH_CONTAINS;
|
||||
}
|
||||
else if(filtername == "path.starts")
|
||||
else if(filtername == "pb" || filtername == "path.starts")
|
||||
{
|
||||
tokenType = FILTER_PATH_STARTS;
|
||||
}
|
||||
else if(filtername == "path.ends")
|
||||
else if(filtername == "pe" || filtername == "path.ends")
|
||||
{
|
||||
tokenType = FILTER_PATH_ENDS;
|
||||
}
|
||||
@ -290,21 +284,21 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
|
||||
{
|
||||
tokenType = FILTER_CONTENT_PAGE;
|
||||
}
|
||||
else if(filtername ==
|
||||
"sort") // TODO: given this is not really a "filter", this feels slightly misplaced here
|
||||
// TODO: given this is not really a "filter", this feels slightly misplaced here
|
||||
else if(filtername == "sort")
|
||||
{
|
||||
if(!result.sortConditions.empty())
|
||||
{
|
||||
throw LooqsGeneralException("Two sort statements are illegal");
|
||||
}
|
||||
// TODO: hack, since we are not a "filter", we must remove a preceeding (implicit) boolean
|
||||
if((result.tokens.last().type & BOOL) == BOOL)
|
||||
{
|
||||
result.tokens.pop_back();
|
||||
}
|
||||
result.sortConditions = createSortConditions(value);
|
||||
continue;
|
||||
}
|
||||
else if(filtername == "limit")
|
||||
{
|
||||
result.limit = value.toInt();
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw LooqsGeneralException("Unknown filter provided!");
|
||||
@ -322,6 +316,26 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
|
||||
}
|
||||
}
|
||||
|
||||
/* Add our default implicit AND boolean condition where appropriate */
|
||||
QVector<Token> newTokens;
|
||||
|
||||
TokenType prevType = BOOL_AND;
|
||||
int needsBoolean = FILTER_CONTENT | FILTER_PATH | NEGATION;
|
||||
for(Token &t : result.tokens)
|
||||
{
|
||||
if(t.type == BRACKET_OPEN || t.type & needsBoolean)
|
||||
{
|
||||
if(!((prevType & BOOL) == BOOL) && !((prevType & NEGATION) == NEGATION) &&
|
||||
!((prevType & BRACKET_OPEN) == BRACKET_OPEN))
|
||||
{
|
||||
newTokens.append(Token(BOOL_AND));
|
||||
}
|
||||
}
|
||||
prevType = t.type;
|
||||
newTokens.append(t);
|
||||
}
|
||||
result.tokens = newTokens;
|
||||
|
||||
bool contentsearch = result.hasContentSearch();
|
||||
bool sortsForContent = std::any_of(result.sortConditions.begin(), result.sortConditions.end(),
|
||||
[](SortCondition c) { return c.field == CONTENT_TEXT; });
|
||||
|
@ -40,6 +40,7 @@ class LooqsQuery
|
||||
/* Helper field to determine quertype as well as to quickly check what kind of filters etc.
|
||||
* are being used in this query*/
|
||||
int tokensMask = 0;
|
||||
int limit = -1;
|
||||
QVector<Token> tokens;
|
||||
QVector<SortCondition> sortConditions;
|
||||
void addToken(Token t);
|
||||
@ -52,6 +53,14 @@ class LooqsQuery
|
||||
{
|
||||
return tokensMask;
|
||||
}
|
||||
int getLimit() const
|
||||
{
|
||||
return limit;
|
||||
}
|
||||
void setLimit(int limit)
|
||||
{
|
||||
this->limit = limit;
|
||||
}
|
||||
bool hasContentSearch();
|
||||
bool hasPathSearch();
|
||||
|
||||
|
5
shared/migrations/migrations.qrc
Normal file
5
shared/migrations/migrations.qrc
Normal file
@ -0,0 +1,5 @@
|
||||
<RCC>
|
||||
<qresource prefix="/looqs-migrations">
|
||||
<file>1.sql</file>
|
||||
</qresource>
|
||||
</RCC>
|
103
shared/paralleldirscanner.cpp
Normal file
103
shared/paralleldirscanner.cpp
Normal file
@ -0,0 +1,103 @@
|
||||
#include "paralleldirscanner.h"
|
||||
|
||||
#include <QRunnable>
|
||||
#include <QMutex>
|
||||
#include <QDirIterator>
|
||||
#include <QThread>
|
||||
#include <QThreadPool>
|
||||
#include <functional>
|
||||
#include "dirscanworker.h"
|
||||
#include "logger.h"
|
||||
|
||||
ParallelDirScanner::ParallelDirScanner()
|
||||
{
|
||||
this->threadpool.setMaxThreadCount(QThread::idealThreadCount() / 2);
|
||||
}
|
||||
|
||||
ConcurrentQueue<QString> &ParallelDirScanner::getResults()
|
||||
{
|
||||
return this->resultPathsQueue;
|
||||
}
|
||||
|
||||
void ParallelDirScanner::setIgnorePatterns(QStringList patterns)
|
||||
{
|
||||
this->ignorePatterns = patterns;
|
||||
}
|
||||
|
||||
void ParallelDirScanner::setPaths(QVector<QString> paths)
|
||||
{
|
||||
this->paths = paths;
|
||||
}
|
||||
|
||||
void ParallelDirScanner::cancel()
|
||||
{
|
||||
this->stopToken.store(true, std::memory_order_seq_cst);
|
||||
}
|
||||
|
||||
void ParallelDirScanner::handleWorkersProgress(unsigned int progress)
|
||||
{
|
||||
this->processedPaths += progress;
|
||||
if(!this->stopToken.load(std::memory_order_seq_cst))
|
||||
emit this->progress(progress, this->processedPaths);
|
||||
}
|
||||
|
||||
void ParallelDirScanner::handleWorkersFinish()
|
||||
{
|
||||
// no mutexes required due to queued connection
|
||||
++finishedWorkers;
|
||||
if(this->stopToken.load(std::memory_order_seq_cst) || finishedWorkers == getThreadsNum())
|
||||
{
|
||||
running = false;
|
||||
emit scanComplete();
|
||||
}
|
||||
delete QObject::sender();
|
||||
}
|
||||
|
||||
unsigned int ParallelDirScanner::getThreadsNum() const
|
||||
{
|
||||
int threadsNum = this->threadpool.maxThreadCount();
|
||||
if(threadsNum > this->paths.size())
|
||||
{
|
||||
threadsNum = this->paths.size();
|
||||
}
|
||||
return threadsNum;
|
||||
}
|
||||
|
||||
void ParallelDirScanner::scan()
|
||||
{
|
||||
this->stopToken.store(false, std::memory_order_relaxed);
|
||||
this->finishedWorkers = 0;
|
||||
this->processedPaths = 0;
|
||||
this->targetPathsQueue.clear();
|
||||
this->resultPathsQueue.clear();
|
||||
|
||||
this->targetPathsQueue.enqueue(this->paths);
|
||||
int threadsNum = getThreadsNum();
|
||||
if(threadsNum == 0)
|
||||
{
|
||||
emit scanComplete();
|
||||
return;
|
||||
}
|
||||
running = true;
|
||||
for(int i = 0; i < threadsNum; i++)
|
||||
{
|
||||
DirScanWorker *runnable = new DirScanWorker(this->targetPathsQueue, this->resultPathsQueue,
|
||||
this->ignorePatterns, 1000, this->stopToken);
|
||||
runnable->setAutoDelete(false);
|
||||
connect(runnable, &DirScanWorker::progress, this, &ParallelDirScanner::handleWorkersProgress,
|
||||
Qt::QueuedConnection);
|
||||
connect(runnable, &DirScanWorker::finished, this, &ParallelDirScanner::handleWorkersFinish,
|
||||
Qt::QueuedConnection);
|
||||
threadpool.start(runnable);
|
||||
}
|
||||
}
|
||||
|
||||
bool ParallelDirScanner::isRunning()
|
||||
{
|
||||
return this->running;
|
||||
}
|
||||
|
||||
unsigned int ParallelDirScanner::pathCount()
|
||||
{
|
||||
return this->processedPaths;
|
||||
}
|
49
shared/paralleldirscanner.h
Normal file
49
shared/paralleldirscanner.h
Normal file
@ -0,0 +1,49 @@
|
||||
#ifndef PARALLELDIRSCANNER_H
|
||||
#define PARALLELDIRSCANNER_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QMutex>
|
||||
#include <atomic>
|
||||
#include <QThreadPool>
|
||||
#include "concurrentqueue.h"
|
||||
class ParallelDirScanner : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
protected:
|
||||
QStringList ignorePatterns;
|
||||
QThreadPool threadpool;
|
||||
|
||||
unsigned int finishedWorkers = 0;
|
||||
unsigned int processedPaths = 0;
|
||||
|
||||
std::atomic<bool> stopToken;
|
||||
|
||||
bool running = false;
|
||||
|
||||
QVector<QString> paths;
|
||||
ConcurrentQueue<QString> targetPathsQueue;
|
||||
ConcurrentQueue<QString> resultPathsQueue;
|
||||
unsigned int getThreadsNum() const;
|
||||
|
||||
public:
|
||||
ParallelDirScanner();
|
||||
|
||||
ConcurrentQueue<QString> &getResults();
|
||||
void setIgnorePatterns(QStringList patterns);
|
||||
void setPaths(QVector<QString> paths);
|
||||
void scan();
|
||||
bool isRunning();
|
||||
|
||||
unsigned int pathCount();
|
||||
|
||||
signals:
|
||||
void scanComplete();
|
||||
void progress(int, int);
|
||||
public slots:
|
||||
void cancel();
|
||||
private slots:
|
||||
void handleWorkersProgress(unsigned int progress);
|
||||
void handleWorkersFinish();
|
||||
};
|
||||
|
||||
#endif // PARALLELDIRSCANNER_H
|
@ -9,6 +9,7 @@
|
||||
#include "odtprocessor.h"
|
||||
#include "odsprocessor.h"
|
||||
#include "../submodules/exile.h/exile.h"
|
||||
#include "common.h"
|
||||
#include "logger.h"
|
||||
|
||||
static DefaultTextProcessor *defaultTextProcessor = new DefaultTextProcessor();
|
||||
@ -22,10 +23,15 @@ static QMap<QString, Processor *> processors{
|
||||
{"py", defaultTextProcessor}, {"xml", nothingProcessor}, {"html", tagStripperProcessor},
|
||||
{"java", defaultTextProcessor}, {"js", defaultTextProcessor}, {"cpp", defaultTextProcessor},
|
||||
{"c", defaultTextProcessor}, {"sql", defaultTextProcessor}, {"odt", odtProcessor},
|
||||
{"ods", odsProcessor}};
|
||||
{"ods", odsProcessor}, {"svg", nothingProcessor}};
|
||||
|
||||
void SandboxedProcessor::enableSandbox(QString readablePath)
|
||||
{
|
||||
if(Common::noSandboxModeRequested())
|
||||
{
|
||||
qInfo() << "Sandbox is disabled!" << Qt::endl;
|
||||
return;
|
||||
}
|
||||
struct exile_policy *policy = exile_init_policy();
|
||||
if(policy == NULL)
|
||||
{
|
||||
@ -34,10 +40,11 @@ void SandboxedProcessor::enableSandbox(QString readablePath)
|
||||
}
|
||||
policy->namespace_options = EXILE_UNSHARE_NETWORK | EXILE_UNSHARE_USER;
|
||||
|
||||
std::string readablePathLocation;
|
||||
if(!readablePath.isEmpty())
|
||||
{
|
||||
std::string readablePathLocation = readablePath.toStdString();
|
||||
if(exile_append_path_policy(policy, EXILE_FS_ALLOW_ALL_READ, readablePathLocation.c_str()) != 0)
|
||||
readablePathLocation = readablePath.toStdString();
|
||||
if(exile_append_path_policies(policy, EXILE_FS_ALLOW_ALL_READ, readablePathLocation.c_str()) != 0)
|
||||
{
|
||||
qCritical() << "Failed to add path policies";
|
||||
exit(EXIT_FAILURE);
|
||||
@ -50,7 +57,7 @@ void SandboxedProcessor::enableSandbox(QString readablePath)
|
||||
int ret = exile_enable_policy(policy);
|
||||
if(ret != 0)
|
||||
{
|
||||
qDebug() << "Failed to establish sandbox: " << ret;
|
||||
qCritical() << "Failed to establish sandbox: " << ret;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
exile_free_policy(policy);
|
||||
@ -74,9 +81,16 @@ void SandboxedProcessor::printResults(const QVector<PageData> &pageData)
|
||||
int SandboxedProcessor::process()
|
||||
{
|
||||
QFileInfo fileInfo(this->filePath);
|
||||
Processor *processor = processors.value(fileInfo.suffix(), nothingProcessor);
|
||||
|
||||
if(processor == nothingProcessor)
|
||||
Processor *processor = processors.value(fileInfo.suffix(), nullptr);
|
||||
if(processor == nullptr)
|
||||
{
|
||||
/* TODO: Not sandboxed */
|
||||
if(Common::isTextFile(fileInfo))
|
||||
{
|
||||
processor = defaultTextProcessor;
|
||||
}
|
||||
}
|
||||
if(processor == nullptr || processor == nothingProcessor)
|
||||
{
|
||||
/* Nothing to do */
|
||||
return NOTHING_PROCESSED;
|
||||
@ -102,7 +116,7 @@ int SandboxedProcessor::process()
|
||||
}
|
||||
catch(LooqsGeneralException &e)
|
||||
{
|
||||
Logger::error() << "Error while processing" << absPath << ":" << e.message << Qt::endl;
|
||||
Logger::error() << "SandboxedProcessor: Error while processing" << absPath << ":" << e.message << Qt::endl;
|
||||
return 3 /* PROCESSFAIL */;
|
||||
}
|
||||
|
@ -1,12 +1,14 @@
|
||||
#ifndef SANDBOXEDPROCESSOR_H
|
||||
#define SANDBOXEDPROCESSOR_H
|
||||
#include <QString>
|
||||
#include <QMimeDatabase>
|
||||
#include "pagedata.h"
|
||||
|
||||
class SandboxedProcessor
|
||||
{
|
||||
private:
|
||||
QString filePath;
|
||||
QMimeDatabase mimeDatabase;
|
||||
|
||||
void enableSandbox(QString readablePath = "");
|
||||
void printResults(const QVector<PageData> &pageData);
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user