105 次代码提交

作者 SHA1 备注 提交日期
02dd7b64b5 gui: PreviewGeneratorOdt: Adjust for DocumentProcessResult 2023-05-14 14:28:11 +02:00
7c30124743 fixup! shared: Add DocumentProcessResult 2023-05-14 14:27:22 +02:00
6a8323f2cf cli: cli.pro: Add poppler include path 2023-05-14 14:27:06 +02:00
763bc47a89 shared: LooqsQuery: Add outline search filters 2023-05-14 14:23:57 +02:00
517e62dca2 shared: sqlitesearch: Begin outline search 2023-05-14 14:23:21 +02:00
0f47f581b3 shared: SqliteDbService: Add insertOutline(), Use DocumentProcessResult 2023-05-14 14:21:22 +02:00
18b18d5103 shared: FileSaver: Use DocumentProcessResult 2023-05-14 14:20:25 +02:00
f4eed7a6ef fixup! shared: processors: Use DocumentProcessResult instead of PageData vector 2023-05-14 14:19:28 +02:00
6878f7846a shared: token: Add FILTER_OUTLINE_CONTAINS 2023-05-14 14:19:07 +02:00
b2ae0e488f PdfProcessor: Extract outline from documents 2023-05-14 14:15:50 +02:00
02a371b81e shared: processors: Use DocumentProcessResult instead of PageData vector 2023-05-14 14:14:59 +02:00
d960570171 shared: Add DocumentProcessResult
This should be returned by processors
2023-05-14 14:07:15 +02:00
c5713f5839 shared: Introduce DocumentOutlineEntry 2023-05-14 14:06:24 +02:00
8550506517 migrations: Add 6.sql: Begin outline index 2023-05-14 14:05:26 +02:00
2b1dc72410 Release v0.9, Update docs 2023-05-07 20:18:55 +02:00
22fee1d064 shared: TokenType: FILTER_TAG_ASSIGNED is not a content search token 2023-05-07 17:11:31 +02:00
50a5c399c4 gui: PreviewGeneratorPlainText: Don't add header if we have nothing to show 2023-05-07 17:11:31 +02:00
4b3ebb08c2 cli: commandadd: Improve help message 2023-05-07 17:11:31 +02:00
4c5643e342 cli,shared: Add remove, show and list for tags 2023-05-07 17:11:31 +02:00
e8d217e191 cli: CommandAdd: Add verbose (-v) 2023-05-07 17:11:31 +02:00
4604970f9d shared: Indexer: Add setProgressReportThreshold() 2023-05-01 23:52:45 +02:00
6cd7a92576 shared: Indexer: Fix case where errors did not increase counter 2023-05-01 23:51:00 +02:00
9540f27c95 gui: Indexing: Disable 'Add' and '...' button when indexing 2023-04-10 19:55:24 +02:00
244e6aa95e gui: Add tag checkboxes and inputdialog for search context menu 2023-04-10 19:55:24 +02:00
3e3a4d0cd4 cli: CommandTag: Use TagManager 2023-04-10 19:55:24 +02:00
94fbdb5a92 shared: sqlitesearch: Allow filtering by tags 2023-04-10 19:55:24 +02:00
abd1b94235 shared: LooqsQuery: Add tag:(),t:() filters to filter by tags 2023-04-10 19:55:24 +02:00
d2dcc2f95b shared: sqlitedbservice: Add setTags(),getTagsForPath(),getTags() 2023-04-10 19:55:24 +02:00
f324da0369 shared: Begin TagManager 2023-04-10 18:31:22 +02:00
a3cfb7ade1 shared: FileScanWorker: Catch LooqsGeneralException for better error msgs 2023-04-02 21:41:35 +02:00
44b9986166 cli: Begin 'tag' command 2023-04-02 21:41:35 +02:00
4fe745e858 shared: sqlitedbservice: Begin addTag() 2023-04-02 21:41:35 +02:00
a0b95479e2 migrations: Add 5.sql: Tag support 2023-04-02 21:41:35 +02:00
07630c3b36 gui: main: Fix exiting after failed migration 2023-04-02 21:41:35 +02:00
a7c4ad5e7c gui: Only enable 'Previews' tab if previews can be generated 2023-04-02 21:41:35 +02:00
32c2653b0f shared: FileSaver: addFile(): Consider fillExistingContentless 2023-04-02 21:41:35 +02:00
a869d677a3 shared: sqlitedbservice: Introduce exec(),execBool(). Refactor 2023-04-02 21:41:35 +02:00
2550af307f gui: mainwindow: Default to index everything 2023-03-26 15:36:23 +02:00
0b829215e5 shared: LooqsQuery: Remove explicit copy constructor 2023-03-12 16:50:37 +01:00
566c4a8c58 tree: Resolve clang-tidy, clazy, compiler warnings 2023-03-12 16:50:25 +01:00
3d0c236cb3 submodules: exile.h: Sync 2023-03-12 10:08:58 +01:00
590a8888fc gui: Add index options group in index tab 2023-01-08 17:37:28 +01:00
ccc4d09b36 shared: FilesSverOptions: Rename members 2023-01-08 17:37:28 +01:00
8298b675aa cli: CommandAdd: Implement --no-content and --fill-content 2023-01-08 17:37:28 +01:00
71789b5b56 shared: SqliteDbService: Add queryFileType() 2023-01-08 17:37:28 +01:00
363d207ccc LICENSE: Update copyright year 2023-01-08 17:37:28 +01:00
4b1522b82a Introduce FileSaverOptions to consolidate common parameters 2023-01-08 17:37:28 +01:00
efca45b88a gui sandbox: Allow wpath to improve poppler text rendering
Apparently poppler or something needs open() with write
flags to render pdfs with proper fonts.

Landlock guards file system write access, so this is fine.
2023-01-08 17:37:28 +01:00
0cd19b53e4 gui: PreviewGeneratorPdf: Enable Text hinting 2023-01-08 17:37:28 +01:00
889725033a gui: mainwindow: Refactor to use new PreviewCoordinator 2023-01-08 17:37:28 +01:00
8485a25b21 gui: Introduce PreviewCoordinator
Move some preview generation logic to PreviewCoordinator
2023-01-08 17:37:28 +01:00
57f0afaf91 gui: mainwindow: Fix typo in method name 2022-11-22 20:29:32 +01:00
20a1f8b2cd Release v0.8.1 2022-11-19 11:54:24 +01:00
a47af257f3 gui: previews: Fix incorrect pos calculation in cached previews
The cached order position introduced in 42e9ac5 is incorrect
as it does not consider the case when we are viewing any
other result page than the first.

Fix this by considering which page we are in when calculating
the offset
2022-11-18 22:22:11 +01:00
9686ef30c7 gui: PreviewResult*: Wrap result in shared pointer immediatly 2022-11-13 17:37:35 +01:00
abce4cfcd9 gui: PreviewGeneratorPlaintext: Escape words we pass to QRegularExpression 2022-11-13 17:27:45 +01:00
d55187a71c submodules: exile.h: Sync to current master 2022-10-26 13:14:03 +02:00
9e1bc98f38 gui: mainwindow.h: Initialize preview-related members with a default 2022-10-26 13:13:20 +02:00
496aefaa09 shared: sqlitesearch: Remove unused var 2022-10-26 13:10:00 +02:00
b4320f611b Release v0.8, minor README changes 2022-10-22 17:20:20 +02:00
1b1ab2387e gui: PreviewGeneratorPdf: Guard cache lookup with mutex
No guarantes the read-only lookup is thread-safe so better
just lock there too
2022-10-22 15:08:29 +02:00
49a1a14009 gui: previewgenerator: Use QHash and guard using mutexes 2022-10-22 15:07:46 +02:00
48ca25abe3 gui: mainwindow: Reorder members for readability 2022-10-19 11:56:21 +02:00
42e9ac5f41 gui: previews: Ensure order matches relevance ranking
Previously, the order of previews would depend simply
on which generator would finish first.

Fix this by caching out of order previews. This may
cause a small delay but should overall be hardly noticable.
2022-10-19 11:11:29 +02:00
7d3c24e6e1 update README.md,HACKING.md 2022-10-18 16:19:25 +02:00
c155d25a37 shared: sqlitesearch: Search trigram index too
Search the trigram index too, combining the results
with the results of the "normal" fts index.

Prioritize the latter since it makes more sense to
rank whole words higher.
2022-10-18 16:06:10 +02:00
583d5babf3 shared: sqlitedbservice: Insert to trigram index too 2022-10-18 16:05:19 +02:00
45659cdc59 shared: migrations: Add 4.sql: Begin trigram index 2022-10-18 16:04:00 +02:00
3022bbdfb5 sqlitesearch: escapeftsArgument: Fix wrong escaping of phrase queries 2022-10-02 19:55:10 +02:00
b6ac652ade shared: indexer: Report progress more often
Processing dirs with large docs takes time and waiting till the threshold
is reached can be a bit annoying in those cases, so report if last report
was 10+ seconds ago.
2022-09-23 20:08:00 +02:00
785a517d62 Release v0.7 2022-09-10 15:15:39 +02:00
bfb5d71448 submodules: exile.h: Update 2022-09-10 15:15:39 +02:00
3e512b8be0 USAGE.md: Update 2022-09-10 15:15:31 +02:00
2ab6e40d44 gui: mainwindow: Set comboPreviewFiles size policy to Maximum
The current expanding setting resizes, somehow, the mainwindow
when a path name is quite long.
2022-08-28 17:48:16 +02:00
31f0568a87 shared: LimitQueue: Change limit type to int
More consistent with "QQueue::size()" and silences warning
2022-08-28 13:10:39 +02:00
238f9add49 gui: Set a more reasonable maximum width for previews
They won't be this large but in particular for vertical scroll,
this makes way more sense.
2022-08-28 13:05:33 +02:00
7c63ee9178 gui: mainwindow: Set center alignment for previews
Noticable now that we have vertical scrolling
2022-08-28 13:04:06 +02:00
1edfcc8f23 gui: PreviewGeneratorPlainText: Escape html before working on text
We use this semi-HTML mode to highlight words, but if we already
have tags in the document this does not work quite well.

Thus, escape the string before further processing it
2022-08-28 13:01:46 +02:00
2df273dee3 gui: PreviewGenerator*: Fallback to partial highlighting if no whole word match 2022-08-28 12:44:42 +02:00
5a47f5949f gui: PreviewGeneratorPlainText: Rework snippets selection
The current snippet selection is useless for many queries.

Attempt a more reasonable snippet selection by prioritizing
those where all words are contained. The more words a snippet
has, the more important it is considered.Therefore, those will
be at the top.

Only highlight whole words
2022-08-27 22:18:43 +02:00
e6a0c0daee gui: PreviewGeneratorPdf: Only highlight whole words
Only highlight whole words, which is less confusing
2022-08-27 22:17:10 +02:00
11b070ed42 gui: mainwindow: Improve preview status reporting
Better represent the state of available previews.

Only add paths to ui->comboPreviewFiles once
2022-08-27 12:04:35 +02:00
47874b3706 gui: ipcworker,ipcserver: Refactor
Crashes were observed, faulting in libQtNetwork.
Those were rather rare. We also have no traces.

Probably depends on some order signal/slots were
processed. Remove shared states between connections,
such as the IPCPreviewWorker and socket instance in IPCServer.
2022-08-27 11:15:45 +02:00
10d61acbd0 shared,gui: SearchResult: remove page vector
Since the previous commit we don't group the results
anymore, making the vector redundant
2022-08-24 00:00:11 +02:00
eef0fae137 shared,gui,cli: Fix intra-file ordering for content search results
group_concat() does not preserve order of the ORDRE BY rank,
making the ordering quite meaningless for pages inside a file.

The recently introduced combobox to filter on a per file basis
should anyway be prefered than any kind of grouping in queries.

So we just remove the groupings here.

"All files" in the previews tab thus should show the best results
first now, from any files part of the result set.

A GUI option to sort by page instead of rank can be considered.
2022-08-23 23:44:47 +02:00
d8205a0da4 gui: Disable search box as long as previews are being generated
Otherwise "spamming" queries can cause high load and
many outstanding may arrive only to be discarded anyway
for not being part of the recent query.
2022-08-23 17:37:05 +02:00
877224b6e1 gui: mainwindow: Only trigger preview generation when in tab
Indirectly generation would fire when we set combobox index
programitcally. So it's slot should only trigger the generation
when the user is viewing the preview tab
2022-08-23 17:35:52 +02:00
14730ed208 gui: mainwindow: Add vertical scroll option, default to it
Seems horizontal mode is too unusual according to multiple
feedback.

Allow choosing this the mode in the settings
2022-08-21 22:57:48 +02:00
fe610d3068 mainwindow: Allow CTRL + mouse wheel to zoom on previews 2022-08-21 18:42:32 +02:00
0c1b57d911 mainwindow: Save/Restore history 2022-08-21 17:48:43 +02:00
2885e40a3a mainwindow: Add search history. Allow going up/down with arrow keys 2022-08-21 17:47:11 +02:00
c0f4087937 sqlitesearch: escapeFtsArgument: Fix handling of '*' prefix search
The * must not be in quotes
2022-08-21 07:55:49 +02:00
46c52afe59 Release v0.6 2022-08-14 23:15:19 +02:00
431abfe7c0 USAGE.md: Update 2022-08-14 20:28:17 +02:00
47c19d121a gui: mainwindow: Add CTRL(+Shift+)Tab shortcut to switch between tabs 2022-08-14 20:25:44 +02:00
166c051cfb gui: mainwindow: Add CTRL+F and CTRL+W shortcuts
Add shortcuts to make entering queries more efficient

CTRL+F: Highlights rightmost filter, e. g. c:(word1 word2) would
highlight everything between (), so "word1 word" here. Alternatively,
highlights lone words, so p:(docs) word1, would highlight word1.

CTRL+W: Removes last filter or words.
2022-08-14 20:25:44 +02:00
47d0440ffb gui: mainwindow: Add checkbox to remove current database 2022-08-14 20:25:44 +02:00
d900d58f26 shared: migrations: Add 3.sql: Drop potentailly harmful trigger
In [1] it's stated that "If the values "inserted" into the text
columns as part of a 'delete' command are not the same as those
currently stored within the table, the results may be unpredictable."

It's to be assumed only inserting ftsid is unpredictable. We
have no way for a proper delete because files are not immutable
or may have been deleted.

For now the index will contain entries for files that don't exist.
They won't appear in search results as they won't be joined
in the query.

[1] https://www.sqlite.org/fts5.html#the_delete_command
2022-08-14 20:24:21 +02:00
eb58b8f770 gui: Clear previews always on new search results
If a first search generates previews and the next one does
not, old entries would still have been visible.

So we just clear them once we get results.
2022-08-06 10:10:45 +02:00
9a70a821bd gui: PreviewGeneratorPlainText: Show line numbers
Generate previews that show the line number and surrounding
lines (like grep -C) for context.
2022-08-06 10:01:24 +02:00
89bf65d9bb gui: PreviewGeneratorPlaintext: Add MAX_SNIPPETS const, remove redundant loop 2022-08-06 09:35:00 +02:00
ad06497b4b shared: Add LimitQueue which discards oldest entry once limit hit 2022-08-06 09:06:00 +02:00
00abc6bc1b gui, shared: Fix and simplify word extraction regexes
They did not work for chars like '-', causing errors.

We can actually just extract non-space chars for these cases.
2022-08-06 08:57:39 +02:00
e8b89b77ab Release v0.5.1 2022-07-30 10:11:44 +02:00
77f5c7e39d gui: mainwindow: Revert pathsQuery to original behaviour
Since 7c5c91e we wrongly merge lone words for paths queries too.
This creates unintended behaviour.

Fix it by creating a new paths query without merged words, which
restores the original behaviour.

Also, get rid of some redundant calls to createFinalTokens()
2022-07-30 10:01:51 +02:00
共有 78 个文件被更改,包括 2397 次插入522 次删除

查看文件

@ -1,4 +1,76 @@
# looqs: Release notes # looqs: Release notes
## 2023-05-07 - v0.9
Highlights: Tag support. Also begin new index mode to only index metadata (currently only path + file size, more to come).
Note: Upgrading can take some time as new column indexes will be added
CHANGES:
- gui: Improve font rendering in previews
- gui: Allow indexing only metadata
- gui: Allow adding content for files which only had metadata indexed before
- gui: Allow assigning tags by right clicking on paths
- cli: "add" command: Implement --verbose (-v)
- cli: "add" command: Implement --no-content and --fill-content
- cli: Add "tag" command which allows managing tags for paths.
- search: Add "tag:()", "t:()" filters
- Minor improvements and refactorings under the hood
- Add packages: Ubuntu 23.04.
## 2022-11-19 - v0.8.1
CHANGES:
- Fix regression causing previews in second (and higher) result page to not render
- Minor improvements
## 2022-10-22 - v0.8
CHANGES:
- For new, not previously indexed files, start creating an additional index using sqlite's experimental trigram tokenizer. Thanks to that, we can now match substrings >= 3 of an unicode sequence. Results of the usual index are prioritized.
- GUI: Ensure order of previews matches ranking exactly. Previously, it depended simply on the time preview generators took, i. e. it was more or less a race.
- Report progress more often during indexing, so users don't get the impression that it's stuck when processing dirs with large documents.
- Fix a regression that caused phrase queries to be broken
- Minor improvements
- Add packages: Ubuntu 22.10.
## 2022-09-10 - v0.7
CHANGES:
- GUI: Add vertical scroll option, default to it. Most feedback considered horizontal scrolling unnatural.
- GUI: Previews: Improve plaintext preview snippet selection by prioritizing those which contain the most search terms
- GUI: Previews: Only highlight whole words, not parts in words.
- GUI: Previews: Don't treat text wrapped inside '<' '>' in plaintext files as HTMl tags which caused such text to get lost in previews.
- GUI: Avoid triggering preview generation in some cases even when previews tab is not the active one
- GUI: Implement a search history. Allow going up/down with arrow keys in the search field.
- GUI: Previews: Allow CTRL + mouse wheel to zoom in on previews
- General: Fix an incorrect sqlite query which caused the ranking information of search results to be lost. "All files" filter in the previews tab therefore now orders by the seemingly most relevant pages, across all documents.
- General: Fix handling of content search queries with prefix terms (those ending in '*').
- GUI: Show how many results are previewable.
- GUI: Refactor to improve stability of sandboxed IPC worker in order to avoid rare segfaults.
## 2022-08-14 - v0.6
This release features multiple fixes and enhancements.
Bad news first: It drops a trivial trigger that appeared to work quite fine, but silently may cause "unpredictability" of the sqlite FTS5 index ( [9422a5b494](https://github.com/quitesimpleorg/looqs/commit/9422a5b494dabd0f1324dc2f92a34c3036137414) ). As a result, FTS queries may return weird and unexplainable results. This is not reasonably automatically recoverable by looqs. I strongly recommend creating a clean, new database. All previous versions are affected. To do that, go to "Settings" -> checking "Remove old database on save" -> "Save settings and restart". Alternatively, specify a new path to keep the old database.
CHANGES:
- GUI: Add line numbers and context lines to plaintext previews
- GUI: Fix case where previews for old queries would have still been visible if new query would not create previews
- GUI: Add CTRL + F, CTRL+W, CTRL+Tab, CTRL+Shift+Tab shortcuts (see user manual)
- GUI: Add checkbox in "Settings" tab allowing to delete database.
- General: Fix wrong regexes that caused query errors with chars like -
- General: Drop trigger sending incomplete sqlite fts5 deletion command, causing undefined index behaviour
## 2022-07-30 - v0.5.1
CHANGES:
- gui: Fix regression in implicit paths queries introduced in previous version
## 2022-07-29 - v0.5 ## 2022-07-29 - v0.5
This release features multiple fixes and enhancements. This release features multiple fixes and enhancements.

查看文件

@ -1,12 +1,7 @@
# looqs - Hacking # looqs - Hacking
## Introduction ## Introduction
Without elaborating here, I hacked looqs because I was not satisfied with the state of desktop search on Linux. If you are interested on how to contribute, please see the file [CONTRIBUTING.md](CONTRIBUTING.md) which contains the instructions on how to submit patches etc.
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,
at least for me.
If you are interested in how to contribute, please see the file [CONTRIBUTING.md](CONTRIBUTING.md) which contains the instructions on how to submit patches etc.
## Security ## 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. 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.
@ -16,7 +11,8 @@ Qt code is considered trusted in this model. While one may critize this, it was
Set the enviornment variable `LOOQS_DISABLE_SANDBOX=1` to disable sandboxing. It's intended for troublehshooting. Set the enviornment variable `LOOQS_DISABLE_SANDBOX=1` to disable sandboxing. It's intended for troublehshooting.
## Database ## Database
The heart is sqlite, with the FTS5 extensions behind the full-text search. While FTS may not be sqlite's strong suit, I definitly did not want to run one of those oftenly recommended heavy (Java based) solutions. I explored other options like Postgresql, I've discard them due to some limitations back then. The heart is sqlite, with the FTS5 extensions behind the full-text search. While FTS may not be sqlite's strong suit, I definitely did not want to run one of those oftenly recommended heavy (Java based) solutions. I explored other options like Postgresql, I've discard them due to some limitations back then. It's also natural to use sqlite as it's
used for metadata in general.
Down the road, alternatives will be explored of course if sqlite should not suffice anymore. Down the road, alternatives will be explored of course if sqlite should not suffice anymore.
@ -27,7 +23,7 @@ looqs simply strips the tags and that seems to work fine so far. Naturally, this
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. 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 ## Name
looqs looks for files. You as the user can also look inside them. The 'k' in "looks" was replaced by a 'q'. Originally, I wanted my projects to have "qs" (for quitesimple) in their name. While abandoned now, this got us to looqs. looqs looks for files. You as the user can also look inside them. The 'k' in "looks" was replaced by a 'q'. Originally, I wanted my projects to have "qs" (for quitesimple) in their name. While that quirk is abandoned now, this got us to looqs.

查看文件

@ -1,4 +1,4 @@
Copyright (c) 2018-2022: Albert Schwarzkopf <looqs at quitesimple period org> Copyright (c) 2018-2023: Albert Schwarzkopf <looqs at quitesimple period org>
looqs is made available under the following license: looqs is made available under the following license:

查看文件

@ -1,10 +1,9 @@
# looqs - Full-text search with previews for your files # 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 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.
search terms have been found, as shown in the screenshots below.
## Screenshots ## Screenshots
### Preview ### Preview
looqs allow you to look inside files. It marks what you have searched for. looqs allows you to look inside files. It highlights what you have searched for.
![Screenshot looqs](https://garage.quitesimple.org/assets/looqs/orwell.png) ![Screenshot looqs](https://garage.quitesimple.org/assets/looqs/orwell.png)
![Screenshot looqs search fstream](https://garage.quitesimple.org/assets/looqs/fstream_write.png) ![Screenshot looqs search fstream](https://garage.quitesimple.org/assets/looqs/fstream_write.png)
@ -29,9 +28,12 @@ There is no need to write the long form of filters. There are also booleans avai
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. 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.
## Current status ## Current status
Latest version: 2022-07-29, v0.5 Latest version: 2023-05-07, v0.9
Please see [Changelog](CHANGELOG.md) for a human readable list of changes. Please keep in mind: looqs is still at an early stage and may exhibit some weirdness and contain bugs.
Please see [Changelog](CHANGELOG.md) for a human readable list of changes. For download instructions, see
further down this document.
## Goals and principles ## Goals and principles
@ -74,7 +76,7 @@ To build on Ubuntu and Debian, clone the repo and then run:
``` ```
git submodule init git submodule init
git submodule update git submodule update
sudo apt install build-essential qtbase5-dev libpoppler-qt5-dev libuchardet-dev libquazip5-dev sudo apt install build-essential qtbase5-dev libqt5sql5-sqlite libpoppler-qt5-dev libuchardet-dev libquazip5-dev
qmake qmake
make make
``` ```
@ -95,7 +97,9 @@ The GUI is located in `gui/looqs-gui`, the binary for the CLI is in `cli/looqs`
## Packages ## Packages
At this point, looqs is not in any official distro package repo, but I maintain some packages. At this point, looqs is not in any official distro package repo, but I maintain some packages.
### Ubuntu 22.04
### Ubuntu 23.04, 22.10, 22.04
Latest release can be installed using apt from the repo. Latest release can be installed using apt from the repo.
``` ```
# First, obtain key, assume it's trusted. # First, obtain key, assume it's trusted.
@ -106,6 +110,8 @@ echo "deb [arch=amd64 signed-by=/usr/share/keyrings/repo.quitesimple.org.gpg] ht
sudo apt-get update sudo apt-get update
sudo apt-get install looqs sudo apt-get install looqs
``` ```
### Gentoo (EXPERIMENTAL)
Available in this overlay: https://github.com/quitesimpleorg/quitesimple-overlay
### Prebuilt tarball (distro-agnostic) (EXPERIMENTAL) ### Prebuilt tarball (distro-agnostic) (EXPERIMENTAL)
looqs is also distributed as a tarball containing prebuilt binaries and its library dependencies. The tarball is looqs is also distributed as a tarball containing prebuilt binaries and its library dependencies. The tarball is
@ -132,7 +138,7 @@ An AppImage may accompany the tarball in the future.
### Other distros ### 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! I appreciate help for others distros. If you create a package, let me know!
### Signature verification ### Signature verification

查看文件

@ -9,6 +9,8 @@ looqs is still at an early stage and may exhibit some weirdness and contain bugs
## Current Limitations and things to know ## Current Limitations and things to know
You should be aware of the following: You should be aware of the following:
- Lags are to be expected for networked mount points such as SMB and NFS etc.
- 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 know about them too. - 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 know about 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. - 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.
@ -26,6 +28,7 @@ Database default path: `$HOME/.local/share/quitesimple.org/looqs/looqs.sqlite`.
### First run ### First run
You will be presented with an empty list. Go to the **"Index"** tab, add some directories and click **"Start indexing"**. You will be presented with an empty list. Go to the **"Index"** tab, add some directories and click **"Start indexing"**.
### Indexing
For large directories the progress bar is essentially just decoration. As long as you see the counters 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. increase, everything is fine even if it seems the progress bar is stuck.
@ -33,19 +36,34 @@ The indexing can be stopped. If you run it again you do not start from scratch,
which files have been modified since they have been added to the index. Thus, files will which files have been modified since they have been added to the index. Thus, files will
only be reprocessed when necessary. Note that cancellation itself may take a moment as files finish processing. only be reprocessed when necessary. Note that cancellation itself may take a moment as files finish processing.
The counters increase in batches, therefore it's normal that it seems no progress is being made, particularly when processing lots of large documents. This aspect will be improved in a future version.
### Search ### Search
The text field at the top is where you type your query. It can be selected quickly using **CTRL + L**. Filters are available, see this document at the end. By default, both the full path and the content are searched. Path names take precedence, i. e. they will appear the top of the list. The text field at the top is where you type your query. It can be selected quickly using **CTRL + L**. Filters are available, see this document at the end. By default, both the full path and the content are searched. Path names take precedence, i. e. they will appear the top of the list.
**CTRL + F**: This is helpful shortcut if you want to perform several searches. Consider the following
query: "p:(docs) c:(invoice credit card)". Press CTRL+F to highlight 'invoice credit card'. This way
you can quickly perform content searches in paths containing 'docs'.
**CTRL + W**: Removes the last filter. If we take above's example "p:(docs) c:(invoice credit card)" again, then CTRL + W kills "c:(invoice credit card)".
The arrow keys (up and down) can be used to go back and forward in the search history.
### Configuring PDF viewer ### 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'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 in the "Settings" tab yourself if the It tries to auto detect some common viewers. You must set the value in the "Settings" tab yourself if the
default does not work for you. In the command line options, "%f" represents the filepath, "%p" the page number. default does not work for you. In the command line options, "%f" represents the filepath, "%p" the page number.
### Preview tab ### Previews tab
The preview tab shows previews. It marks your search keywords too. Click on a preview to open the file. The 'previews' 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. A right click on a preview allows you to copy the file path, or to open the containing folder.
When the combobox is set to "All previews", the previews are ordered by relevance from all documents/pages.
By default, a vertical scrolling is active. In the settings, it can be changed to horizontal scroll, which may be
preferred by users of (larger) wide screen monitors.
### Syncing index ### 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. 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.
@ -147,6 +165,8 @@ A number of search filters are available.
| path.begins:(term) | pb:(term) | Filters path beginning with the specified term | | path.begins:(term) | pb:(term) | Filters path beginning with the specified term |
| contains:(terms) | c:(terms) | Full-text search, also understands quotes | | contains:(terms) | c:(terms) | Full-text search, also understands quotes |
| limit:(integer) | - | Limits the number of results. The default is 1000. Say "limit:0" to see all results | | limit:(integer) | - | Limits the number of results. The default is 1000. Say "limit:0" to see all results |
| tag:(tagname) | t:(tagname) | Filter for files that have been tagged with the corresponding tag |
Filters can be combined. The booleans AND and OR are supported. Negations can be applied too, except for c:(). Negations are specified with "!". Filters can be combined. The booleans AND and OR are supported. Negations can be applied too, except for c:(). Negations are specified with "!".
The AND boolean is implicit and thus entering it strictly optional. The AND boolean is implicit and thus entering it strictly optional.
@ -159,11 +179,5 @@ Examples:
|p:(notes) (pe:(odt) OR pe:(docx)) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|Finds files such as notes.docx, notes.odt but also any .docs and .odt when the path contains the string 'notes'| |p:(notes) (pe:(odt) OR pe:(docx)) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|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.| |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".| |c:("I think, therefore")|Performs a FTS search for the phrase "I think, therefore".|
|c:("invoice") Downloads|This query is equivalent to c:("invoice") p:("Downloads")| |c:("invoice") Downloads|Equivalent to c:("invoice") p:("Downloads")|
|p:(Downloads) invoice|Equivalent to c:("invoice") p:("Downloads")|

查看文件

@ -15,6 +15,7 @@ DEFINES += QT_DEPRECATED_WARNINGS
# You can also select to disable deprecated APIs only up to a certain version of Qt. # 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 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \ SOURCES += \
commandtag.cpp \
main.cpp \ main.cpp \
commandadd.cpp \ commandadd.cpp \
commanddelete.cpp \ commanddelete.cpp \
@ -27,6 +28,7 @@ HEADERS += \
command.h \ command.h \
commandadd.h \ commandadd.h \
commanddelete.h \ commanddelete.h \
commandtag.h \
commandupdate.h \ commandupdate.h \
commandsearch.h \ commandsearch.h \
commandlist.h commandlist.h
@ -44,6 +46,8 @@ packagesExist(quazip1-qt5) {
} }
INCLUDEPATH += $$PWD/../shared INCLUDEPATH += $$PWD/../shared
INCLUDEPATH += /usr/include/poppler/qt5/
DEPENDPATH += $$PWD/../shared DEPENDPATH += $$PWD/../shared
win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../shared/release/libshared.a win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../shared/release/libshared.a

查看文件

@ -2,7 +2,6 @@
#include <QThread> #include <QThread>
#include <QDebug> #include <QDebug>
#include "command.h" #include "command.h"
#include "looqsgeneralexception.h"
void Command::execute() void Command::execute()
{ {

查看文件

@ -23,7 +23,7 @@ void CommandAdd::indexerFinished()
if(failedPathsCount > 0) if(failedPathsCount > 0)
{ {
Logger::info() << "Failed paths: " << Qt::endl; Logger::info() << "Failed paths: " << Qt::endl;
for(QString paths : result.failedPaths()) for(const QString &paths : result.failedPaths())
{ {
Logger::info() << paths << Qt::endl; Logger::info() << paths << Qt::endl;
} }
@ -41,23 +41,36 @@ int CommandAdd::handle(QStringList arguments)
{ {
QCommandLineParser parser; QCommandLineParser parser;
parser.addOptions({{{"c", "continue"}, parser.addOptions({{{"c", "continue"},
"Continue adding files, don't exit on first error. If this option is not given, looqs will " "Continue adding files, don't exit on first error. Exit code will be 0. If this option is not "
"exit asap, but it's possible that a few files will still be processed. " "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. "}, "Set -t 1 to avoid this behavior, but processing will be slower. "},
{{"n", "no-content"}, "Only add paths to database. Do not index content"},
{{"v", "verbose"}, "Print paths of files being processed"},
{{"f", "fill-content"}, "Index content for files previously indexed with -n"},
{{"t", "threads"}, "Number of threads to use.", "threads"}}); {{"t", "threads"}, "Number of threads to use.", "threads"}});
parser.addHelpOption(); parser.addHelpOption();
parser.addPositionalArgument("add", "Add paths to the index", parser.addPositionalArgument("add", "Add paths to the index",
"add [paths...]. If no path is given, read from stdin, one path per line."); "add [paths...]. If no path is given, read from stdin, one path per line.");
parser.process(arguments); parser.process(arguments);
this->keepGoing = parser.isSet("continue"); this->keepGoing = parser.isSet("continue");
bool pathsOnly = parser.isSet("no-content");
bool fillContent = parser.isSet("fill-content");
bool verbose = parser.isSet("verbose");
if(parser.isSet("threads")) if(parser.isSet("threads"))
{ {
QString threadsCount = parser.value("threads"); QString threadsCount = parser.value("threads");
QThreadPool::globalInstance()->setMaxThreadCount(threadsCount.toInt()); QThreadPool::globalInstance()->setMaxThreadCount(threadsCount.toInt());
} }
if(pathsOnly && fillContent)
{
Logger::error() << "Invalid options: -n and -f cannot both be set";
return EXIT_FAILURE;
}
QStringList files = parser.positionalArguments(); QStringList files = parser.positionalArguments();
if(files.length() == 0) if(files.length() == 0)
@ -71,15 +84,47 @@ int CommandAdd::handle(QStringList arguments)
} }
} }
FileSaverOptions fileSaverOptions;
fileSaverOptions.keepGoing = keepGoing;
fileSaverOptions.fillExistingContentless = fillContent;
fileSaverOptions.metadataOnly = pathsOnly;
fileSaverOptions.verbose = verbose;
indexer = new Indexer(*this->dbService); indexer = new Indexer(*this->dbService);
indexer->setFileSaverOptions(fileSaverOptions);
indexer->setTargetPaths(files.toVector()); indexer->setTargetPaths(files.toVector());
indexer->setKeepGoing(keepGoing);
if(verbose)
{
indexer->setProgressReportThreshold(1);
}
connect(indexer, &Indexer::pathsCountChanged, this, connect(indexer, &Indexer::pathsCountChanged, this,
[](int pathsCount) { Logger::info() << "Found paths: " << pathsCount << Qt::endl; }); [](int pathsCount) { Logger::info() << "Found paths: " << pathsCount << Qt::endl; });
connect(indexer, &Indexer::indexProgress, this, connect(indexer, &Indexer::indexProgress, this,
[](int pathsCount, unsigned int added, unsigned int skipped, unsigned int failed, unsigned int totalCount) [verbose, this](int pathsCount, unsigned int /*added*/, unsigned int /*skipped*/, unsigned int /*failed*/,
{ Logger::info() << "Processed files: " << pathsCount << Qt::endl; }); unsigned int /*totalCount*/)
{
Logger::info() << "Processed files: " << pathsCount << Qt::endl;
if(verbose)
{
IndexResult indexResult = indexer->getResult();
int newlyAdded = indexResult.results.count() - currentResult.results.count();
if(newlyAdded > 0)
{
int newOffset = indexResult.results.count() - newlyAdded;
for(int i = newOffset; i < indexResult.results.count(); i++)
{
auto result = indexResult.results.at(i);
Logger::info() << SaveFileResultToString(result.second) << result.first << Qt::endl;
}
}
this->currentResult = indexResult;
}
}
);
connect(indexer, &Indexer::finished, this, &CommandAdd::indexerFinished); connect(indexer, &Indexer::finished, this, &CommandAdd::indexerFinished);
this->autoFinish = false; this->autoFinish = false;

查看文件

@ -13,6 +13,8 @@ class CommandAdd : public Command
bool keepGoing = true; bool keepGoing = true;
protected: protected:
IndexResult currentResult;
public: public:
using Command::Command; using Command::Command;

查看文件

@ -1,6 +1,5 @@
#include <QCommandLineParser> #include <QCommandLineParser>
#include "commandlist.h" #include "commandlist.h"
#include "databasefactory.h"
#include "logger.h" #include "logger.h"
int CommandList::handle(QStringList arguments) int CommandList::handle(QStringList arguments)

查看文件

@ -1,6 +1,5 @@
#include <QCommandLineParser> #include <QCommandLineParser>
#include "commandsearch.h" #include "commandsearch.h"
#include "databasefactory.h"
#include "logger.h" #include "logger.h"
int CommandSearch::handle(QStringList arguments) int CommandSearch::handle(QStringList arguments)
@ -33,11 +32,18 @@ int CommandSearch::handle(QStringList arguments)
try try
{ {
QHash<QString, bool> seenMap;
auto results = dbService->search(query); auto results = dbService->search(query);
for(SearchResult &result : results) for(const SearchResult &result : results)
{ {
Logger::info() << result.fileData.absPath << Qt::endl; const QString &absPath = result.fileData.absPath;
if(!seenMap.contains(absPath))
{
seenMap[absPath] = true;
Logger::info() << absPath << Qt::endl;
}
} }
} }
catch(LooqsGeneralException &e) catch(LooqsGeneralException &e)

153
cli/commandtag.cpp 普通文件
查看文件

@ -0,0 +1,153 @@
#include <QCommandLineParser>
#include "commandtag.h"
#include "logger.h"
#include "tagmanager.h"
bool CommandTag::ensureAbsolutePaths(const QVector<QString> &paths, QVector<QString> &absolutePaths)
{
for(const QString &path : paths)
{
QFileInfo info{path};
if(!info.exists())
{
Logger::error() << "Can't add tag for file " + info.absoluteFilePath() + " because it does not exist"
<< Qt::endl;
return false;
}
QString absolutePath = info.absoluteFilePath();
if(!this->dbService->fileExistsInDatabase(absolutePath))
{
Logger::error() << "Only files that have been indexed can be tagged. File not in index: " + absolutePath
<< Qt::endl;
return false;
}
absolutePaths.append(absolutePath);
}
return true;
}
int CommandTag::handle(QStringList arguments)
{
QCommandLineParser parser;
parser.addPositionalArgument("add", "Adds a tag to a file",
"add [tag] [paths...]. Adds the tag to the specified paths");
parser.addPositionalArgument("remove", "Removes a path associated to a tag", "remove [tag] [path]");
parser.addPositionalArgument("delete", "Deletes a tag", "delete [tag]");
parser.addPositionalArgument("list", "Lists paths associated with a tag, or all tags", "list [tag]");
parser.addPositionalArgument("show", "Lists tags associated with a path", "show [path]");
parser.addHelpOption();
parser.parse(arguments);
QStringList args = parser.positionalArguments();
if(args.length() == 0)
{
parser.showHelp(EXIT_FAILURE);
return EXIT_FAILURE;
}
TagManager tagManager{*this->dbService};
QString cmd = args[0];
if(cmd == "add")
{
if(args.length() < 3)
{
Logger::error() << "Not enough arguments provided. 'add' requires a tag followed by at least one path"
<< Qt::endl;
return EXIT_FAILURE;
}
QString tag = args[1];
QVector<QString> paths = args.mid(2).toVector();
QVector<QString> absolutePaths;
if(!ensureAbsolutePaths(paths, absolutePaths))
{
return EXIT_FAILURE;
}
bool result = tagManager.addPathsToTag(tag, absolutePaths);
if(!result)
{
Logger::error() << "Failed to assign tags" << Qt::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if(cmd == "list")
{
QString tag;
if(args.length() >= 2)
{
tag = args[1];
}
QVector<QString> entries;
if(tag.isEmpty())
{
entries = tagManager.getTags();
}
else
{
entries = tagManager.getPaths(tag);
}
for(const QString &entry : entries)
{
Logger::info() << entry << Qt::endl;
}
}
if(cmd == "remove")
{
if(args.length() < 3)
{
Logger::error() << "Not enough arguments provided. 'remove' requires a tag followed by at least one path"
<< Qt::endl;
return EXIT_FAILURE;
}
QString tag = args[1];
QVector<QString> paths = args.mid(2).toVector();
QVector<QString> absolutePaths;
if(!ensureAbsolutePaths(paths, absolutePaths))
{
return EXIT_FAILURE;
}
if(!tagManager.removePathsForTag(tag, absolutePaths))
{
Logger::error() << "Failed to remove path assignments" << Qt::endl;
return EXIT_FAILURE;
}
}
if(cmd == "delete")
{
if(args.length() != 2)
{
Logger::error() << "The 'delete' command requires the tag to delete" << Qt::endl;
return EXIT_FAILURE;
}
if(!tagManager.deleteTag(args[1]))
{
Logger::error() << "Failed to delete tag" << Qt::endl;
return EXIT_FAILURE;
}
}
if(cmd == "show")
{
if(args.length() != 2)
{
Logger::error() << "The 'show' command requires a path to show the assigned tags" << Qt::endl;
return EXIT_FAILURE;
}
QString path = args[1];
QVector<QString> absolutePaths;
if(!ensureAbsolutePaths({path}, absolutePaths))
{
return EXIT_FAILURE;
}
QVector<QString> tags = tagManager.getTags(absolutePaths.at(0));
for(const QString &entry : tags)
{
Logger::info() << entry << Qt::endl;
}
}
return EXIT_SUCCESS;
}

16
cli/commandtag.h 普通文件
查看文件

@ -0,0 +1,16 @@
#ifndef COMMANDTAG_H
#define COMMANDTAG_H
#include "command.h"
class CommandTag : public Command
{
protected:
bool ensureAbsolutePaths(const QVector<QString> &paths, QVector<QString> &absolutePaths);
public:
using Command::Command;
int handle(QStringList arguments) override;
};
#endif // COMMANDTAG_H

查看文件

@ -38,10 +38,13 @@ int CommandUpdate::handle(QStringList arguments)
QThreadPool::globalInstance()->setMaxThreadCount(threadsCount.toInt()); QThreadPool::globalInstance()->setMaxThreadCount(threadsCount.toInt());
} }
bool hasErrors = false;
IndexSyncer *syncer = new IndexSyncer(*this->dbService); IndexSyncer *syncer = new IndexSyncer(*this->dbService);
syncer->setKeepGoing(keepGoing);
syncer->setVerbose(verbose); FileSaverOptions fileOptions;
fileOptions.keepGoing = keepGoing;
fileOptions.verbose = verbose;
syncer->setFileSaverOptions(fileOptions);
syncer->setPattern(pattern); syncer->setPattern(pattern);
syncer->setDryRun(dryRun); syncer->setDryRun(dryRun);
syncer->setRemoveDeletedFromIndex(deleteMissing); syncer->setRemoveDeletedFromIndex(deleteMissing);
@ -60,7 +63,7 @@ int CommandUpdate::handle(QStringList arguments)
/* TODO: updated not printed, handled be verbose in FileSaver, but this can be improved */ /* TODO: updated not printed, handled be verbose in FileSaver, but this can be improved */
} }
connect(syncer, &IndexSyncer::finished, this, connect(syncer, &IndexSyncer::finished, this,
[&](unsigned int totalUpdated, unsigned int totalRemoved, unsigned int totalErrors) [this, dryRun, keepGoing](unsigned int totalUpdated, unsigned int totalRemoved, unsigned int totalErrors)
{ {
Logger::info() << "Syncing finished" << Qt::endl; Logger::info() << "Syncing finished" << Qt::endl;
@ -72,7 +75,7 @@ int CommandUpdate::handle(QStringList arguments)
} }
int retval = 0; int retval = 0;
if(hasErrors && !keepGoing) if(this->hasErrors && !keepGoing)
{ {
retval = 1; retval = 1;
} }
@ -82,7 +85,7 @@ int CommandUpdate::handle(QStringList arguments)
[&](QString error) [&](QString error)
{ {
Logger::error() << error << Qt::endl; Logger::error() << error << Qt::endl;
hasErrors = true; this->hasErrors = true;
}); });
this->autoFinish = false; this->autoFinish = false;

查看文件

@ -4,6 +4,9 @@
#include "filesaver.h" #include "filesaver.h"
class CommandUpdate : public Command class CommandUpdate : public Command
{ {
protected:
bool hasErrors = false;
public: public:
using Command::Command; using Command::Command;
int handle(QStringList arguments) override; int handle(QStringList arguments) override;

查看文件

@ -21,6 +21,7 @@
#include "commandupdate.h" #include "commandupdate.h"
#include "commandsearch.h" #include "commandsearch.h"
#include "commandlist.h" #include "commandlist.h"
#include "commandtag.h"
#include "databasefactory.h" #include "databasefactory.h"
#include "logger.h" #include "logger.h"
#include "sandboxedprocessor.h" #include "sandboxedprocessor.h"
@ -31,7 +32,7 @@
void printUsage(QString argv0) void printUsage(QString argv0)
{ {
qInfo() << "Usage:" << argv0 << "command"; qInfo() << "Usage:" << argv0 << "command";
qInfo() << "Valid commands: add, update, delete, search, list. Each command has a --help option."; qInfo() << "Valid commands: add, update, search, delete, tag, list. Each command has a --help option.";
} }
Command *commandFromName(QString name, SqliteDbService &dbService) Command *commandFromName(QString name, SqliteDbService &dbService)
@ -56,6 +57,10 @@ Command *commandFromName(QString name, SqliteDbService &dbService)
{ {
return new CommandList(dbService); return new CommandList(dbService);
} }
if(name == "tag")
{
return new CommandTag(dbService);
}
return nullptr; return nullptr;
} }

查看文件

@ -34,6 +34,7 @@ SOURCES += \
main.cpp \ main.cpp \
mainwindow.cpp \ mainwindow.cpp \
clicklabel.cpp \ clicklabel.cpp \
previewcoordinator.cpp \
previewgenerator.cpp \ previewgenerator.cpp \
previewgeneratormapfunctor.cpp \ previewgeneratormapfunctor.cpp \
previewgeneratorodt.cpp \ previewgeneratorodt.cpp \
@ -54,6 +55,7 @@ HEADERS += \
ipcserver.h \ ipcserver.h \
mainwindow.h \ mainwindow.h \
clicklabel.h \ clicklabel.h \
previewcoordinator.h \
previewgenerator.h \ previewgenerator.h \
previewgeneratormapfunctor.h \ previewgeneratormapfunctor.h \
previewgeneratorodt.h \ previewgeneratorodt.h \

查看文件

@ -1,16 +1,50 @@
#include <QtConcurrent> #include <QtConcurrent>
#include "ipcpreviewworker.h" #include "ipcpreviewworker.h"
#include "previewgeneratormapfunctor.h" #include "previewgeneratormapfunctor.h"
IPCPreviewWorker::IPCPreviewWorker() IPCPreviewWorker::IPCPreviewWorker(QLocalSocket *peer)
{ {
this->peer = peer;
this->connect(&previewWorkerWatcher, &QFutureWatcher<QByteArray>::resultReadyAt, this, this->connect(&previewWorkerWatcher, &QFutureWatcher<QByteArray>::resultReadyAt, this,
[this](int index) { emit previewGenerated(previewWorkerWatcher.resultAt(index)); }); [this](int index)
connect(&previewWorkerWatcher, &QFutureWatcher<QByteArray>::finished, this, [this] { emit finished(); }); {
if(this->peer != nullptr)
{
QDataStream stream{this->peer};
stream << previewWorkerWatcher.resultAt(index);
this->peer->flush();
}
});
connect(&previewWorkerWatcher, &QFutureWatcher<QByteArray>::finished, this, &IPCPreviewWorker::shutdownSocket);
connect(this->peer, &QLocalSocket::disconnected, this, &IPCPreviewWorker::shutdownSocket);
} }
void IPCPreviewWorker::start(RenderConfig config, const QVector<RenderTarget> &targets, QLocalSocket *peer) void IPCPreviewWorker::shutdownSocket()
{
if(cleaned)
{
return;
}
cleaned = true;
if(this->peer != nullptr)
{
if(this->peer->state() == QLocalSocket::ConnectedState)
{
this->peer->flush();
this->peer->waitForBytesWritten();
this->peer->disconnectFromServer();
if(this->peer->state() != QLocalSocket::UnconnectedState)
{
this->peer->waitForDisconnected();
}
}
delete this->peer;
this->peer = nullptr;
}
emit finished();
}
void IPCPreviewWorker::start(RenderConfig config, const QVector<RenderTarget> &targets)
{ {
stop();
auto mapFunctor = PreviewGeneratorMapFunctor(); auto mapFunctor = PreviewGeneratorMapFunctor();
mapFunctor.setRenderConfig(config); mapFunctor.setRenderConfig(config);

查看文件

@ -11,13 +11,21 @@ class IPCPreviewWorker : public QObject
Q_OBJECT Q_OBJECT
private: private:
QFutureWatcher<QByteArray> previewWorkerWatcher; QFutureWatcher<QByteArray> previewWorkerWatcher;
QLocalSocket *peer;
bool cleaned = false;
public: public:
IPCPreviewWorker(); IPCPreviewWorker(QLocalSocket *peer);
void start(RenderConfig config, const QVector<RenderTarget> &targets, QLocalSocket *peer); void start(RenderConfig config, const QVector<RenderTarget> &targets);
void stop(); void stop();
~IPCPreviewWorker()
{
delete this->peer;
}
private slots:
void shutdownSocket();
signals: signals:
void previewGenerated(QByteArray);
void finished(); void finished();
}; };

查看文件

@ -18,8 +18,6 @@ IpcServer::IpcServer()
/* Only 1, we are doing work for the GUI, not a service for general availability */ /* Only 1, we are doing work for the GUI, not a service for general availability */
this->spawningServer.setMaxPendingConnections(1); this->spawningServer.setMaxPendingConnections(1);
connect(&this->spawningServer, &QLocalServer::newConnection, this, &IpcServer::spawnerNewConnection); 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) bool IpcServer::startSpawner(QString socketPath)
@ -31,8 +29,6 @@ bool IpcServer::startSpawner(QString socketPath)
void IpcServer::spawnerNewConnection() void IpcServer::spawnerNewConnection()
{ {
QLocalSocket *socket = this->spawningServer.nextPendingConnection(); QLocalSocket *socket = this->spawningServer.nextPendingConnection();
connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
this->currentSocket = socket;
if(socket != nullptr) if(socket != nullptr)
{ {
if(!socket->waitForReadyRead()) if(!socket->waitForReadyRead())
@ -53,21 +49,22 @@ void IpcServer::spawnerNewConnection()
stream.startTransaction(); stream.startTransaction();
stream >> renderConfig >> targets; stream >> renderConfig >> targets;
} while(!stream.commitTransaction() && socket->state() == QLocalSocket::ConnectedState); } while(!stream.commitTransaction() && socket->state() == QLocalSocket::ConnectedState);
if(socket->state() == QLocalSocket::ConnectedState)
stream << targets.count(); {
socket->flush(); stream << targets.count();
previewWorker.start(renderConfig, targets, socket); socket->flush();
IPCPreviewWorker *previewWorker = new IPCPreviewWorker(socket);
connect(previewWorker, &IPCPreviewWorker::finished, this, [previewWorker] { delete previewWorker; });
previewWorker->start(renderConfig, targets);
}
else
{
delete socket;
}
} }
if(command == StopGeneratePreviews) if(command == StopGeneratePreviews)
{ {
previewWorker.stop(); /* TODO: implement */
} }
} }
} }
void IpcServer::handlePreviewGenerated(QByteArray ba)
{
QDataStream stream{this->currentSocket};
stream << ba;
this->currentSocket->flush();
}

查看文件

@ -10,13 +10,10 @@ class IpcServer : public QObject
{ {
Q_OBJECT Q_OBJECT
private: private:
IPCPreviewWorker previewWorker;
QLocalServer spawningServer; QLocalServer spawningServer;
QLocalSocket *currentSocket = nullptr;
SaveFileResult addFile(QString file); SaveFileResult addFile(QString file);
private slots: private slots:
void spawnerNewConnection(); void spawnerNewConnection();
void handlePreviewGenerated(QByteArray ba);
public: public:
IpcServer(); IpcServer();

查看文件

@ -28,7 +28,7 @@ void enableIpcSandbox()
policy->namespace_options = EXILE_UNSHARE_USER | EXILE_UNSHARE_MOUNT | EXILE_UNSHARE_NETWORK; policy->namespace_options = EXILE_UNSHARE_USER | EXILE_UNSHARE_MOUNT | EXILE_UNSHARE_NETWORK;
policy->no_new_privs = 1; policy->no_new_privs = 1;
policy->drop_caps = 1; policy->drop_caps = 1;
policy->vow_promises = exile_vows_from_str("thread cpath rpath unix stdio proc error"); policy->vow_promises = exile_vows_from_str("thread cpath rpath wpath unix stdio proc error");
policy->mount_path_policies_to_chroot = 1; policy->mount_path_policies_to_chroot = 1;
QString ipcSocketPath = Common::ipcSocketPath(); QString ipcSocketPath = Common::ipcSocketPath();
@ -193,7 +193,7 @@ int main(int argc, char *argv[])
Logger::error() << error << Qt::endl; Logger::error() << error << Qt::endl;
QMessageBox::critical(nullptr, "Error during upgrade", QMessageBox::critical(nullptr, "Error during upgrade",
error); error);
qApp->quit(); exit(EXIT_FAILURE);
} }
); );

查看文件

@ -15,14 +15,16 @@
#include <QFileDialog> #include <QFileDialog>
#include <QScreen> #include <QScreen>
#include <QProgressDialog> #include <QProgressDialog>
#include <QDesktopWidget>
#include <QWidgetAction>
#include <QInputDialog>
#include "mainwindow.h" #include "mainwindow.h"
#include "ui_mainwindow.h" #include "ui_mainwindow.h"
#include "clicklabel.h" #include "clicklabel.h"
#include "../shared/sqlitesearch.h" #include "../shared/sqlitesearch.h"
#include "../shared/looqsgeneralexception.h" #include "../shared/looqsgeneralexception.h"
#include "../shared/common.h" #include "../shared/common.h"
#include "ipcpreviewclient.h"
#include "previewgenerator.h"
#include "aboutdialog.h" #include "aboutdialog.h"
MainWindow::MainWindow(QWidget *parent, QString socketPath) MainWindow::MainWindow(QWidget *parent, QString socketPath)
@ -31,8 +33,7 @@ MainWindow::MainWindow(QWidget *parent, QString socketPath)
this->progressDialog.cancel(); // because constructing it shows it, quite weird this->progressDialog.cancel(); // because constructing it shows it, quite weird
ui->setupUi(this); ui->setupUi(this);
setWindowTitle(QCoreApplication::applicationName()); setWindowTitle(QCoreApplication::applicationName());
this->ipcPreviewClient.moveToThread(&this->ipcClientThread);
this->ipcPreviewClient.setSocketPath(socketPath);
QSettings settings; QSettings settings;
this->dbFactory = new DatabaseFactory(Common::databasePath()); this->dbFactory = new DatabaseFactory(Common::databasePath());
@ -44,6 +45,9 @@ MainWindow::MainWindow(QWidget *parent, QString socketPath)
indexer = new Indexer(*(this->dbService)); indexer = new Indexer(*(this->dbService));
indexer->setParent(this); indexer->setParent(this);
tagManager = new TagManager(*(this->dbService));
connectSignals(); connectSignals();
ui->treeResultsList->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); ui->treeResultsList->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
ui->tabWidget->setCurrentIndex(0); ui->tabWidget->setCurrentIndex(0);
@ -60,6 +64,10 @@ MainWindow::MainWindow(QWidget *parent, QString socketPath)
QString ignorePatterns = settings.value("ignorePatterns").toString(); QString ignorePatterns = settings.value("ignorePatterns").toString();
ui->txtIgnorePatterns->setText(ignorePatterns); ui->txtIgnorePatterns->setText(ignorePatterns);
QStringList searchHistoryList = settings.value(SETTINGS_KEY_SEARCHHISTORY).toStringList();
this->searchHistory = searchHistoryList.toVector();
this->currentSearchHistoryIndex = this->searchHistory.size();
ui->spinPreviewPage->setValue(1); ui->spinPreviewPage->setValue(1);
ui->spinPreviewPage->setMinimum(1); ui->spinPreviewPage->setMinimum(1);
@ -70,7 +78,10 @@ MainWindow::MainWindow(QWidget *parent, QString socketPath)
policy.setRetainSizeWhenHidden(true); policy.setRetainSizeWhenHidden(true);
ui->btnOpenFailed->setSizePolicy(policy); ui->btnOpenFailed->setSizePolicy(policy);
this->ipcClientThread.start(); ui->txtSearch->installEventFilter(this);
ui->scrollArea->viewport()->installEventFilter(this);
this->previewCoordinator.setSocketPath(socketPath);
} }
void MainWindow::addPathToIndex() void MainWindow::addPathToIndex()
@ -142,7 +153,7 @@ void MainWindow::connectSignals()
connect(this->indexer, &Indexer::finished, this, &MainWindow::finishIndexing); connect(this->indexer, &Indexer::finished, this, &MainWindow::finishIndexing);
connect(ui->lstPaths->selectionModel(), &QItemSelectionModel::selectionChanged, this, connect(ui->lstPaths->selectionModel(), &QItemSelectionModel::selectionChanged, this,
[&](const QItemSelection &selected, const QItemSelection &deselected) [&](const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/)
{ ui->btnDeletePath->setEnabled(this->ui->lstPaths->selectedItems().count() > 0); }); { ui->btnDeletePath->setEnabled(this->ui->lstPaths->selectedItems().count() > 0); });
connect(ui->btnDeletePath, &QPushButton::clicked, this, [&] { qDeleteAll(ui->lstPaths->selectedItems()); }); connect(ui->btnDeletePath, &QPushButton::clicked, this, [&] { qDeleteAll(ui->lstPaths->selectedItems()); });
@ -162,62 +173,71 @@ void MainWindow::connectSignals()
} }
}); });
connect(ui->menuAboutAction, &QAction::triggered, this, connect(ui->menuAboutAction, &QAction::triggered, this,
[this](bool checked) [this](bool /*checked*/)
{ {
AboutDialog aboutDialog(this); AboutDialog aboutDialog(this);
aboutDialog.exec(); aboutDialog.exec();
}); });
connect(ui->menuAboutQtAction, &QAction::triggered, this, connect(ui->menuAboutQtAction, &QAction::triggered, this,
[this](bool checked) { QMessageBox::aboutQt(this, "About Qt"); }); [this](bool /*checked*/) { QMessageBox::aboutQt(this, "About Qt"); });
connect(ui->menuSyncIndexAction, &QAction::triggered, this, &MainWindow::startIndexSync); connect(ui->menuSyncIndexAction, &QAction::triggered, this, &MainWindow::startIndexSync);
connect(ui->menuOpenUserManualAction, &QAction::triggered, this, connect(ui->menuOpenUserManualAction, &QAction::triggered, this,
[this]() { QDesktopServices::openUrl(Common::userManualUrl()); }); []() { QDesktopServices::openUrl(Common::userManualUrl()); });
connect(indexSyncer, &IndexSyncer::finished, this, connect(
[&](unsigned int totalUpdated, unsigned int totalDeleted, unsigned int totalErrored) indexSyncer, &IndexSyncer::finished, this,
{ [&](unsigned int totalUpdated, unsigned int totalDeleted, unsigned int totalErrored)
this->progressDialog.cancel(); {
this->progressDialog.cancel();
QMessageBox::information( QMessageBox::information(
this, "Syncing finished", this, "Syncing finished",
QString("Syncing finished\n\nTotal updated: %1\nTotal deleted: %2\nTotal errors: %3\n") QString("Syncing finished\n\nTotal updated: %1\nTotal deleted: %2\nTotal errors: %3\n")
.arg(QString::number(totalUpdated)) .arg(QString::number(totalUpdated), QString::number(totalDeleted), QString::number(totalErrored)));
.arg(QString::number(totalDeleted)) });
.arg(QString::number(totalErrored)));
});
connect(this, &MainWindow::beginIndexSync, indexSyncer, &IndexSyncer::sync); connect(this, &MainWindow::beginIndexSync, indexSyncer, &IndexSyncer::sync);
connect(&this->progressDialog, &QProgressDialog::canceled, indexSyncer, &IndexSyncer::cancel); connect(&this->progressDialog, &QProgressDialog::canceled, indexSyncer, &IndexSyncer::cancel);
connect(ui->btnSaveSettings, &QPushButton::clicked, this, &MainWindow::saveSettings); connect(ui->btnSaveSettings, &QPushButton::clicked, this, &MainWindow::saveSettings);
connect(ui->btnOpenFailed, &QPushButton::clicked, this, &MainWindow::exportFailedPaths); connect(ui->btnOpenFailed, &QPushButton::clicked, this, &MainWindow::exportFailedPaths);
connect( connect(
ui->comboPreviewFiles, qOverload<int>(&QComboBox::currentIndexChanged), this, [&]() { makePreviews(1); }, ui->comboPreviewFiles, qOverload<int>(&QComboBox::currentIndexChanged), this,
[&]()
{
if(this->previewTabActive())
{
makePreviews(1);
}
},
Qt::QueuedConnection); Qt::QueuedConnection);
connect(&ipcPreviewClient, &IPCPreviewClient::previewReceived, this, &MainWindow::previewReceived, connect(&previewCoordinator, &PreviewCoordinator::previewReady, this, &MainWindow::previewReceived,
Qt::QueuedConnection); Qt::QueuedConnection);
connect(&ipcPreviewClient, &IPCPreviewClient::finished, this, connect(&previewCoordinator, &PreviewCoordinator::completedGeneration, this,
[&] [&]
{ {
this->ui->previewProcessBar->setValue(this->ui->previewProcessBar->maximum()); this->ui->previewProcessBar->setValue(this->ui->previewProcessBar->maximum());
this->ui->spinPreviewPage->setEnabled(true); this->ui->spinPreviewPage->setEnabled(true);
this->ui->comboPreviewFiles->setEnabled(true); this->ui->comboPreviewFiles->setEnabled(true);
ui->txtSearch->setEnabled(true);
}); });
connect(&ipcPreviewClient, &IPCPreviewClient::error, this, connect(&previewCoordinator, &PreviewCoordinator::error, this,
[this](QString msg) [this](QString msg)
{ {
qCritical() << msg << Qt::endl; qCritical() << msg << Qt::endl;
QMessageBox::critical(this, "IPC error", msg); QMessageBox::critical(this, "IPC error", msg);
}); });
connect(ui->radioMetadataOnly, &QRadioButton::toggled, this,
connect(this, &MainWindow::startIpcPreviews, &ipcPreviewClient, &IPCPreviewClient::startGeneration, [this](bool toggled)
Qt::QueuedConnection); {
connect(this, &MainWindow::stopIpcPreviews, &ipcPreviewClient, &IPCPreviewClient::stopGeneration, if(toggled)
Qt::QueuedConnection); {
this->ui->chkFillContentForContentless->setChecked(false);
};
});
} }
void MainWindow::exportFailedPaths() void MainWindow::exportFailedPaths()
{ {
QString filename = QString filename =
QString("/tmp/looqs_indexresult_failed_%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hhmmss")); QString("/tmp/looqs_indexresult_failed_%1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hhmmss"));
QFile outFile(filename); QFile outFile(filename);
@ -250,8 +270,11 @@ void MainWindow::startIndexSync()
progressDialog.setValue(0); progressDialog.setValue(0);
progressDialog.open(); progressDialog.open();
indexSyncer->setKeepGoing(true); FileSaverOptions options;
indexSyncer->setVerbose(false); options.keepGoing = true;
options.verbose = false;
indexSyncer->setFileSaverOptions(options);
indexSyncer->setDryRun(false); indexSyncer->setDryRun(false);
indexSyncer->setRemoveDeletedFromIndex(true); indexSyncer->setRemoveDeletedFromIndex(true);
@ -270,6 +293,7 @@ void MainWindow::startIndexing()
if(this->indexer->isRunning()) if(this->indexer->isRunning())
{ {
ui->btnStartIndexing->setEnabled(false); ui->btnStartIndexing->setEnabled(false);
ui->btnStartIndexing->setText("Start indexing"); ui->btnStartIndexing->setText("Start indexing");
this->indexer->requestCancellation(); this->indexer->requestCancellation();
return; return;
@ -279,6 +303,8 @@ void MainWindow::startIndexing()
ui->resultsTab->setEnabled(false); ui->resultsTab->setEnabled(false);
ui->settingsTab->setEnabled(false); ui->settingsTab->setEnabled(false);
ui->txtPathScanAdd->setEnabled(false); ui->txtPathScanAdd->setEnabled(false);
ui->btnAddPath->setEnabled(false);
ui->btnChoosePath->setEnabled(false);
ui->txtSearch->setEnabled(false); ui->txtSearch->setEnabled(false);
ui->previewProcessBar->setValue(0); ui->previewProcessBar->setValue(0);
ui->previewProcessBar->setVisible(true); ui->previewProcessBar->setVisible(true);
@ -295,6 +321,15 @@ void MainWindow::startIndexing()
this->indexer->setTargetPaths(paths); this->indexer->setTargetPaths(paths);
QString ignorePatterns = ui->txtIgnorePatterns->text(); QString ignorePatterns = ui->txtIgnorePatterns->text();
this->indexer->setIgnorePattern(ignorePatterns.split(";")); this->indexer->setIgnorePattern(ignorePatterns.split(";"));
FileSaverOptions options;
options.fillExistingContentless =
ui->chkFillContentForContentless->isEnabled() && ui->chkFillContentForContentless->isChecked();
options.metadataOnly = ui->radioMetadataOnly->isChecked();
options.verbose = false;
options.keepGoing = true;
this->indexer->setFileSaverOptions(options);
this->indexer->beginIndexing(); this->indexer->beginIndexing();
QSettings settings; QSettings settings;
settings.setValue("indexPaths", pathSettingsValue); settings.setValue("indexPaths", pathSettingsValue);
@ -317,6 +352,8 @@ void MainWindow::finishIndexing()
ui->resultsTab->setEnabled(true); ui->resultsTab->setEnabled(true);
ui->settingsTab->setEnabled(true); ui->settingsTab->setEnabled(true);
ui->txtPathScanAdd->setEnabled(true); ui->txtPathScanAdd->setEnabled(true);
ui->btnAddPath->setEnabled(true);
ui->btnChoosePath->setEnabled(true);
ui->txtSearch->setEnabled(true); ui->txtSearch->setEnabled(true);
if(result.erroredPaths > 0) if(result.erroredPaths > 0)
{ {
@ -324,7 +361,7 @@ void MainWindow::finishIndexing()
} }
} }
void MainWindow::comboScaleChanged(int i) void MainWindow::comboScaleChanged(int /*i*/)
{ {
QSettings scaleSetting; QSettings scaleSetting;
scaleSetting.setValue("currentScale", ui->comboScale->currentText()); scaleSetting.setValue("currentScale", ui->comboScale->currentText());
@ -341,6 +378,183 @@ bool MainWindow::indexerTabActive()
return ui->tabWidget->currentIndex() == 2; return ui->tabWidget->currentIndex() == 2;
} }
void MainWindow::processShortcut(int key)
{
if(key == Qt::Key_Tab || key == Qt::Key_Backtab)
{
int tabIndex = ui->tabWidget->currentIndex();
if(key == Qt::Key_Tab)
{
++tabIndex;
}
if(key == Qt::Key_Backtab)
{
--tabIndex;
}
tabIndex = tabIndex % ui->tabWidget->count();
if(tabIndex < 0)
{
tabIndex = ui->tabWidget->count() - 1;
}
ui->tabWidget->setCurrentIndex(tabIndex);
}
if(key == Qt::Key_L)
{
ui->txtSearch->setFocus();
ui->txtSearch->selectAll();
}
if(key == Qt::Key_W)
{
ui->txtSearch->setFocus();
QString currentText = ui->txtSearch->text().trimmed();
static QRegularExpression separatorRegex("[\\s\\)]");
int index = currentText.lastIndexOf(separatorRegex);
if(index != -1)
{
bool isFilter = (index == currentText.length() - 1);
currentText.remove(index + 1, currentText.length() - index - 1);
if(isFilter)
{
index = currentText.lastIndexOf(' ', index);
if(index == -1)
{
index = 0;
}
currentText.remove(index, currentText.length());
}
if(currentText.length() > 0)
{
currentText += ' ';
}
ui->txtSearch->setText(currentText);
}
else
{
ui->txtSearch->clear();
}
}
if(key == Qt::Key_F)
{
ui->txtSearch->setFocus();
QString currentText = ui->txtSearch->text().trimmed();
int index = currentText.lastIndexOf(')');
if(index != -1)
{
bool isFilter = (index == currentText.length() - 1);
if(!isFilter)
{
ui->txtSearch->setSelection(index + 2, ui->txtSearch->text().length() - index - 1);
}
else
{
int begin = currentText.lastIndexOf('(', index - 1);
if(begin != -1)
{
ui->txtSearch->setSelection(begin + 1, index - begin - 1);
}
}
}
else
{
int spaceIndex = currentText.lastIndexOf(' ');
int colonIndex = currentText.lastIndexOf(':');
if(colonIndex > spaceIndex)
{
int target = currentText.indexOf(' ', colonIndex);
if(target == -1)
{
target = ui->txtSearch->text().size() - colonIndex;
}
ui->txtSearch->setSelection(colonIndex + 1, target - 1);
}
else
{
ui->txtSearch->setSelection(spaceIndex + 1, ui->txtSearch->text().size() - spaceIndex - 1);
}
}
}
}
bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
if(object == ui->txtSearch && !searchHistory.empty())
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == Qt::Key_Up)
{
if(this->currentSavedSearchText.isEmpty())
{
this->currentSavedSearchText = ui->txtSearch->text();
}
if(this->currentSearchHistoryIndex <= 0)
{
return true;
}
--this->currentSearchHistoryIndex;
QString text = this->searchHistory.at(this->currentSearchHistoryIndex);
ui->txtSearch->setText(text);
return true;
}
else if(keyEvent->key() == Qt::Key_Down)
{
if(this->currentSearchHistoryIndex == searchHistory.size() - 1)
{
if(!this->currentSavedSearchText.isEmpty())
{
ui->txtSearch->setText(this->currentSavedSearchText);
this->currentSavedSearchText.clear();
++this->currentSearchHistoryIndex;
}
return true;
}
if(this->currentSearchHistoryIndex < searchHistory.size() - 1)
{
++this->currentSearchHistoryIndex;
QString text = this->searchHistory.at(this->currentSearchHistoryIndex);
ui->txtSearch->setText(text);
}
return true;
}
else
{
this->currentSavedSearchText.clear();
/* Off by one on purpose so Key_Up decrements it again and lands at
* the last entry */
this->currentSearchHistoryIndex = this->searchHistory.size();
}
}
}
if(object == ui->scrollArea->viewport())
{
if(event->type() == QEvent::Wheel)
{
QWheelEvent *wheelEvent = static_cast<QWheelEvent *>(event);
if(wheelEvent->modifiers() & Qt::ControlModifier)
{
if(wheelEvent->angleDelta().y() > 0)
{
if(ui->comboScale->currentIndex() < ui->comboScale->count() - 1)
{
ui->comboScale->setCurrentIndex(ui->comboScale->currentIndex() + 1);
}
}
else
{
if(ui->comboScale->currentIndex() > 0)
{
ui->comboScale->setCurrentIndex(ui->comboScale->currentIndex() - 1);
}
}
return true;
}
}
}
return QMainWindow::eventFilter(object, event);
}
void MainWindow::keyPressEvent(QKeyEvent *event) void MainWindow::keyPressEvent(QKeyEvent *event)
{ {
bool quit = bool quit =
@ -348,17 +562,15 @@ void MainWindow::keyPressEvent(QKeyEvent *event)
if(quit) if(quit)
{ {
qApp->quit(); qApp->quit();
return;
} }
if(event->modifiers() & Qt::ControlModifier) if(event->modifiers() & Qt::ControlModifier)
{ {
processShortcut(event->key());
if(event->key() == Qt::Key_L) return;
{
ui->txtSearch->setFocus();
ui->txtSearch->selectAll();
}
} }
QWidget::keyPressEvent(event); QWidget::keyPressEvent(event);
} }
@ -404,10 +616,24 @@ void MainWindow::initSettingsTabs()
ui->txtSettingMountPaths->setText(mountPaths); ui->txtSettingMountPaths->setText(mountPaths);
ui->spinSettingNumerPerPages->setValue(numPagesPerPreview); ui->spinSettingNumerPerPages->setValue(numPagesPerPreview);
ui->txtSettingDatabasePath->setText(databasePath); ui->txtSettingDatabasePath->setText(databasePath);
bool horizontalScroll = settings.value(SETTINGS_KEY_PREVIEWS_SCROLL_HORIZONTALLY).toBool();
ui->radioScrollHorizontally->setChecked(horizontalScroll);
ui->radioScrollVertically->setChecked(!horizontalScroll);
} }
void MainWindow::saveSettings() void MainWindow::saveSettings()
{ {
if(ui->chkRemoveOldDb->isChecked())
{
bool result = QFile::remove(Common::databasePath());
if(!result)
{
QMessageBox::critical(this, "Error removing database",
"Failed to remove old database. Settings not saved.");
return;
}
}
QSettings settings; QSettings settings;
QString pdfViewerCmd = ui->txtSettingPdfPreviewerCmd->text(); QString pdfViewerCmd = ui->txtSettingPdfPreviewerCmd->text();
@ -420,6 +646,7 @@ void MainWindow::saveSettings()
settings.setValue(SETTINGS_KEY_MOUNTPATHS, mountPaths); settings.setValue(SETTINGS_KEY_MOUNTPATHS, mountPaths);
settings.setValue(SETTINGS_KEY_PREVIEWSPERPAGE, ui->spinSettingNumerPerPages->value()); settings.setValue(SETTINGS_KEY_PREVIEWSPERPAGE, ui->spinSettingNumerPerPages->value());
settings.setValue(SETTINGS_KEY_DBPATH, databasePath); settings.setValue(SETTINGS_KEY_DBPATH, databasePath);
settings.setValue(SETTINGS_KEY_PREVIEWS_SCROLL_HORIZONTALLY, ui->radioScrollHorizontally->isChecked());
settings.sync(); settings.sync();
@ -427,22 +654,26 @@ void MainWindow::saveSettings()
qApp->quit(); qApp->quit();
} }
void MainWindow::previewReceived(QSharedPointer<PreviewResult> preview, unsigned int previewGeneration) void MainWindow::previewReceived()
{ {
if(previewGeneration < this->currentPreviewGeneration)
{
return;
}
this->ui->previewProcessBar->setValue(this->ui->previewProcessBar->value() + 1); this->ui->previewProcessBar->setValue(this->ui->previewProcessBar->value() + 1);
QBoxLayout *layout = static_cast<QBoxLayout *>(ui->scrollAreaWidgetContents->layout());
int index = layout->count();
if(index > 0)
{
--index;
}
QSharedPointer<PreviewResult> preview = this->previewCoordinator.resultAt(index);
if(!preview.isNull() && preview->hasPreview()) if(!preview.isNull() && preview->hasPreview())
{ {
QString docPath = preview->getDocumentPath(); QString docPath = preview->getDocumentPath();
auto previewPage = preview->getPage(); auto previewPage = preview->getPage();
ClickLabel *headerLabel = new ClickLabel(); ClickLabel *headerLabel = new ClickLabel();
headerLabel->setText(QString("Path: ") + preview->getDocumentPath()); headerLabel->setText(QString("Path: ") + preview->getDocumentPath());
ClickLabel *label = dynamic_cast<ClickLabel *>(preview->createPreviewWidget()); ClickLabel *label = dynamic_cast<ClickLabel *>(preview->createPreviewWidget());
label->setMaximumWidth(QApplication::desktop()->availableGeometry().width() - 200);
QVBoxLayout *previewLayout = new QVBoxLayout(); QVBoxLayout *previewLayout = new QVBoxLayout();
@ -456,8 +687,8 @@ void MainWindow::previewReceived(QSharedPointer<PreviewResult> preview, unsigned
{ {
QFileInfo fileInfo{docPath}; QFileInfo fileInfo{docPath};
QMenu menu("labeRightClick", this); QMenu menu("labeRightClick", this);
createSearchResutlMenu(menu, fileInfo); createSearchResultMenu(menu, fileInfo);
menu.addAction("Copy page number", menu.addAction("Copy page number", this,
[previewPage] { QGuiApplication::clipboard()->setText(QString::number(previewPage)); }); [previewPage] { QGuiApplication::clipboard()->setText(QString::number(previewPage)); });
menu.exec(QCursor::pos()); menu.exec(QCursor::pos());
}; };
@ -474,11 +705,12 @@ void MainWindow::previewReceived(QSharedPointer<PreviewResult> preview, unsigned
previewLayout->setMargin(0); previewLayout->setMargin(0);
previewLayout->insertStretch(0, 1); previewLayout->insertStretch(0, 1);
previewLayout->insertStretch(-1, 1); previewLayout->insertStretch(-1, 1);
previewLayout->setAlignment(Qt::AlignCenter);
QWidget *previewWidget = new QWidget(); QWidget *previewWidget = new QWidget();
previewWidget->setLayout(previewLayout); previewWidget->setLayout(previewLayout);
ui->scrollAreaWidgetContents->layout()->addWidget(previewWidget); layout->insertWidget(index, previewWidget);
} }
} }
@ -495,6 +727,14 @@ void MainWindow::lineEditReturnPressed()
ui->tabWidget->setCurrentIndex(0); ui->tabWidget->setCurrentIndex(0);
} }
// TODO: validate q; // TODO: validate q;
while(this->searchHistory.size() > 30)
{
this->searchHistory.removeFirst();
}
this->searchHistory.append(q);
this->currentSearchHistoryIndex = this->searchHistory.size();
this->currentSavedSearchText.clear();
ui->treeResultsList->clear(); ui->treeResultsList->clear();
ui->lblSearchResults->setText("Searching..."); ui->lblSearchResults->setText("Searching...");
this->ui->txtSearch->setEnabled(false); this->ui->txtSearch->setEnabled(false);
@ -508,7 +748,6 @@ void MainWindow::lineEditReturnPressed()
LooqsQuery pathsQuery = tmpQuery; LooqsQuery pathsQuery = tmpQuery;
this->contentSearchQuery = tmpQuery; this->contentSearchQuery = tmpQuery;
this->contentSearchQuery.setTokens({});
bool addContentSearch = false; bool addContentSearch = false;
bool addPathSearch = false; bool addPathSearch = false;
@ -526,17 +765,15 @@ void MainWindow::lineEditReturnPressed()
return tokens; return tokens;
}; };
/* An explicit search, we just pass it on */ /* An explicit search, no lone words. We just pass it on */
if(!(tmpQuery.getTokensMask() & TokenType::WORD)) if(!(tmpQuery.getTokensMask() & TokenType::WORD))
{ {
if(tmpQuery.hasContentSearch()) if(tmpQuery.hasContentSearch())
{ {
this->contentSearchQuery.setTokens(createFinalTokens(TokenType::FILTER_CONTENT_CONTAINS));
addContentSearch = true; addContentSearch = true;
} }
else else
{ {
this->contentSearchQuery.setTokens(createFinalTokens(TokenType::FILTER_PATH_CONTAINS));
addPathSearch = true; addPathSearch = true;
} }
} }
@ -551,8 +788,7 @@ void MainWindow::lineEditReturnPressed()
/* A content search and lone words, e. g. c:("to be or not") ebooks */ /* A content search and lone words, e. g. c:("to be or not") ebooks */
else if(tmpQuery.hasContentSearch() && (tmpQuery.getTokensMask() & TokenType::WORD)) else if(tmpQuery.hasContentSearch() && (tmpQuery.getTokensMask() & TokenType::WORD))
{ {
this->contentSearchQuery = tmpQuery; this->contentSearchQuery = LooqsQuery::build(q, TokenType::FILTER_PATH_CONTAINS, false);
this->contentSearchQuery.setTokens(createFinalTokens(TokenType::FILTER_PATH_CONTAINS));
addContentSearch = true; addContentSearch = true;
addPathSearch = false; addPathSearch = false;
} }
@ -560,7 +796,7 @@ void MainWindow::lineEditReturnPressed()
else if(!tmpQuery.hasPathSearch() && !tmpQuery.hasContentSearch()) else if(!tmpQuery.hasPathSearch() && !tmpQuery.hasContentSearch())
{ {
this->contentSearchQuery.setTokens(createFinalTokens(TokenType::FILTER_CONTENT_CONTAINS)); this->contentSearchQuery.setTokens(createFinalTokens(TokenType::FILTER_CONTENT_CONTAINS));
pathsQuery.setTokens(createFinalTokens(TokenType::FILTER_PATH_CONTAINS)); pathsQuery = LooqsQuery::build(q, TokenType::FILTER_PATH_CONTAINS, false);
addContentSearch = true; addContentSearch = true;
addPathSearch = true; addPathSearch = true;
} }
@ -580,6 +816,10 @@ void MainWindow::lineEditReturnPressed()
} }
results.append(searcher.search(this->contentSearchQuery)); results.append(searcher.search(this->contentSearchQuery));
} }
else
{
this->contentSearchQuery.setTokens({});
}
return results; return results;
}); });
searchWatcher.setFuture(searchFuture); searchWatcher.setFuture(searchFuture);
@ -587,52 +827,59 @@ void MainWindow::lineEditReturnPressed()
void MainWindow::handleSearchResults(const QVector<SearchResult> &results) void MainWindow::handleSearchResults(const QVector<SearchResult> &results)
{ {
this->previewableSearchResults.clear(); qDeleteAll(ui->scrollAreaWidgetContents->children());
ui->treeResultsList->clear(); ui->treeResultsList->clear();
ui->comboPreviewFiles->clear(); ui->comboPreviewFiles->clear();
ui->comboPreviewFiles->addItem("All previews"); ui->comboPreviewFiles->addItem("All previews");
ui->comboPreviewFiles->setVisible(true); ui->comboPreviewFiles->setVisible(true);
ui->lblTotalPreviewPagesCount->setText("");
this->previewCoordinator.init(results);
bool hasDeleted = false; bool hasDeleted = false;
QHash<QString, bool> seenMap;
for(const SearchResult &result : results) for(const SearchResult &result : results)
{ {
QFileInfo pathInfo(result.fileData.absPath); const QString &absPath = result.fileData.absPath;
QFileInfo pathInfo(absPath);
QString fileName = pathInfo.fileName(); if(!seenMap.contains(absPath))
QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeResultsList);
QDateTime dt = QDateTime::fromSecsSinceEpoch(result.fileData.mtime);
item->setIcon(0, iconProvider.icon(pathInfo));
item->setText(0, fileName);
item->setText(1, result.fileData.absPath);
item->setText(2, dt.toString(Qt::ISODate));
item->setText(3, this->locale().formattedDataSize(result.fileData.size));
bool exists = pathInfo.exists();
if(exists)
{ {
if(!result.wasContentSearch) QString fileName = pathInfo.fileName();
{ QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeResultsList);
continue;
}
if(!pathInfo.suffix().contains("htm")) // hack until we can preview them properly... QDateTime dt = QDateTime::fromSecsSinceEpoch(result.fileData.mtime);
{ item->setIcon(0, iconProvider.icon(pathInfo));
if(PreviewGenerator::get(pathInfo) != nullptr) item->setText(0, fileName);
{ item->setText(1, absPath);
this->previewableSearchResults.append(result); item->setText(2, dt.toString(Qt::ISODate));
ui->comboPreviewFiles->addItem(result.fileData.absPath); item->setText(3, this->locale().formattedDataSize(result.fileData.size));
}
}
} }
else bool exists = pathInfo.exists();
if(!exists)
{ {
hasDeleted = true; hasDeleted = true;
} }
seenMap[absPath] = true;
} }
seenMap.clear();
for(const SearchResult &result : this->previewCoordinator.getPreviewableSearchResults())
{
const QString &absPath = result.fileData.absPath;
if(!seenMap.contains(absPath))
{
ui->comboPreviewFiles->addItem(absPath);
}
seenMap[absPath] = true;
}
ui->treeResultsList->resizeColumnToContents(0); ui->treeResultsList->resizeColumnToContents(0);
ui->treeResultsList->resizeColumnToContents(1); ui->treeResultsList->resizeColumnToContents(1);
ui->treeResultsList->resizeColumnToContents(2); ui->treeResultsList->resizeColumnToContents(2);
previewDirty = !this->previewableSearchResults.empty();
previewDirty = this->previewCoordinator.previewableCount() > 0;
ui->spinPreviewPage->setValue(1); ui->spinPreviewPage->setValue(1);
@ -641,7 +888,10 @@ void MainWindow::handleSearchResults(const QVector<SearchResult> &results)
makePreviews(1); makePreviews(1);
} }
ui->tabWidget->setTabEnabled(1, previewDirty);
QString statusText = "Results: " + QString::number(results.size()) + " files"; QString statusText = "Results: " + QString::number(results.size()) + " files";
statusText += ", previewable: " + QString::number(this->previewCoordinator.previewableCount());
if(hasDeleted) if(hasDeleted)
{ {
statusText += " WARNING: Some files are inaccessible. No preview available for those. Index may be out of sync"; statusText += " WARNING: Some files are inaccessible. No preview available for those. Index may be out of sync";
@ -658,18 +908,27 @@ int MainWindow::currentSelectedScale()
void MainWindow::makePreviews(int page) void MainWindow::makePreviews(int page)
{ {
if(this->previewableSearchResults.empty()) if(this->previewCoordinator.previewableCount() == 0)
{ {
return; return;
} }
qDeleteAll(ui->scrollAreaWidgetContents->children()); qDeleteAll(ui->scrollAreaWidgetContents->children());
ui->scrollAreaWidgetContents->setLayout(new QHBoxLayout()); QSettings settings;
ui->previewProcessBar->setMaximum(this->previewableSearchResults.size()); bool horizontalScroll = settings.value(SETTINGS_KEY_PREVIEWS_SCROLL_HORIZONTALLY, false).toBool();
processedPdfPreviews = 0; if(horizontalScroll)
{
ui->scrollAreaWidgetContents->setLayout(new QHBoxLayout());
}
else
{
ui->scrollAreaWidgetContents->setLayout(new QVBoxLayout());
ui->scrollAreaWidgetContents->layout()->setAlignment(Qt::AlignCenter);
}
ui->previewProcessBar->setMaximum(this->previewCoordinator.previewableCount());
QVector<QString> wordsToHighlight; QVector<QString> wordsToHighlight;
QRegularExpression extractor(R"#("([^"]*)"|((\p{L}|\p{N})+))#"); static QRegularExpression extractor(R"#("([^"]*)"|([^\s]+))#");
for(const Token &token : this->contentSearchQuery.getTokens()) for(const Token &token : this->contentSearchQuery.getTokens())
{ {
if(token.type == FILTER_CONTENT_CONTAINS) if(token.type == FILTER_CONTENT_CONTAINS)
@ -687,12 +946,12 @@ void MainWindow::makePreviews(int page)
} }
} }
} }
int end = previewsPerPage; int length = previewsPerPage;
int begin = page * previewsPerPage - previewsPerPage; int beginOffset = page * previewsPerPage - previewsPerPage;
if(begin < 0) if(beginOffset < 0)
{ {
// Should not happen actually // Should not happen actually
begin = 0; beginOffset = 0;
} }
int currentScale = currentSelectedScale(); int currentScale = currentSelectedScale();
@ -702,7 +961,7 @@ void MainWindow::makePreviews(int page)
renderConfig.wordsToHighlight = wordsToHighlight; renderConfig.wordsToHighlight = wordsToHighlight;
QVector<RenderTarget> targets; QVector<RenderTarget> targets;
for(SearchResult &sr : this->previewableSearchResults) for(const SearchResult &sr : this->previewCoordinator.getPreviewableSearchResults())
{ {
if(ui->comboPreviewFiles->currentIndex() != 0) if(ui->comboPreviewFiles->currentIndex() != 0)
{ {
@ -713,26 +972,24 @@ void MainWindow::makePreviews(int page)
} }
RenderTarget renderTarget; RenderTarget renderTarget;
renderTarget.path = sr.fileData.absPath; renderTarget.path = sr.fileData.absPath;
renderTarget.page = (int)sr.page;
for(unsigned int pagenum : sr.pages) targets.append(renderTarget);
{
renderTarget.page = (int)pagenum;
targets.append(renderTarget);
}
} }
int numpages = ceil(static_cast<double>(targets.size()) / previewsPerPage); int numpages = ceil(static_cast<double>(targets.size()) / previewsPerPage);
ui->spinPreviewPage->setMaximum(numpages); ui->spinPreviewPage->setMaximum(numpages);
targets = targets.mid(begin, end); targets = targets.mid(beginOffset, length);
ui->lblTotalPreviewPagesCount->setText(QString::number(numpages)); ui->lblTotalPreviewPagesCount->setText(QString::number(numpages));
ui->previewProcessBar->setMaximum(targets.count()); ui->previewProcessBar->setMaximum(targets.count());
ui->previewProcessBar->setMinimum(0); ui->previewProcessBar->setMinimum(0);
ui->previewProcessBar->setValue(0); ui->previewProcessBar->setValue(0);
ui->previewProcessBar->setVisible(this->previewableSearchResults.size() > 0); ui->previewProcessBar->setVisible(this->previewCoordinator.previewableCount() > 0);
++this->currentPreviewGeneration;
this->ui->spinPreviewPage->setEnabled(false); this->ui->spinPreviewPage->setEnabled(false);
this->ui->comboPreviewFiles->setEnabled(false); this->ui->comboPreviewFiles->setEnabled(false);
emit startIpcPreviews(renderConfig, targets); this->ui->txtSearch->setEnabled(false);
this->previewCoordinator.startGeneration(renderConfig, targets);
} }
void MainWindow::handleSearchError(QString error) void MainWindow::handleSearchError(QString error)
@ -740,27 +997,87 @@ void MainWindow::handleSearchError(QString error)
ui->lblSearchResults->setText("Error:" + error); ui->lblSearchResults->setText("Error:" + error);
} }
void MainWindow::createSearchResutlMenu(QMenu &menu, const QFileInfo &fileInfo) void MainWindow::createSearchResultMenu(QMenu &menu, const QFileInfo &fileInfo)
{ {
menu.addAction("Copy filename to clipboard", menu.addAction("Copy filename to clipboard", this,
[&fileInfo] { QGuiApplication::clipboard()->setText(fileInfo.fileName()); }); [&fileInfo] { QGuiApplication::clipboard()->setText(fileInfo.fileName()); });
menu.addAction("Copy full path to clipboard", menu.addAction("Copy full path to clipboard", this,
[&fileInfo] { QGuiApplication::clipboard()->setText(fileInfo.absoluteFilePath()); }); [&fileInfo] { QGuiApplication::clipboard()->setText(fileInfo.absoluteFilePath()); });
menu.addAction("Open containing folder", [this, &fileInfo] { this->openFile(fileInfo.absolutePath()); }); menu.addAction("Open containing folder", this, [this, &fileInfo] { this->openFile(fileInfo.absolutePath()); });
auto previewables = this->previewCoordinator.getPreviewableSearchResults();
auto result = auto result =
std::find_if(this->previewableSearchResults.begin(), this->previewableSearchResults.end(), std::find_if(previewables.begin(), previewables.end(),
[this, &fileInfo](SearchResult &a) { return fileInfo.absoluteFilePath() == a.fileData.absPath; }); [&fileInfo](SearchResult &a) { return fileInfo.absoluteFilePath() == a.fileData.absPath; });
if(result != this->previewableSearchResults.end()) if(result != previewables.end())
{ {
menu.addAction("Show previews for this file", menu.addAction("Show previews for this file", this,
[this, &fileInfo] [this, &fileInfo]
{ {
ui->tabWidget->setCurrentIndex(1); ui->tabWidget->setCurrentIndex(1);
this->ui->comboPreviewFiles->setCurrentText(fileInfo.absoluteFilePath()); this->ui->comboPreviewFiles->setCurrentText(fileInfo.absoluteFilePath());
}); });
} }
QMenu *tagMenu = menu.addMenu("Tag file with: ");
QVector<QString> allTags = this->dbService->getTags();
QHash<QString, bool> fileTags;
QString path = fileInfo.absoluteFilePath();
for(const QString &fileTag : this->dbService->getTagsForPath(path))
{
fileTags[fileTag] = true;
}
for(const QString &tag : allTags)
{
QCheckBox *checkBox = new QCheckBox(tagMenu);
QWidgetAction *checkableAction = new QWidgetAction(tagMenu);
checkableAction->setDefaultWidget(checkBox);
checkBox->setText(tag);
checkBox->setChecked(fileTags.contains(tag));
tagMenu->addAction(checkableAction);
connect(checkBox, &QCheckBox::stateChanged, this,
[this, checkBox, path]
{
QVector<QString> currentTags = this->dbService->getTagsForPath(path);
QString checkBoxText = checkBox->text();
if(checkBox->isChecked())
{
if(!this->tagManager->addTagsToPath(path, {checkBoxText}))
{
QMessageBox::critical(this, "Error while adding tag",
"An error occured while trying to add the tag");
}
}
else
{
if(!this->tagManager->removeTagsForPath(path, {checkBoxText}))
{
QMessageBox::critical(this, "Error while removing tag",
"An error occured while trying to remove the tag");
}
}
});
}
tagMenu->addAction("Add new tags", this,
[this, path]
{
bool ok;
QString text =
QInputDialog::getText(this, tr("Enter new tags"), tr("New tags (comma separated):"),
QLineEdit::Normal, "", &ok);
if(ok && !this->tagManager->addTagsToPath(path, text, ','))
{
QMessageBox::critical(this, "Error while trying to add tags",
"An error occured while trying to add tags");
}
});
} }
void MainWindow::openDocument(QString path, int num) void MainWindow::openDocument(QString path, int num)
@ -790,7 +1107,7 @@ void MainWindow::openFile(QString path)
QDesktopServices::openUrl(QUrl::fromLocalFile(path)); QDesktopServices::openUrl(QUrl::fromLocalFile(path));
} }
void MainWindow::treeSearchItemActivated(QTreeWidgetItem *item, int i) void MainWindow::treeSearchItemActivated(QTreeWidgetItem *item, int /*i*/)
{ {
openFile(item->text(1)); openFile(item->text(1));
} }
@ -804,17 +1121,25 @@ void MainWindow::showSearchResultsContextMenu(const QPoint &point)
} }
QFileInfo pathinfo(item->text(1)); QFileInfo pathinfo(item->text(1));
QMenu menu("SearchResults", this); QMenu menu("SearchResults", this);
createSearchResutlMenu(menu, pathinfo); createSearchResultMenu(menu, pathinfo);
menu.exec(QCursor::pos()); menu.exec(QCursor::pos());
} }
MainWindow::~MainWindow() MainWindow::~MainWindow()
{ {
syncerThread.terminate(); syncerThread.terminate();
ipcClientThread.terminate();
delete this->indexSyncer; delete this->indexSyncer;
delete this->dbService; delete this->dbService;
delete this->dbFactory; delete this->dbFactory;
delete this->indexer; delete this->indexer;
delete this->tagManager;
delete ui; delete ui;
} }
void MainWindow::closeEvent(QCloseEvent * /*event*/)
{
QStringList list = this->searchHistory.toList();
QSettings settings;
settings.setValue(SETTINGS_KEY_SEARCHHISTORY, list);
settings.sync();
}

查看文件

@ -12,8 +12,9 @@
#include <QProgressDialog> #include <QProgressDialog>
#include "../shared/looqsquery.h" #include "../shared/looqsquery.h"
#include "../shared/indexsyncer.h" #include "../shared/indexsyncer.h"
#include "ipcpreviewclient.h" #include "previewcoordinator.h"
#include "indexer.h" #include "indexer.h"
#include "tagmanager.h"
namespace Ui namespace Ui
{ {
class MainWindow; class MainWindow;
@ -23,52 +24,51 @@ class MainWindow : public QMainWindow
{ {
Q_OBJECT Q_OBJECT
public:
explicit MainWindow(QWidget *parent, QString socketPath);
~MainWindow();
signals:
void beginSearch(const QString &query);
void startPdfPreviewGeneration(QVector<SearchResult> paths, double scalefactor);
private: private:
DatabaseFactory *dbFactory; DatabaseFactory *dbFactory;
SqliteDbService *dbService; SqliteDbService *dbService;
Ui::MainWindow *ui; Ui::MainWindow *ui;
IPCPreviewClient ipcPreviewClient;
QThread ipcClientThread; PreviewCoordinator previewCoordinator;
QThread syncerThread; QThread syncerThread;
Indexer *indexer;
IndexSyncer *indexSyncer; IndexSyncer *indexSyncer;
QProgressDialog progressDialog; QProgressDialog progressDialog;
Indexer *indexer;
QFileIconProvider iconProvider; QFileIconProvider iconProvider;
bool previewDirty;
QSqlDatabase db; QSqlDatabase db;
QFutureWatcher<QVector<SearchResult>> searchWatcher; QFutureWatcher<QVector<SearchResult>> searchWatcher;
void add(QString path, unsigned int page); LooqsQuery contentSearchQuery;
QVector<SearchResult> previewableSearchResults; QVector<QString> searchHistory;
TagManager *tagManager;
int currentSearchHistoryIndex = 0;
QString currentSavedSearchText;
bool previewDirty = false;
int previewsPerPage = 20;
void connectSignals(); void connectSignals();
void makePreviews(int page); void makePreviews(int page);
bool previewTabActive(); bool previewTabActive();
bool indexerTabActive(); bool indexerTabActive();
void keyPressEvent(QKeyEvent *event) override; void keyPressEvent(QKeyEvent *event) override;
unsigned int processedPdfPreviews;
void handleSearchResults(const QVector<SearchResult> &results); void handleSearchResults(const QVector<SearchResult> &results);
void handleSearchError(QString error); void handleSearchError(QString error);
LooqsQuery contentSearchQuery; void createSearchResultMenu(QMenu &menu, const QFileInfo &fileInfo);
int previewsPerPage;
void createSearchResutlMenu(QMenu &menu, const QFileInfo &fileInfo);
void openDocument(QString path, int num); void openDocument(QString path, int num);
void openFile(QString path); void openFile(QString path);
unsigned int currentPreviewGeneration = 1;
void initSettingsTabs(); void initSettingsTabs();
int currentSelectedScale(); int currentSelectedScale();
void processShortcut(int key);
bool eventFilter(QObject *object, QEvent *event) override;
private slots: private slots:
void lineEditReturnPressed(); void lineEditReturnPressed();
void treeSearchItemActivated(QTreeWidgetItem *item, int i); void treeSearchItemActivated(QTreeWidgetItem *item, int i);
void showSearchResultsContextMenu(const QPoint &point); void showSearchResultsContextMenu(const QPoint &point);
void tabChanged(); void tabChanged();
void previewReceived(QSharedPointer<PreviewResult> preview, unsigned int previewGeneration); void previewReceived();
void comboScaleChanged(int i); void comboScaleChanged(int i);
void spinPreviewPageValueChanged(int val); void spinPreviewPageValueChanged(int val);
void startIndexing(); void startIndexing();
@ -82,6 +82,16 @@ class MainWindow : public QMainWindow
void startIpcPreviews(RenderConfig config, const QVector<RenderTarget> &targets); void startIpcPreviews(RenderConfig config, const QVector<RenderTarget> &targets);
void stopIpcPreviews(); void stopIpcPreviews();
void beginIndexSync(); void beginIndexSync();
public:
explicit MainWindow(QWidget *parent, QString socketPath);
~MainWindow();
signals:
void beginSearch(const QString &query);
void startPdfPreviewGeneration(QVector<SearchResult> paths, double scalefactor);
protected:
void closeEvent(QCloseEvent *event) override;
}; };
#endif // MAINWINDOW_H #endif // MAINWINDOW_H

查看文件

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>1280</width> <width>1280</width>
<height>855</height> <height>923</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -18,16 +18,13 @@
<item> <item>
<widget class="QLineEdit" name="txtSearch"/> <widget class="QLineEdit" name="txtSearch"/>
</item> </item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3"/>
</item>
<item> <item>
<widget class="QTabWidget" name="tabWidget"> <widget class="QTabWidget" name="tabWidget">
<property name="tabPosition"> <property name="tabPosition">
<enum>QTabWidget::South</enum> <enum>QTabWidget::South</enum>
</property> </property>
<property name="currentIndex"> <property name="currentIndex">
<number>1</number> <number>2</number>
</property> </property>
<widget class="QWidget" name="resultsTab"> <widget class="QWidget" name="resultsTab">
<attribute name="title"> <attribute name="title">
@ -82,7 +79,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>1244</width> <width>1244</width>
<height>565</height> <height>641</height>
</rect> </rect>
</property> </property>
<layout class="QHBoxLayout" name="horizontalLayout"/> <layout class="QHBoxLayout" name="horizontalLayout"/>
@ -165,7 +162,7 @@
<item> <item>
<widget class="QComboBox" name="comboPreviewFiles"> <widget class="QComboBox" name="comboPreviewFiles">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed"> <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch> <horstretch>0</horstretch>
<verstretch>0</verstretch> <verstretch>0</verstretch>
</sizepolicy> </sizepolicy>
@ -195,62 +192,6 @@
</attribute> </attribute>
<layout class="QGridLayout" name="gridLayout"> <layout class="QGridLayout" name="gridLayout">
<item row="6" column="0"> <item row="6" column="0">
<widget class="QLineEdit" name="txtIgnorePatterns"/>
</item>
<item row="11" column="0">
<widget class="QPushButton" name="btnStartIndexing">
<property name="text">
<string>Start indexing</string>
</property>
</widget>
</item>
<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"> <widget class="QGroupBox" name="groupBoxIndexProgress">
<property name="contextMenuPolicy"> <property name="contextMenuPolicy">
<enum>Qt::PreventContextMenu</enum> <enum>Qt::PreventContextMenu</enum>
@ -452,6 +393,108 @@
</layout> </layout>
</widget> </widget>
</item> </item>
<item row="2" column="0">
<widget class="QGroupBox" name="groupBoxIndexOptions">
<property name="title">
<string>Index options</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_11">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Ignore patterns, separated by ';'. Example: *.js;*Downloads*:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="txtIgnorePatterns"/>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioIndexEverything">
<property name="text">
<string>Index everything (metadata + file content)</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkFillContentForContentless">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Index content for files previously indexed without content</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioMetadataOnly">
<property name="text">
<string>Index metadata only, don't process content of files</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="8" column="0">
<widget class="QPushButton" name="btnStartIndexing">
<property name="text">
<string>Start indexing</string>
</property>
</widget>
</item>
<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>
</layout> </layout>
</widget> </widget>
<widget class="QWidget" name="settingsTab"> <widget class="QWidget" name="settingsTab">
@ -532,9 +575,29 @@
<item> <item>
<widget class="QLineEdit" name="txtSettingDatabasePath"/> <widget class="QLineEdit" name="txtSettingDatabasePath"/>
</item> </item>
<item>
<widget class="QCheckBox" name="chkRemoveOldDb">
<property name="text">
<string>Remove old database on save</string>
</property>
</widget>
</item>
</layout> </layout>
</widget> </widget>
</item> </item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item> <item>
<widget class="QGroupBox" name="Misc"> <widget class="QGroupBox" name="Misc">
<property name="title"> <property name="title">
@ -544,7 +607,7 @@
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_9"> <layout class="QHBoxLayout" name="horizontalLayout_9">
<item> <item>
<widget class="QLabel" name="label_4"> <widget class="QLabel" name="lblMaxNumbersPreviewPages">
<property name="text"> <property name="text">
<string>Max number of previews per 'page' in 'Previews' tab: </string> <string>Max number of previews per 'page' in 'Previews' tab: </string>
</property> </property>
@ -568,22 +631,47 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_8">
<item>
<widget class="QLabel" name="lblScrollModeForPreviews">
<property name="text">
<string>Scroll mode for previews:</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioScrollVertically">
<property name="text">
<string>Vertically</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioScrollHorizontally">
<property name="text">
<string>Horizontally</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout> </layout>
</widget> </widget>
</item> </item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item> <item>
<widget class="QPushButton" name="btnSaveSettings"> <widget class="QPushButton" name="btnSaveSettings">
<property name="text"> <property name="text">
@ -656,5 +744,22 @@
</widget> </widget>
<layoutdefault spacing="6" margin="11"/> <layoutdefault spacing="6" margin="11"/>
<resources/> <resources/>
<connections/> <connections>
<connection>
<sender>radioIndexEverything</sender>
<signal>toggled(bool)</signal>
<receiver>chkFillContentForContentless</receiver>
<slot>setEnabled(bool)</slot>
<hints>
<hint type="sourcelabel">
<x>639</x>
<y>464</y>
</hint>
<hint type="destinationlabel">
<x>639</x>
<y>497</y>
</hint>
</hints>
</connection>
</connections>
</ui> </ui>

97
gui/previewcoordinator.cpp 普通文件
查看文件

@ -0,0 +1,97 @@
#include "previewcoordinator.h"
#include <QFileInfo>
PreviewCoordinator::PreviewCoordinator()
{
this->ipcPreviewClient.moveToThread(&this->ipcClientThread);
connect(&ipcPreviewClient, &IPCPreviewClient::previewReceived, this, &PreviewCoordinator::handleReceivedPreview,
Qt::QueuedConnection);
connect(&ipcPreviewClient, &IPCPreviewClient::finished, this, [&] { emit completedGeneration(); });
connect(this, &PreviewCoordinator::ipcStartGeneration, &ipcPreviewClient, &IPCPreviewClient::startGeneration,
Qt::QueuedConnection);
this->ipcClientThread.start();
}
void PreviewCoordinator::init(const QVector<SearchResult> &searchResults)
{
this->previewableSearchResults.clear();
for(const SearchResult &result : searchResults)
{
if(result.wasContentSearch)
{
QString path = result.fileData.absPath;
// HACK until we can preview them properly
if(path.endsWith(".html") || path.endsWith(".htm"))
{
continue;
}
QFileInfo info{path};
if(info.exists())
{
this->previewableSearchResults.append(result);
}
}
}
}
void PreviewCoordinator::setSocketPath(QString socketPath)
{
this->socketPath = socketPath;
this->ipcPreviewClient.setSocketPath(socketPath);
}
int PreviewCoordinator::previewableCount() const
{
return this->previewableSearchResults.count();
}
QSharedPointer<PreviewResult> PreviewCoordinator::resultAt(int index)
{
if(this->previewResults.size() > index)
{
return {this->previewResults[index]};
}
return {nullptr};
}
const QVector<SearchResult> &PreviewCoordinator::getPreviewableSearchResults() const
{
return this->previewableSearchResults;
}
void PreviewCoordinator::handleReceivedPreview(QSharedPointer<PreviewResult> preview, unsigned int previewGeneration)
{
if(previewGeneration < this->currentPreviewGeneration)
{
return;
}
if(!preview.isNull() && preview->hasPreview())
{
QString docPath = preview->getDocumentPath();
auto previewPage = preview->getPage();
int pos = previewOrder[docPath + QString::number(previewPage)];
this->previewResults[pos] = preview;
emit previewReady();
}
}
void PreviewCoordinator::startGeneration(RenderConfig config, const QVector<RenderTarget> &targets)
{
++this->currentPreviewGeneration;
this->previewOrder.clear();
this->previewResults.clear();
this->previewResults.resize(targets.size());
this->previewResults.fill(nullptr);
int i = 0;
for(const RenderTarget &target : targets)
{
this->previewOrder[target.path + QString::number(target.page)] = i++;
}
emit ipcStartGeneration(config, targets);
}

48
gui/previewcoordinator.h 普通文件
查看文件

@ -0,0 +1,48 @@
#ifndef PREVIEWCOORDINATOR_H
#define PREVIEWCOORDINATOR_H
#include <QVector>
#include <QObject>
#include <QThread>
#include "searchresult.h"
#include "previewresult.h"
#include "ipcpreviewclient.h"
#include "rendertarget.h"
class PreviewCoordinator : public QObject
{
Q_OBJECT
private:
QThread ipcClientThread;
IPCPreviewClient ipcPreviewClient;
QString socketPath;
QVector<QSharedPointer<PreviewResult>> previewResults;
QVector<SearchResult> previewableSearchResults;
unsigned int currentPreviewGeneration = 1;
/* Quick lookup table for the order a preview should have */
QHash<QString, int> previewOrder;
public:
PreviewCoordinator();
void init(const QVector<SearchResult> &searchResults);
int previewableCount() const;
const QVector<SearchResult> &getPreviewableSearchResults() const;
QSharedPointer<PreviewResult> resultAt(int index);
void setSocketPath(QString socketPath);
public slots:
void startGeneration(RenderConfig config, const QVector<RenderTarget> &targets);
void handleReceivedPreview(QSharedPointer<PreviewResult> preview, unsigned int previewGeneration);
signals:
void previewReady();
void completedGeneration();
void error(QString);
void ipcStartGeneration(RenderConfig config, const QVector<RenderTarget> &targets);
};
#endif // PREVIEWCOORDINATOR_H

查看文件

@ -1,20 +1,24 @@
#include "../shared/common.h" #include "../shared/common.h"
#include "previewgenerator.h" #include "previewgenerator.h"
#include <QMutexLocker>
#include "previewgeneratorpdf.h" #include "previewgeneratorpdf.h"
#include "previewgeneratorplaintext.h" #include "previewgeneratorplaintext.h"
#include "previewgeneratorodt.h" #include "previewgeneratorodt.h"
static PreviewGenerator *plainTextGenerator = new PreviewGeneratorPlainText(); static PreviewGenerator *plainTextGenerator = new PreviewGeneratorPlainText();
static QMap<QString, PreviewGenerator *> generators{ static QHash<QString, PreviewGenerator *> generators{
{"pdf", new PreviewGeneratorPdf()}, {"txt", plainTextGenerator}, {"md", plainTextGenerator}, {"pdf", new PreviewGeneratorPdf()}, {"txt", plainTextGenerator}, {"md", plainTextGenerator},
{"py", plainTextGenerator}, {"java", plainTextGenerator}, {"js", plainTextGenerator}, {"py", plainTextGenerator}, {"java", plainTextGenerator}, {"js", plainTextGenerator},
{"cpp", plainTextGenerator}, {"c", plainTextGenerator}, {"sql", plainTextGenerator}, {"cpp", plainTextGenerator}, {"c", plainTextGenerator}, {"sql", plainTextGenerator},
{"odt", new PreviewGeneratorOdt()}}; {"odt", new PreviewGeneratorOdt()}};
static QMutex generatorsMutex;
PreviewGenerator *PreviewGenerator::get(QFileInfo &info) PreviewGenerator *PreviewGenerator::get(QFileInfo &info)
{ {
QMutexLocker locker(&generatorsMutex);
PreviewGenerator *result = generators.value(info.suffix(), nullptr); PreviewGenerator *result = generators.value(info.suffix(), nullptr);
locker.unlock();
if(result == nullptr) if(result == nullptr)
{ {
if(Common::isTextFile(info)) if(Common::isTextFile(info))

查看文件

@ -24,7 +24,7 @@ QSharedPointer<PreviewResult> PreviewGeneratorOdt::generate(RenderConfig config,
throw LooqsGeneralException("Error while reading content.xml of " + documentPath); throw LooqsGeneralException("Error while reading content.xml of " + documentPath);
} }
TagStripperProcessor tsp; TagStripperProcessor tsp;
QString content = tsp.process(entireContent).first().content; QString content = tsp.process(entireContent).pages.constFirst().content;
PreviewGeneratorPlainText plainTextGenerator; PreviewGeneratorPlainText plainTextGenerator;
result->setText(plainTextGenerator.generatePreviewText(content, config, info.fileName())); result->setText(plainTextGenerator.generatePreviewText(content, config, info.fileName()));

查看文件

@ -1,15 +1,18 @@
#include <QMutexLocker> #include <QMutexLocker>
#include <QPainter> #include <QPainter>
#include <QRegularExpression>
#include "previewgeneratorpdf.h" #include "previewgeneratorpdf.h"
static QMutex cacheMutex; static QMutex cacheMutex;
Poppler::Document *PreviewGeneratorPdf::document(QString path) Poppler::Document *PreviewGeneratorPdf::document(QString path)
{ {
QMutexLocker locker(&cacheMutex);
if(documentcache.contains(path)) if(documentcache.contains(path))
{ {
return documentcache.value(path); return documentcache.value(path);
} }
locker.unlock();
Poppler::Document *result = Poppler::Document::load(path); Poppler::Document *result = Poppler::Document::load(path);
if(result == nullptr) if(result == nullptr)
{ {
@ -17,7 +20,10 @@ Poppler::Document *PreviewGeneratorPdf::document(QString path)
return nullptr; return nullptr;
} }
result->setRenderHint(Poppler::Document::TextAntialiasing); result->setRenderHint(Poppler::Document::TextAntialiasing);
QMutexLocker locker(&cacheMutex); result->setRenderHint(Poppler::Document::TextHinting);
result->setRenderHint(Poppler::Document::TextSlightHinting);
locker.relock();
documentcache.insert(path, result); documentcache.insert(path, result);
locker.unlock(); locker.unlock();
return result; return result;
@ -45,7 +51,12 @@ QSharedPointer<PreviewResult> PreviewGeneratorPdf::generate(RenderConfig config,
QImage img = pdfPage->renderToImage(config.scaleX, config.scaleY); QImage img = pdfPage->renderToImage(config.scaleX, config.scaleY);
for(QString &word : config.wordsToHighlight) for(QString &word : config.wordsToHighlight)
{ {
QList<QRectF> rects = pdfPage->search(word, Poppler::Page::SearchFlag::IgnoreCase); QList<QRectF> rects =
pdfPage->search(word, Poppler::Page::SearchFlag::IgnoreCase | Poppler::Page::SearchFlag::WholeWords);
if(rects.empty())
{
rects = pdfPage->search(word, Poppler::Page::SearchFlag::IgnoreCase);
}
for(QRectF &rect : rects) for(QRectF &rect : rects)
{ {
QPainter painter(&img); QPainter painter(&img);

查看文件

@ -1,7 +1,9 @@
#include <QTextStream> #include <QTextStream>
#include <QRegularExpression>
#include "previewgeneratorplaintext.h" #include "previewgeneratorplaintext.h"
#include "previewresultplaintext.h" #include "previewresultplaintext.h"
#include "../shared/limitqueue.h"
QString PreviewGeneratorPlainText::generatePreviewText(QString content, RenderConfig config, QString fileName) QString PreviewGeneratorPlainText::generatePreviewText(QString content, RenderConfig config, QString fileName)
{ {
@ -14,14 +16,13 @@ QString PreviewGeneratorPlainText::generatePreviewText(QString content, RenderCo
QHash<QString, int> countmap; QHash<QString, int> countmap;
const unsigned int maxSnippets = 7;
unsigned int currentSnippets = 0; unsigned int currentSnippets = 0;
for(QString &word : config.wordsToHighlight) for(QString &word : config.wordsToHighlight)
{ {
int lastPos = 0; int lastPos = 0;
int index = content.indexOf(word, lastPos, Qt::CaseInsensitive); int index = content.indexOf(word, lastPos, Qt::CaseInsensitive);
while(index != -1 && currentSnippets < maxSnippets) while(index != -1 && currentSnippets < MAX_SNIPPETS)
{ {
countmap[word] = countmap.value(word, 0) + 1; countmap[word] = countmap.value(word, 0) + 1;
@ -57,17 +58,15 @@ QString PreviewGeneratorPlainText::generatePreviewText(QString content, RenderCo
++i; ++i;
} }
for(QString &word : config.wordsToHighlight) resulText = resulText.toHtmlEscaped();
{
resulText.replace(word, "<span style=\"background-color: yellow;\">" + word + "</span>", Qt::CaseInsensitive);
}
QString header = "<b>" + fileName + "</b> "; QString header = "<b>" + fileName + "</b> ";
for(QString &word : config.wordsToHighlight) for(QString &word : config.wordsToHighlight)
{ {
resulText.replace(word, "<span style=\"background-color: yellow;\">" + word + "</span>", Qt::CaseInsensitive);
header += word + ": " + QString::number(countmap[word]) + " "; header += word + ": " + QString::number(countmap[word]) + " ";
} }
if(currentSnippets == maxSnippets)
if(currentSnippets == MAX_SNIPPETS)
{ {
header += "(truncated)"; header += "(truncated)";
} }
@ -77,6 +76,193 @@ QString PreviewGeneratorPlainText::generatePreviewText(QString content, RenderCo
return header + resulText.replace("\n", "<br>").mid(0, 1000); return header + resulText.replace("\n", "<br>").mid(0, 1000);
} }
struct Snippet
{
/* Contains each line number and line of the snippet*/
QString snippetText;
/* How many times a word occurs in the snippetText */
QHash<QString, int> wordCountMap;
};
QString PreviewGeneratorPlainText::generateLineBasedPreviewText(QTextStream &in, RenderConfig config, QString fileName)
{
QVector<Snippet> snippets;
const int contextLinesCount = 2;
LimitQueue<QString> queue(contextLinesCount);
QString currentLine;
currentLine.reserve(512);
/* How many lines to read after a line with a match (like grep -A ) */
int justReadLinesCount = -1;
struct Snippet currentSnippet;
auto appendLine = [&currentSnippet, &config](int lineNumber, QString &line)
{
int foundWordsCount = 0;
for(QString &word : config.wordsToHighlight)
{
QRegularExpression searchRegex("\\b" + QRegularExpression::escape(word) + "\\b");
bool containsRegex = line.contains(searchRegex);
bool contains = false;
if(!containsRegex)
{
contains = line.contains(word, Qt::CaseInsensitive);
}
if(containsRegex || contains)
{
currentSnippet.wordCountMap[word] = currentSnippet.wordCountMap.value(word, 0) + 1;
QString replacementString = "<span style=\"background-color: yellow;\">" + word + "</span>";
if(containsRegex)
{
line.replace(searchRegex, replacementString);
}
else
{
line.replace(word, replacementString, Qt::CaseInsensitive);
}
++foundWordsCount;
}
}
currentSnippet.snippetText.append(QString("<b>%1</b>%2<br>").arg(lineNumber).arg(line));
return foundWordsCount;
};
unsigned int lineCount = 0;
while(in.readLineInto(&currentLine))
{
currentLine = currentLine.toHtmlEscaped();
++lineCount;
bool matched = false;
if(justReadLinesCount > 0)
{
int result = appendLine(lineCount, currentLine);
if(justReadLinesCount == 1 && result > 0)
{
justReadLinesCount = contextLinesCount;
}
else
{
--justReadLinesCount;
}
continue;
}
if(justReadLinesCount == 0)
{
currentSnippet.snippetText += "---<br>";
justReadLinesCount = -1;
snippets.append(currentSnippet);
currentSnippet = {};
}
for(QString &word : config.wordsToHighlight)
{
if(currentLine.contains(word, Qt::CaseInsensitive))
{
matched = true;
break;
}
}
if(matched)
{
while(queue.size() > 0)
{
int queuedLineCount = lineCount - queue.size();
QString queuedLine = queue.dequeue();
appendLine(queuedLineCount, queuedLine);
}
appendLine(lineCount, currentLine);
justReadLinesCount = contextLinesCount;
}
else
{
queue.enqueue(currentLine);
}
}
if(!currentSnippet.snippetText.isEmpty())
{
currentSnippet.snippetText += "---<br>";
snippets.append(currentSnippet);
}
std::sort(snippets.begin(), snippets.end(),
[](Snippet &a, Snippet &b)
{
int differentWordsA = 0;
int totalWordsA = 0;
int differentWordsB = 0;
int totalWordsB = 0;
for(int count : qAsConst(a.wordCountMap))
{
if(count > 0)
{
++differentWordsA;
}
totalWordsA += count;
}
for(int count : qAsConst(b.wordCountMap))
{
if(count > 0)
{
++differentWordsB;
}
totalWordsB += count;
}
if(differentWordsA > differentWordsB)
{
return true;
}
if(differentWordsA == differentWordsB)
{
return totalWordsA > totalWordsB;
}
return false;
});
QString resultText = "";
unsigned int snippetsCount = 0;
QString header = "<b>" + fileName + "</b> ";
QHash<QString, int> totalWordCountMap;
bool isTruncated = false;
for(Snippet &snippet : snippets)
{
if(snippetsCount++ < MAX_SNIPPETS)
{
resultText += snippet.snippetText;
}
else
{
isTruncated = true;
}
for(auto it = snippet.wordCountMap.keyValueBegin(); it != snippet.wordCountMap.keyValueEnd(); it++)
{
totalWordCountMap[it->first] = totalWordCountMap.value(it->first, 0) + it->second;
}
}
if(!resultText.isEmpty())
{
if(isTruncated)
{
header += "(truncated) ";
}
for(QString &word : config.wordsToHighlight)
{
header += word + ": " + QString::number(totalWordCountMap[word]) + " ";
}
header += "<hr>";
resultText = header + resultText;
}
return resultText;
}
QSharedPointer<PreviewResult> PreviewGeneratorPlainText::generate(RenderConfig config, QString documentPath, QSharedPointer<PreviewResult> PreviewGeneratorPlainText::generate(RenderConfig config, QString documentPath,
unsigned int page) unsigned int page)
{ {
@ -87,9 +273,7 @@ QSharedPointer<PreviewResult> PreviewGeneratorPlainText::generate(RenderConfig c
return QSharedPointer<PreviewResultPlainText>(result); return QSharedPointer<PreviewResultPlainText>(result);
} }
QTextStream in(&file); QTextStream in(&file);
QString content = in.readAll();
QFileInfo info{documentPath}; QFileInfo info{documentPath};
result->setText(generatePreviewText(content, config, info.fileName())); result->setText(generateLineBasedPreviewText(in, config, info.fileName()));
return QSharedPointer<PreviewResultPlainText>(result); return QSharedPointer<PreviewResultPlainText>(result);
} }

查看文件

@ -1,12 +1,17 @@
#ifndef PREVIEWGENERATORPLAINTEXT_H #ifndef PREVIEWGENERATORPLAINTEXT_H
#define PREVIEWGENERATORPLAINTEXT_H #define PREVIEWGENERATORPLAINTEXT_H
#include <QTextStream>
#include "previewgenerator.h" #include "previewgenerator.h"
class PreviewGeneratorPlainText : public PreviewGenerator class PreviewGeneratorPlainText : public PreviewGenerator
{ {
protected:
const unsigned int MAX_SNIPPETS = 7;
public: public:
using PreviewGenerator::PreviewGenerator; using PreviewGenerator::PreviewGenerator;
QString generatePreviewText(QString content, RenderConfig config, QString fileName); QString generatePreviewText(QString content, RenderConfig config, QString fileName);
QString generateLineBasedPreviewText(QTextStream &in, RenderConfig config, QString fileName);
QSharedPointer<PreviewResult> generate(RenderConfig config, QString documentPath, unsigned int page); QSharedPointer<PreviewResult> generate(RenderConfig config, QString documentPath, unsigned int page);
}; };

查看文件

@ -30,7 +30,7 @@ QByteArray PreviewResultPdf::serialize() const
QSharedPointer<PreviewResultPdf> PreviewResultPdf::deserialize(QByteArray &ba) QSharedPointer<PreviewResultPdf> PreviewResultPdf::deserialize(QByteArray &ba)
{ {
PreviewResultPdf *result = new PreviewResultPdf(); QSharedPointer<PreviewResultPdf> result(new PreviewResultPdf());
PreviewResultType type; PreviewResultType type;
QDataStream stream{&ba, QIODevice::ReadOnly}; QDataStream stream{&ba, QIODevice::ReadOnly};
@ -40,5 +40,5 @@ QSharedPointer<PreviewResultPdf> PreviewResultPdf::deserialize(QByteArray &ba)
throw std::runtime_error("Invalid byte array: Not a pdf preview"); throw std::runtime_error("Invalid byte array: Not a pdf preview");
} }
stream >> result->documentPath >> result->page >> result->previewImage; stream >> result->documentPath >> result->page >> result->previewImage;
return QSharedPointer<PreviewResultPdf>(result); return result;
} }

查看文件

@ -40,7 +40,8 @@ QByteArray PreviewResultPlainText::serialize() const
QSharedPointer<PreviewResultPlainText> PreviewResultPlainText::deserialize(QByteArray &ba) QSharedPointer<PreviewResultPlainText> PreviewResultPlainText::deserialize(QByteArray &ba)
{ {
PreviewResultPlainText *result = new PreviewResultPlainText(); QSharedPointer<PreviewResultPlainText> result(new PreviewResultPlainText());
PreviewResultType type; PreviewResultType type;
QDataStream stream{&ba, QIODevice::ReadOnly}; QDataStream stream{&ba, QIODevice::ReadOnly};
@ -50,5 +51,5 @@ QSharedPointer<PreviewResultPlainText> PreviewResultPlainText::deserialize(QByte
throw std::runtime_error("Invalid byte array: Not a pdf preview"); throw std::runtime_error("Invalid byte array: Not a pdf preview");
} }
stream >> result->documentPath >> result->page >> result->text; stream >> result->documentPath >> result->page >> result->text;
return QSharedPointer<PreviewResultPlainText>(result); return result;
} }

查看文件

@ -9,6 +9,8 @@
#define SETTINGS_KEY_EXCLUDEDPATHS "excludedpaths" #define SETTINGS_KEY_EXCLUDEDPATHS "excludedpaths"
#define SETTINGS_KEY_MOUNTPATHS "mountpaths" #define SETTINGS_KEY_MOUNTPATHS "mountpaths"
#define SETTINGS_KEY_PREVIEWSPERPAGE "previewsPerPage" #define SETTINGS_KEY_PREVIEWSPERPAGE "previewsPerPage"
#define SETTINGS_KEY_SEARCHHISTORY "searchhistory"
#define SETTINGS_KEY_PREVIEWS_SCROLL_HORIZONTALLY "horizontalscroll"
namespace Common namespace Common
{ {

查看文件

@ -24,7 +24,9 @@ QString DefaultTextProcessor::processText(const QByteArray &data) const
return {}; return {};
} }
QVector<PageData> DefaultTextProcessor::process(const QByteArray &data) const DocumentProcessResult DefaultTextProcessor::process(const QByteArray &data) const
{ {
return {{0, processText(data)}}; DocumentProcessResult result;
result.pages.append({0, processText(data)});
return result;
} }

查看文件

@ -11,7 +11,7 @@ class DefaultTextProcessor : public Processor
public: public:
DefaultTextProcessor(); DefaultTextProcessor();
QString processText(const QByteArray &data) const; QString processText(const QByteArray &data) const;
QVector<PageData> process(const QByteArray &data) const override; DocumentProcessResult process(const QByteArray &data) const override;
}; };
#endif // DEFAULTTEXTPROCESSOR_H #endif // DEFAULTTEXTPROCESSOR_H

查看文件

@ -0,0 +1,31 @@
#include "documentoutlineentry.h"
DocumentOutlineEntry::DocumentOutlineEntry()
{
}
QDataStream &operator<<(QDataStream &out, const DocumentOutlineEntry &pd)
{
out << pd.text << pd.type << pd.destinationPage;
out << pd.children.size();
for(const DocumentOutlineEntry &entry : pd.children)
{
out << entry;
}
return out;
}
QDataStream &operator>>(QDataStream &in, DocumentOutlineEntry &pd)
{
in >> pd.text >> pd.type >> pd.destinationPage;
int numChildren;
in >> numChildren;
for(int i = 0; i < numChildren; i++)
{
DocumentOutlineEntry entry;
in >> entry;
pd.children.append(entry);
}
return in;
}

查看文件

@ -0,0 +1,29 @@
#ifndef DOCUMENTOUTLINEENTRY_H
#define DOCUMENTOUTLINEENTRY_H
#include <QMetaType>
#include <QDataStream>
#include <QString>
enum OutlineDestinationType
{
OUTLINE_DESTINATION_TYPE_NONE,
OUTLINE_DESTINATION_TYPE_PAGE
/* In the future, links, or #anchors are possible */
};
class DocumentOutlineEntry
{
public:
DocumentOutlineEntry();
QVector<DocumentOutlineEntry> children;
OutlineDestinationType type;
QString text;
unsigned int destinationPage;
};
Q_DECLARE_METATYPE(DocumentOutlineEntry);
QDataStream &operator<<(QDataStream &out, const DocumentOutlineEntry &pd);
QDataStream &operator>>(QDataStream &in, DocumentOutlineEntry &pd);
#endif // DOCUMENTOUTLINEENTRY_H

查看文件

@ -0,0 +1,39 @@
#include "documentprocessresult.h"
QDataStream &operator<<(QDataStream &out, const DocumentProcessResult &pd)
{
out << pd.pages.size();
out << pd.outlines.size();
for(const PageData &pd : pd.pages)
{
out << pd;
}
for(const DocumentOutlineEntry &outline : pd.outlines)
{
out << outline;
}
return out;
}
QDataStream &operator>>(QDataStream &in, DocumentProcessResult &pd)
{
int numPages, numOutlines;
in >> numPages;
in >> numOutlines;
for(int i = 0; i < numPages; i++)
{
PageData data;
in >> data;
pd.pages.append(data);
}
for(int i = 0; i < numOutlines; i++)
{
DocumentOutlineEntry outline;
in >> outline;
pd.outlines.append(outline);
}
return in;
}

查看文件

@ -0,0 +1,17 @@
#ifndef DOCUMENTPROCESSRESULT_H
#define DOCUMENTPROCESSRESULT_H
#include <pagedata.h>
#include <documentoutlineentry.h>
class DocumentProcessResult
{
public:
QVector<PageData> pages;
QVector<DocumentOutlineEntry> outlines;
};
Q_DECLARE_METATYPE(DocumentProcessResult);
QDataStream &operator<<(QDataStream &out, const DocumentProcessResult &pd);
QDataStream &operator>>(QDataStream &in, DocumentProcessResult &pd);
#endif // DOCUMENTPROCESSRESULT_H

查看文件

@ -25,10 +25,22 @@ SaveFileResult FileSaver::addFile(QString path)
QString absPath = info.absoluteFilePath(); QString absPath = info.absoluteFilePath();
auto mtime = info.lastModified().toSecsSinceEpoch(); auto mtime = info.lastModified().toSecsSinceEpoch();
if(this->dbService->fileExistsInDatabase(absPath, mtime))
bool exists = false;
if(this->fileSaverOptions.fillExistingContentless)
{
exists = this->dbService->fileExistsInDatabase(absPath, mtime, 'c');
}
else
{
exists = this->dbService->fileExistsInDatabase(absPath, mtime);
}
if(exists)
{ {
return SKIPPED; return SKIPPED;
} }
return saveFile(info); return saveFile(info);
} }
@ -38,18 +50,17 @@ SaveFileResult FileSaver::updateFile(QString path)
return saveFile(info); return saveFile(info);
} }
int FileSaver::addFiles(const QVector<QString> paths, bool keepGoing, bool verbose) int FileSaver::addFiles(const QVector<QString> paths)
{ {
return processFiles(paths, std::bind(&FileSaver::addFile, this, std::placeholders::_1), keepGoing, verbose); return processFiles(paths, std::bind(&FileSaver::addFile, this, std::placeholders::_1));
} }
int FileSaver::updateFiles(const QVector<QString> paths, bool keepGoing, bool verbose) int FileSaver::updateFiles(const QVector<QString> paths)
{ {
return processFiles(paths, std::bind(&FileSaver::updateFile, this, std::placeholders::_1), keepGoing, verbose); return processFiles(paths, std::bind(&FileSaver::updateFile, this, std::placeholders::_1));
} }
int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFileResult(QString path)> saverFunc, int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFileResult(QString path)> saverFunc)
bool keepGoing, bool verbose)
{ {
std::atomic<bool> terminate{false}; std::atomic<bool> terminate{false};
std::atomic<int> processedCount{0}; std::atomic<int> processedCount{0};
@ -60,7 +71,7 @@ int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFile
{ {
return; return;
} }
if(verbose) if(this->fileSaverOptions.verbose)
{ {
Logger::info() << "Processing " << path << Qt::endl; Logger::info() << "Processing " << path << Qt::endl;
} }
@ -68,7 +79,7 @@ int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFile
if(result == DBFAIL || result == PROCESSFAIL) if(result == DBFAIL || result == PROCESSFAIL)
{ {
Logger::error() << "Failed to process " << path << Qt::endl; Logger::error() << "Failed to process " << path << Qt::endl;
if(!keepGoing) if(!this->fileSaverOptions.keepGoing)
{ {
terminate = true; terminate = true;
} }
@ -76,7 +87,7 @@ int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFile
else else
{ {
++processedCount; ++processedCount;
if(verbose) if(this->fileSaverOptions.verbose)
{ {
if(result == SKIPPED) if(result == SKIPPED)
{ {
@ -99,7 +110,7 @@ int FileSaver::processFiles(const QVector<QString> paths, std::function<SaveFile
SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo) SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
{ {
QVector<PageData> pageData; DocumentProcessResult processResult;
QString canonicalPath = fileInfo.canonicalFilePath(); QString canonicalPath = fileInfo.canonicalFilePath();
int processorReturnCode = -1; int processorReturnCode = -1;
@ -120,11 +131,26 @@ SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
{ {
if(canonicalPath.startsWith(excludedPath)) if(canonicalPath.startsWith(excludedPath))
{ {
if(this->fileSaverOptions.verbose)
{
Logger::info() << "Skipped due to excluded path";
}
return SKIPPED; return SKIPPED;
} }
} }
if(fileInfo.size() > 0) bool mustFillContent = this->fileSaverOptions.fillExistingContentless;
if(!mustFillContent)
{
mustFillContent = !this->fileSaverOptions.metadataOnly;
if(mustFillContent)
{
auto filetype = this->dbService->queryFileType(fileInfo.absolutePath());
mustFillContent = !filetype.has_value() || filetype.value() == 'c';
}
}
if(fileInfo.size() > 0 && mustFillContent)
{ {
QProcess process; QProcess process;
QStringList args; QStringList args;
@ -143,11 +169,10 @@ SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
* finishes. * finishes.
*/ */
QDataStream in(process.readAllStandardOutput()); QDataStream in(process.readAllStandardOutput());
while(!in.atEnd())
if(!in.atEnd())
{ {
PageData pd; in >> processResult;
in >> pd;
pageData.append(pd);
} }
processorReturnCode = process.exitCode(); processorReturnCode = process.exitCode();
if(processorReturnCode != OK && processorReturnCode != OK_WASEMPTY) if(processorReturnCode != OK && processorReturnCode != OK_WASEMPTY)
@ -159,7 +184,7 @@ SaveFileResult FileSaver::saveFile(const QFileInfo &fileInfo)
} }
} }
} }
SaveFileResult result = this->dbService->saveFile(fileInfo, pageData); SaveFileResult result = this->dbService->saveFile(fileInfo, processResult, this->fileSaverOptions.metadataOnly);
if(result == OK && processorReturnCode == OK_WASEMPTY) if(result == OK && processorReturnCode == OK_WASEMPTY)
{ {
return OK_WASEMPTY; return OK_WASEMPTY;

查看文件

@ -2,6 +2,7 @@
#define FILESAVER_H #define FILESAVER_H
#include <QSqlDatabase> #include <QSqlDatabase>
#include <QFileInfo> #include <QFileInfo>
#include "filesaveroptions.h"
#include "pagedata.h" #include "pagedata.h"
#include "filedata.h" #include "filedata.h"
#include "sqlitedbservice.h" #include "sqlitedbservice.h"
@ -11,16 +12,21 @@ class FileSaver
private: private:
SqliteDbService *dbService; SqliteDbService *dbService;
QStringList excludedPaths = Common::excludedPaths(); QStringList excludedPaths = Common::excludedPaths();
FileSaverOptions fileSaverOptions;
public: public:
FileSaver(SqliteDbService &dbService); FileSaver(SqliteDbService &dbService);
SaveFileResult addFile(QString path); SaveFileResult addFile(QString path);
SaveFileResult updateFile(QString path); SaveFileResult updateFile(QString path);
SaveFileResult saveFile(const QFileInfo &fileInfo); SaveFileResult saveFile(const QFileInfo &fileInfo);
int processFiles(const QVector<QString> paths, std::function<SaveFileResult(QString path)> saverFunc, int processFiles(const QVector<QString> paths, std::function<SaveFileResult(QString path)> saverFunc);
bool keepGoing, bool verbose); int addFiles(const QVector<QString> paths);
int addFiles(const QVector<QString> paths, bool keepGoing, bool verbose); int updateFiles(const QVector<QString> paths);
int updateFiles(const QVector<QString> paths, bool keepGoing, bool verbose);
void setFileSaverOptions(FileSaverOptions options)
{
this->fileSaverOptions = options;
}
}; };
#endif // FILESAVER_H #endif // FILESAVER_H

14
shared/filesaveroptions.h 普通文件
查看文件

@ -0,0 +1,14 @@
#ifndef FILESAVEROPTIONS_H
#define FILESAVEROPTIONS_H
class FileSaverOptions
{
public:
bool verbose = false;
bool keepGoing = false;
bool metadataOnly = false;
/* Whether those previously explicitly without content should be filled */
bool fillExistingContentless = false;
};
#endif // FILESAVEROPTIONS_H

查看文件

@ -12,6 +12,7 @@ FileScanWorker::FileScanWorker(SqliteDbService &db, ConcurrentQueue<QString> &qu
void FileScanWorker::run() void FileScanWorker::run()
{ {
FileSaver saver{*this->dbService}; FileSaver saver{*this->dbService};
saver.setFileSaverOptions(this->fileSaverOptions);
auto paths = queue->dequeue(batchsize); auto paths = queue->dequeue(batchsize);
for(QString &path : paths) for(QString &path : paths)
{ {
@ -20,11 +21,18 @@ void FileScanWorker::run()
{ {
sfr = saver.addFile(path); sfr = saver.addFile(path);
} }
catch(LooqsGeneralException &e)
{
Logger::error() << e.message << Qt::endl;
sfr = PROCESSFAIL;
}
catch(std::exception &e) catch(std::exception &e)
{ {
Logger::error() << e.what(); Logger::error() << e.what() << Qt::endl;
sfr = PROCESSFAIL; // well... sfr = PROCESSFAIL; // well...
} }
emit result({path, sfr}); emit result({path, sfr});
if(stopToken->load(std::memory_order_relaxed)) // TODO: relaxed should suffice here, but recheck if(stopToken->load(std::memory_order_relaxed)) // TODO: relaxed should suffice here, but recheck
{ {
@ -34,3 +42,8 @@ void FileScanWorker::run()
} }
emit finished(); emit finished();
} }
void FileScanWorker::setFileSaverOptions(FileSaverOptions options)
{
this->fileSaverOptions = options;
}

查看文件

@ -15,12 +15,14 @@ class FileScanWorker : public QObject, public QRunnable
protected: protected:
SqliteDbService *dbService; SqliteDbService *dbService;
ConcurrentQueue<QString> *queue; ConcurrentQueue<QString> *queue;
FileSaverOptions fileSaverOptions;
int batchsize; int batchsize;
std::atomic<bool> *stopToken; std::atomic<bool> *stopToken;
public: public:
FileScanWorker(SqliteDbService &db, ConcurrentQueue<QString> &queue, int batchsize, std::atomic<bool> &stopToken); FileScanWorker(SqliteDbService &db, ConcurrentQueue<QString> &queue, int batchsize, std::atomic<bool> &stopToken);
void run() override; void run() override;
void setFileSaverOptions(FileSaverOptions options);
signals: signals:
void result(FileScanResult); void result(FileScanResult);
void finished(); void finished();

查看文件

@ -73,16 +73,6 @@ void Indexer::setTargetPaths(QVector<QString> pathsToScan)
this->pathsToScan = pathsToScan; this->pathsToScan = pathsToScan;
} }
void Indexer::setVerbose(bool verbose)
{
this->verbose = verbose;
}
void Indexer::setKeepGoing(bool keepGoing)
{
this->keepGoing = keepGoing;
}
void Indexer::requestCancellation() void Indexer::requestCancellation()
{ {
this->dirScanner->cancel(); this->dirScanner->cancel();
@ -108,6 +98,7 @@ void Indexer::launchWorker(ConcurrentQueue<QString> &queue, int batchsize)
FileScanWorker *runnable = new FileScanWorker(*this->db, queue, batchsize, this->workerCancellationToken); FileScanWorker *runnable = new FileScanWorker(*this->db, queue, batchsize, this->workerCancellationToken);
connect(runnable, &FileScanWorker::result, this, &Indexer::processFileScanResult); connect(runnable, &FileScanWorker::result, this, &Indexer::processFileScanResult);
connect(runnable, &FileScanWorker::finished, this, &Indexer::processFinishedWorker); connect(runnable, &FileScanWorker::finished, this, &Indexer::processFinishedWorker);
runnable->setFileSaverOptions(this->fileSaverOptions);
++this->runningWorkers; ++this->runningWorkers;
QThreadPool::globalInstance()->start(runnable); QThreadPool::globalInstance()->start(runnable);
} }
@ -120,24 +111,6 @@ void Indexer::dirScanProgress(int current, int total)
void Indexer::processFileScanResult(FileScanResult result) void Indexer::processFileScanResult(FileScanResult result)
{ {
if(isErrorSaveFileResult(result.second))
{
this->currentIndexResult.results.append(result);
if(!keepGoing)
{
this->requestCancellation();
emit finished();
return;
}
}
else
{
if(verbose)
{
this->currentIndexResult.results.append(result);
}
}
/* TODO: OK_WASEMPTY might need a special list */ /* TODO: OK_WASEMPTY might need a special list */
if(result.second == OK || result.second == OK_WASEMPTY) if(result.second == OK || result.second == OK_WASEMPTY)
{ {
@ -152,12 +125,32 @@ void Indexer::processFileScanResult(FileScanResult result)
++this->currentIndexResult.erroredPaths; ++this->currentIndexResult.erroredPaths;
} }
if(currentScanProcessedCount++ == progressReportThreshold) if(isErrorSaveFileResult(result.second))
{
this->currentIndexResult.results.append(result);
if(!this->fileSaverOptions.keepGoing)
{
this->requestCancellation();
emit finished();
return;
}
}
else
{
if(this->fileSaverOptions.verbose)
{
this->currentIndexResult.results.append(result);
}
}
QTime currentTime = QTime::currentTime();
if(currentScanProcessedCount++ == progressReportThreshold || this->lastProgressReportTime.secsTo(currentTime) >= 10)
{ {
emit indexProgress(this->currentIndexResult.total(), this->currentIndexResult.addedPaths, emit indexProgress(this->currentIndexResult.total(), this->currentIndexResult.addedPaths,
this->currentIndexResult.skippedPaths, this->currentIndexResult.erroredPaths, this->currentIndexResult.skippedPaths, this->currentIndexResult.erroredPaths,
this->dirScanner->pathCount()); this->dirScanner->pathCount());
currentScanProcessedCount = 0; currentScanProcessedCount = 0;
this->lastProgressReportTime = currentTime;
} }
} }
@ -173,3 +166,13 @@ void Indexer::processFinishedWorker()
emit finished(); emit finished();
} }
} }
void Indexer::setFileSaverOptions(FileSaverOptions options)
{
this->fileSaverOptions = options;
}
void Indexer::setProgressReportThreshold(int threshold)
{
this->progressReportThreshold = threshold;
}

查看文件

@ -52,8 +52,7 @@ class Indexer : public QObject
{ {
Q_OBJECT Q_OBJECT
protected: protected:
bool verbose = false; FileSaverOptions fileSaverOptions;
bool keepGoing = true;
SqliteDbService *db; SqliteDbService *db;
int progressReportThreshold = 50; int progressReportThreshold = 50;
@ -72,14 +71,18 @@ class Indexer : public QObject
IndexResult currentIndexResult; IndexResult currentIndexResult;
void launchWorker(ConcurrentQueue<QString> &queue, int batchsize); void launchWorker(ConcurrentQueue<QString> &queue, int batchsize);
QTime lastProgressReportTime = QTime::currentTime();
public: public:
bool isRunning(); bool isRunning();
void beginIndexing(); void beginIndexing();
void setIgnorePattern(QStringList ignorePattern); void setIgnorePattern(QStringList ignorePattern);
void setTargetPaths(QVector<QString> pathsToScan); void setTargetPaths(QVector<QString> pathsToScan);
void setVerbose(bool verbose);
void setKeepGoing(bool keepGoing); void setFileSaverOptions(FileSaverOptions options);
void setProgressReportThreshold(int threshold);
void requestCancellation(); void requestCancellation();

查看文件

@ -7,21 +7,16 @@ IndexSyncer::IndexSyncer(SqliteDbService &dbService)
this->dbService = &dbService; this->dbService = &dbService;
} }
void IndexSyncer::setFileSaverOptions(FileSaverOptions options)
{
fileSaverOptions = options;
}
void IndexSyncer::setDryRun(bool dryRun) void IndexSyncer::setDryRun(bool dryRun)
{ {
this->dryRun = 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) void IndexSyncer::setRemoveDeletedFromIndex(bool removeDeletedFromIndex)
{ {
this->removeDeletedFromIndex = removeDeletedFromIndex; this->removeDeletedFromIndex = removeDeletedFromIndex;
@ -35,7 +30,7 @@ void IndexSyncer::setPattern(QString pattern)
void IndexSyncer::sync() void IndexSyncer::sync()
{ {
this->stopToken.store(false, std::memory_order_relaxed); this->stopToken.store(false, std::memory_order_relaxed);
FileSaver saver(*this->dbService);
QVector<FileData> files; QVector<FileData> files;
int offset = 0; int offset = 0;
int limit = 10000; int limit = 10000;
@ -87,7 +82,7 @@ void IndexSyncer::sync()
if(!this->dbService->deleteFile(fileData.absPath)) if(!this->dbService->deleteFile(fileData.absPath))
{ {
emit error("Error: Failed to delete " + fileData.absPath + " from the index"); emit error("Error: Failed to delete " + fileData.absPath + " from the index");
if(!this->keepGoing) if(!this->fileSaverOptions.keepGoing)
{ {
emit finished(totalUpdatesFilesCount, totalDeletedFilesCount, totalErroredFilesCount); emit finished(totalUpdatesFilesCount, totalDeletedFilesCount, totalErroredFilesCount);
return; return;
@ -104,13 +99,15 @@ void IndexSyncer::sync()
} }
} }
unsigned int updatedFilesCount = saver.updateFiles(filePathsToUpdate, keepGoing, verbose); FileSaver saver(*this->dbService);
saver.setFileSaverOptions(this->fileSaverOptions);
unsigned int updatedFilesCount = saver.updateFiles(filePathsToUpdate);
unsigned int shouldHaveUpdatedCount = static_cast<unsigned int>(filePathsToUpdate.size()); unsigned int shouldHaveUpdatedCount = static_cast<unsigned int>(filePathsToUpdate.size());
if(updatedFilesCount != shouldHaveUpdatedCount) if(updatedFilesCount != shouldHaveUpdatedCount)
{ {
totalErroredFilesCount += (shouldHaveUpdatedCount - updatedFilesCount); totalErroredFilesCount += (shouldHaveUpdatedCount - updatedFilesCount);
if(!keepGoing) if(!this->fileSaverOptions.keepGoing)
{ {
QString errorMsg = QString("Failed to update all files selected for updating in this batch. Updated") + QString errorMsg = QString("Failed to update all files selected for updating in this batch. Updated") +
updatedFilesCount + "out of" + shouldHaveUpdatedCount + "selected for updating"; updatedFilesCount + "out of" + shouldHaveUpdatedCount + "selected for updating";

查看文件

@ -1,16 +1,15 @@
#ifndef INDEXSYNCER_H #ifndef INDEXSYNCER_H
#define INDEXSYNCER_H #define INDEXSYNCER_H
#include "sqlitedbservice.h" #include "sqlitedbservice.h"
#include "filesaveroptions.h"
class IndexSyncer : public QObject class IndexSyncer : public QObject
{ {
Q_OBJECT Q_OBJECT
private: private:
SqliteDbService *dbService = nullptr; SqliteDbService *dbService = nullptr;
bool keepGoing = true; FileSaverOptions fileSaverOptions;
bool removeDeletedFromIndex = true; bool removeDeletedFromIndex = true;
bool dryRun = false; bool dryRun = false;
bool verbose = false;
QString pattern; QString pattern;
std::atomic<bool> stopToken{false}; std::atomic<bool> stopToken{false};
@ -18,12 +17,12 @@ class IndexSyncer : public QObject
public: public:
IndexSyncer(SqliteDbService &dbService); IndexSyncer(SqliteDbService &dbService);
void setFileSaverOptions(FileSaverOptions options);
public slots: public slots:
void sync(); void sync();
void cancel(); void cancel();
void setDryRun(bool dryRun); void setDryRun(bool dryRun);
void setVerbose(bool verbose);
void setKeepGoing(bool keepGoing);
void setRemoveDeletedFromIndex(bool removeDeletedFromIndex); void setRemoveDeletedFromIndex(bool removeDeletedFromIndex);
void setPattern(QString pattern); void setPattern(QString pattern);

48
shared/limitqueue.h 普通文件
查看文件

@ -0,0 +1,48 @@
#ifndef LIMITQUEUE_H
#define LIMITQUEUE_H
#include <QQueue>
template <class T> class LimitQueue
{
protected:
QQueue<T> queue;
int limit = 0;
public:
LimitQueue();
LimitQueue(int limit)
{
this->limit = limit;
}
void enqueue(const T &t)
{
if(queue.size() == limit)
{
queue.dequeue();
}
queue.enqueue(t);
}
int size()
{
return queue.size();
}
T dequeue()
{
return queue.dequeue();
}
void setLimit(int limit)
{
this->limit = limit;
}
void clear()
{
queue.clear();
}
};
#endif // LIMITQUEUE_H

查看文件

@ -7,6 +7,7 @@
#include <optional> #include <optional>
#include <algorithm> #include <algorithm>
#include "looqsquery.h" #include "looqsquery.h"
#include "looqsgeneralexception.h"
const QVector<Token> &LooqsQuery::getTokens() const const QVector<Token> &LooqsQuery::getTokens() const
{ {
@ -28,6 +29,11 @@ bool LooqsQuery::hasContentSearch() const
return (this->getTokensMask() & FILTER_CONTENT) == FILTER_CONTENT; return (this->getTokensMask() & FILTER_CONTENT) == FILTER_CONTENT;
} }
bool LooqsQuery::hasOutlineSearch() const
{
return (this->getTokensMask() & FILTER_OUTLINE_CONTAINS) == FILTER_OUTLINE_CONTAINS;
}
bool LooqsQuery::hasPathSearch() const bool LooqsQuery::hasPathSearch() const
{ {
return (this->getTokensMask() & FILTER_PATH) == FILTER_PATH; return (this->getTokensMask() & FILTER_PATH) == FILTER_PATH;
@ -180,9 +186,9 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
QStringList loneWords; QStringList loneWords;
LooqsQuery result; LooqsQuery result;
QRegularExpression rx( static QRegularExpression rx(
"((?<filtername>(\\.|\\w)+):(?<args>\\((?<innerargs>[^\\)]+)\\)|([\\p{L}\\p{N},])+)|(?<boolean>AND|OR)" "((?<filtername>(\\.|\\w)+):(?<args>\\((?<innerargs>[^\\)]+)\\)|([^\\s])+)|(?<boolean>AND|OR)"
"|(?<negation>!)|(?<bracket>\\(|\\))|(?<loneword>[\"\\p{L}\\p{N}]+))"); "|(?<negation>!)|(?<bracket>\\(|\\))|(?<loneword>[^\\s]+))");
QRegularExpressionMatchIterator i = rx.globalMatch(expression); QRegularExpressionMatchIterator i = rx.globalMatch(expression);
auto previousWasBool = [&result] { return !result.tokens.empty() && ((result.tokens.last().type & BOOL) == BOOL); }; 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); }; auto previousWas = [&result](TokenType t) { return !result.tokens.empty() && (result.tokens.last().type == t); };
@ -284,6 +290,14 @@ LooqsQuery LooqsQuery::build(QString expression, TokenType loneWordsTokenType, b
{ {
tokenType = FILTER_CONTENT_PAGE; tokenType = FILTER_CONTENT_PAGE;
} }
else if(filtername == "t" || filtername == "tag")
{
tokenType = FILTER_TAG_ASSIGNED;
}
else if(filtername == "toc" || filtername == "outline")
{
tokenType = FILTER_OUTLINE_CONTAINS;
}
// 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") else if(filtername == "sort")
{ {

查看文件

@ -2,7 +2,6 @@
#define LOOQSQUERY_H #define LOOQSQUERY_H
#include <QString> #include <QString>
#include <QVector> #include <QVector>
#include "looqsgeneralexception.h"
#include "token.h" #include "token.h"
/* Fields that can be queried or sorted */ /* Fields that can be queried or sorted */
enum QueryField enum QueryField
@ -46,7 +45,7 @@ class LooqsQuery
void addToken(Token t); void addToken(Token t);
void updateTokensMask() void updateTokensMask()
{ {
for(const Token &t : tokens) for(const Token &t : qAsConst(tokens))
{ {
this->tokensMask |= t.type; this->tokensMask |= t.type;
} }
@ -69,6 +68,7 @@ class LooqsQuery
this->limit = limit; this->limit = limit;
} }
bool hasContentSearch() const; bool hasContentSearch() const;
bool hasOutlineSearch() const;
bool hasPathSearch() const; bool hasPathSearch() const;
void addSortCondition(SortCondition sc); void addSortCondition(SortCondition sc);
@ -92,14 +92,6 @@ class LooqsQuery
this->sortConditions = sortConditions; this->sortConditions = sortConditions;
updateTokensMask(); updateTokensMask();
} }
LooqsQuery(const LooqsQuery &o)
{
this->tokens = o.tokens;
this->sortConditions = o.sortConditions;
this->tokensMask = o.tokensMask;
this->limit = o.limit;
}
}; };
#endif // LOOQSQUERY_H #endif // LOOQSQUERY_H

1
shared/migrations/3.sql 普通文件
查看文件

@ -0,0 +1 @@
DROP trigger content_ad;

3
shared/migrations/4.sql 普通文件
查看文件

@ -0,0 +1,3 @@
CREATE VIRTUAL TABLE fts_trigram USING fts5(content, content='',tokenize="trigram");
ALTER TABLE content ADD COLUMN fts_trigramid integer;
CREATE INDEX content_fts_trigramid ON content (fts_trigramid);

6
shared/migrations/5.sql 普通文件
查看文件

@ -0,0 +1,6 @@
CREATE TABLE tag(id integer PRIMARY KEY, name varchar(128) UNIQUE);
CREATE TABLE filetag(fileid integer, tagid integer);
CREATE INDEX filetag_fileid ON filetag(fileid);
CREATE INDEX tag_id ON tag(id);
CREATE INDEX file_path ON file ( path );
UPDATE file SET filetype='c' WHERE filetype='f';

2
shared/migrations/6.sql 普通文件
查看文件

@ -0,0 +1,2 @@
CREATE TABLE outline(id INTEGER PRIMARY KEY, fileid INTEGER REFERENCES file (id) ON DELETE CASCADE, text varchar(1024), page integer);
CREATE INDEX outline_fileid ON outline (fileid);

查看文件

@ -2,5 +2,9 @@
<qresource prefix="/looqs-migrations"> <qresource prefix="/looqs-migrations">
<file>1.sql</file> <file>1.sql</file>
<file>2.sql</file> <file>2.sql</file>
<file>3.sql</file>
<file>4.sql</file>
<file>5.sql</file>
<file>6.sql</file>
</qresource> </qresource>
</RCC> </RCC>

查看文件

@ -10,7 +10,7 @@ class NothingProcessor : public Processor
NothingProcessor(); NothingProcessor();
public: public:
QVector<PageData> process(const QByteArray &data) const override DocumentProcessResult process(const QByteArray & /*data*/) const override
{ {
return {}; return {};
} }

查看文件

@ -3,12 +3,12 @@
#include "odtprocessor.h" #include "odtprocessor.h"
#include "tagstripperprocessor.h" #include "tagstripperprocessor.h"
QVector<PageData> OdtProcessor::process(const QByteArray &data) const DocumentProcessResult OdtProcessor::process(const QByteArray & /*data*/) const
{ {
throw LooqsGeneralException("Not implemented yet"); throw LooqsGeneralException("Not implemented yet");
} }
QVector<PageData> OdtProcessor::process(QString path) const DocumentProcessResult OdtProcessor::process(QString path) const
{ {
QuaZipFile zipFile(path); QuaZipFile zipFile(path);
zipFile.setFileName("content.xml"); zipFile.setFileName("content.xml");

查看文件

@ -8,9 +8,9 @@ class OdtProcessor : public Processor
{ {
this->PREFERED_DATA_SOURCE = FILEPATH; this->PREFERED_DATA_SOURCE = FILEPATH;
} }
QVector<PageData> process(const QByteArray &data) const override; DocumentProcessResult process(const QByteArray &data) const override;
QVector<PageData> process(QString path) const override; DocumentProcessResult process(QString path) const override;
}; };
#endif // ODTPROCESSOR_H #endif // ODTPROCESSOR_H

查看文件

@ -1,5 +1,3 @@
#include "paralleldirscanner.h"
#include <QRunnable> #include <QRunnable>
#include <QMutex> #include <QMutex>
#include <QDirIterator> #include <QDirIterator>
@ -7,7 +5,7 @@
#include <QThreadPool> #include <QThreadPool>
#include <functional> #include <functional>
#include "dirscanworker.h" #include "dirscanworker.h"
#include "logger.h" #include "paralleldirscanner.h"
ParallelDirScanner::ParallelDirScanner() ParallelDirScanner::ParallelDirScanner()
{ {

查看文件

@ -5,9 +5,30 @@ PdfProcessor::PdfProcessor()
{ {
} }
QVector<PageData> PdfProcessor::process(const QByteArray &data) const QVector<DocumentOutlineEntry> PdfProcessor::createOutline(const QVector<Poppler::OutlineItem> &outlineItems) const
{ {
QVector<PageData> result; QVector<DocumentOutlineEntry> result;
for(const Poppler::OutlineItem &outlineItem : outlineItems)
{
DocumentOutlineEntry documentOutlineEntry;
documentOutlineEntry.text = outlineItem.name();
documentOutlineEntry.type = OUTLINE_DESTINATION_TYPE_PAGE;
if(!outlineItem.destination().isNull())
{
documentOutlineEntry.destinationPage = outlineItem.destination()->pageNumber();
}
if(outlineItem.hasChildren())
{
documentOutlineEntry.children = createOutline(outlineItem.children());
}
result.append(documentOutlineEntry);
}
return result;
}
DocumentProcessResult PdfProcessor::process(const QByteArray &data) const
{
DocumentProcessResult result;
QScopedPointer<Poppler::Document> doc(Poppler::Document::loadFromData(data)); QScopedPointer<Poppler::Document> doc(Poppler::Document::loadFromData(data));
if(doc.isNull()) if(doc.isNull())
{ {
@ -26,12 +47,13 @@ QVector<PageData> PdfProcessor::process(const QByteArray &data) const
for(auto i = 0; i < pagecount; i++) for(auto i = 0; i < pagecount; i++)
{ {
QString text = doc->page(i)->text(entirePage); QString text = doc->page(i)->text(entirePage);
result.append({static_cast<unsigned int>(i + 1), text}); result.pages.append({static_cast<unsigned int>(i + 1), text});
/*TODO: hack, so we can fts search several words over the whole document, not just pages. /*TODO: hack, so we can fts search several words over the whole document, not just pages.
* this of course uses more space and should be solved differently. * this of course uses more space and should be solved differently.
*/ */
entire += text; entire += text;
} }
result.append({0, entire}); result.pages.append({0, entire});
result.outlines = createOutline(doc->outline());
return result; return result;
} }

查看文件

@ -1,5 +1,6 @@
#ifndef PDFPROCESSOR_H #ifndef PDFPROCESSOR_H
#define PDFPROCESSOR_H #define PDFPROCESSOR_H
#include <poppler-qt5.h>
#include "processor.h" #include "processor.h"
class PdfProcessor : public Processor class PdfProcessor : public Processor
{ {
@ -7,7 +8,8 @@ class PdfProcessor : public Processor
PdfProcessor(); PdfProcessor();
public: public:
QVector<PageData> process(const QByteArray &data) const override; QVector<DocumentOutlineEntry> createOutline(const QVector<Poppler::OutlineItem> &outlineItems) const;
DocumentProcessResult process(const QByteArray &data) const override;
}; };
#endif // PDFPROCESSOR_H #endif // PDFPROCESSOR_H

查看文件

@ -2,8 +2,8 @@
#define PROCESSOR_H #define PROCESSOR_H
#include <QVector> #include <QVector>
#include <QFile> #include <QFile>
#include "pagedata.h"
#include "utils.h" #include "utils.h"
#include "documentprocessresult.h"
enum DataSource enum DataSource
{ {
FILEPATH, FILEPATH,
@ -18,8 +18,8 @@ class Processor
* a single file */ * a single file */
DataSource PREFERED_DATA_SOURCE = ARRAY; DataSource PREFERED_DATA_SOURCE = ARRAY;
Processor(); Processor();
virtual QVector<PageData> process(const QByteArray &data) const = 0; virtual DocumentProcessResult process(const QByteArray &data) const = 0;
virtual QVector<PageData> process(QString path) const virtual DocumentProcessResult process(QString path) const
{ {
return process(Utils::readFile(path)); return process(Utils::readFile(path));
} }

查看文件

@ -65,18 +65,12 @@ void SandboxedProcessor::enableSandbox(QString readablePath)
exile_free_policy(policy); exile_free_policy(policy);
} }
void SandboxedProcessor::printResults(const QVector<PageData> &pageData) void SandboxedProcessor::printResults(const DocumentProcessResult &result)
{ {
QFile fsstdout; QFile fsstdout;
fsstdout.open(stdout, QIODevice::WriteOnly); fsstdout.open(stdout, QIODevice::WriteOnly);
QDataStream stream(&fsstdout); QDataStream stream(&fsstdout);
stream << result;
for(const PageData &data : pageData)
{
stream << data;
// fsstdout.flush();
}
fsstdout.close(); fsstdout.close();
} }
@ -102,7 +96,7 @@ SaveFileResult SandboxedProcessor::process()
return OK; return OK;
} }
QVector<PageData> pageData; DocumentProcessResult processResult;
QString absPath = fileInfo.absoluteFilePath(); QString absPath = fileInfo.absoluteFilePath();
try try
@ -111,13 +105,13 @@ SaveFileResult SandboxedProcessor::process()
{ {
/* Read access to FS needed... doh..*/ /* Read access to FS needed... doh..*/
enableSandbox(absPath); enableSandbox(absPath);
pageData = processor->process(absPath); processResult = processor->process(absPath);
} }
else else
{ {
QByteArray data = Utils::readFile(absPath); QByteArray data = Utils::readFile(absPath);
enableSandbox(); enableSandbox();
pageData = processor->process(data); processResult = processor->process(data);
} }
} }
catch(LooqsGeneralException &e) catch(LooqsGeneralException &e)
@ -126,6 +120,6 @@ SaveFileResult SandboxedProcessor::process()
return PROCESSFAIL; return PROCESSFAIL;
} }
printResults(pageData); printResults(processResult);
return pageData.isEmpty() ? OK_WASEMPTY : OK; return processResult.pages.isEmpty() ? OK_WASEMPTY : OK;
} }

查看文件

@ -2,7 +2,7 @@
#define SANDBOXEDPROCESSOR_H #define SANDBOXEDPROCESSOR_H
#include <QString> #include <QString>
#include <QMimeDatabase> #include <QMimeDatabase>
#include "pagedata.h" #include "documentprocessresult.h"
#include "savefileresult.h" #include "savefileresult.h"
class SandboxedProcessor class SandboxedProcessor
@ -12,7 +12,7 @@ class SandboxedProcessor
QMimeDatabase mimeDatabase; QMimeDatabase mimeDatabase;
void enableSandbox(QString readablePath = ""); void enableSandbox(QString readablePath = "");
void printResults(const QVector<PageData> &pageData); void printResults(const DocumentProcessResult &pageData);
public: public:
SandboxedProcessor(QString filepath) SandboxedProcessor(QString filepath)

查看文件

@ -6,7 +6,7 @@ class SearchResult
{ {
public: public:
FileData fileData; FileData fileData;
QVector<unsigned int> pages; unsigned int page;
bool wasContentSearch = false; bool wasContentSearch = false;
}; };

查看文件

@ -42,6 +42,8 @@ SOURCES += sqlitesearch.cpp \
dbmigrator.cpp \ dbmigrator.cpp \
defaulttextprocessor.cpp \ defaulttextprocessor.cpp \
dirscanworker.cpp \ dirscanworker.cpp \
documentoutlineentry.cpp \
documentprocessresult.cpp \
encodingdetector.cpp \ encodingdetector.cpp \
filesaver.cpp \ filesaver.cpp \
filescanworker.cpp \ filescanworker.cpp \
@ -60,6 +62,7 @@ SOURCES += sqlitesearch.cpp \
processor.cpp \ processor.cpp \
sandboxedprocessor.cpp \ sandboxedprocessor.cpp \
sqlitedbservice.cpp \ sqlitedbservice.cpp \
tagmanager.cpp \
tagstripperprocessor.cpp \ tagstripperprocessor.cpp \
utils.cpp \ utils.cpp \
../submodules/exile.h/exile.c \ ../submodules/exile.h/exile.c \
@ -71,12 +74,16 @@ HEADERS += sqlitesearch.h \
dbmigrator.h \ dbmigrator.h \
defaulttextprocessor.h \ defaulttextprocessor.h \
dirscanworker.h \ dirscanworker.h \
documentoutlineentry.h \
documentprocessresult.h \
encodingdetector.h \ encodingdetector.h \
filedata.h \ filedata.h \
filesaver.h \ filesaver.h \
filesaveroptions.h \
filescanworker.h \ filescanworker.h \
indexer.h \ indexer.h \
indexsyncer.h \ indexsyncer.h \
limitqueue.h \
logger.h \ logger.h \
looqsgeneralexception.h \ looqsgeneralexception.h \
looqsquery.h \ looqsquery.h \
@ -91,6 +98,7 @@ HEADERS += sqlitesearch.h \
savefileresult.h \ savefileresult.h \
searchresult.h \ searchresult.h \
sqlitedbservice.h \ sqlitedbservice.h \
tagmanager.h \
tagstripperprocessor.h \ tagstripperprocessor.h \
token.h \ token.h \
common.h \ common.h \

查看文件

@ -2,25 +2,10 @@
#include <QFileInfo> #include <QFileInfo>
#include <QDateTime> #include <QDateTime>
#include <QSqlError> #include <QSqlError>
#include "looqsgeneralexception.h"
#include "sqlitedbservice.h" #include "sqlitedbservice.h"
#include "filedata.h" #include "filedata.h"
#include "logger.h" #include "logger.h"
bool SqliteDbService::fileExistsInDatabase(QString path, qint64 mtime)
{
auto query = QSqlQuery(dbFactory->forCurrentThread());
query.prepare("SELECT 1 FROM file WHERE path = ? and mtime = ?");
query.addBindValue(path);
query.addBindValue(mtime);
if(!query.exec())
{
throw LooqsGeneralException("Error while trying to query for file existance: " + query.lastError().text());
}
if(!query.next())
{
return false;
}
return query.value(0).toBool();
}
QVector<SearchResult> SqliteDbService::search(const LooqsQuery &query) QVector<SearchResult> SqliteDbService::search(const LooqsQuery &query)
{ {
@ -29,20 +14,29 @@ QVector<SearchResult> SqliteDbService::search(const LooqsQuery &query)
return searcher.search(query); return searcher.search(query);
} }
bool SqliteDbService::fileExistsInDatabase(QString path) std::optional<QChar> SqliteDbService::queryFileType(QString absPath)
{ {
auto query = QSqlQuery(dbFactory->forCurrentThread()); auto query = exec("SELECT filetype FROM file WHERE path = ?", {absPath});
query.prepare("SELECT 1 FROM file WHERE path = ?");
query.addBindValue(path);
if(!query.exec())
{
throw LooqsGeneralException("Error while trying to query for file existance: " + query.lastError().text());
}
if(!query.next()) if(!query.next())
{ {
return false; return {};
} }
return query.value(0).toBool(); return query.value(0).toChar();
}
bool SqliteDbService::fileExistsInDatabase(QString path)
{
return execBool("SELECT 1 FROM file WHERE path = ?", {path});
}
bool SqliteDbService::fileExistsInDatabase(QString path, qint64 mtime)
{
return execBool("SELECT 1 FROM file WHERE path = ? AND mtime = ?", {path, mtime});
}
bool SqliteDbService::fileExistsInDatabase(QString path, qint64 mtime, QChar fileType)
{
return execBool("SELECT 1 FROM file WHERE path = ? AND mtime = ? AND filetype = ?", {path, mtime, fileType});
} }
SqliteDbService::SqliteDbService(DatabaseFactory &dbFactory) SqliteDbService::SqliteDbService(DatabaseFactory &dbFactory)
@ -110,11 +104,212 @@ unsigned int SqliteDbService::getFiles(QVector<FileData> &results, QString wildC
return processedRows; return processedRows;
} }
SaveFileResult SqliteDbService::saveFile(QFileInfo fileInfo, QVector<PageData> &pageData) QVector<QString> SqliteDbService::getTags()
{
QVector<QString> result;
auto query = QSqlQuery(dbFactory->forCurrentThread());
query.prepare("SELECT name FROM tag ORDER by name ASC");
query.setForwardOnly(true);
if(!query.exec())
{
throw LooqsGeneralException("Error while trying to retrieve tags from database: " + query.lastError().text());
}
while(query.next())
{
QString tagname = query.value(0).toString();
result.append(tagname);
}
return result;
}
QVector<QString> SqliteDbService::getTagsForPath(QString path)
{
QVector<QString> result;
auto query = QSqlQuery(dbFactory->forCurrentThread());
query.prepare("SELECT name FROM tag INNER JOIN filetag ON tag.id = filetag.tagid INNER JOIN file ON filetag.fileid "
"= file.id WHERE file.path = ? ORDER BY name ASC");
query.addBindValue(path);
query.setForwardOnly(true);
if(!query.exec())
{
throw LooqsGeneralException("Error while trying to retrieve tags from database: " + query.lastError().text());
}
while(query.next())
{
QString tagname = query.value(0).toString();
result.append(tagname);
}
return result;
}
QVector<QString> SqliteDbService::getPathsForTag(QString tag)
{
QVector<QString> result;
auto query = QSqlQuery(dbFactory->forCurrentThread());
query.prepare(
"SELECT file.path FROM tag INNER JOIN filetag ON tag.id = filetag.tagid INNER JOIN file ON filetag.fileid "
"= file.id WHERE tag.name = ?");
query.addBindValue(tag.toLower());
query.setForwardOnly(true);
if(!query.exec())
{
throw LooqsGeneralException("Error while trying to retrieve paths from database: " + query.lastError().text());
}
while(query.next())
{
QString path = query.value(0).toString();
result.append(path);
}
return result;
}
bool SqliteDbService::setTags(QString path, const QSet<QString> &tags)
{
QSqlDatabase db = dbFactory->forCurrentThread();
if(!db.transaction())
{
Logger::error() << "Failed to open transaction for " << path << " : " << db.lastError() << Qt::endl;
return false;
}
QSqlQuery deletionQuery = QSqlQuery(db);
deletionQuery.prepare("DELETE FROM filetag WHERE fileid = (SELECT id FROM file WHERE path = ?)");
deletionQuery.addBindValue(path);
if(!deletionQuery.exec())
{
db.rollback();
Logger::error() << "Failed to delete existing tags " << deletionQuery.lastError() << Qt::endl;
return false;
}
for(const QString &tag : tags)
{
QSqlQuery tagQuery = QSqlQuery(db);
tagQuery.prepare("INSERT OR IGNORE INTO tag (name) VALUES(?)");
tagQuery.addBindValue(tag.toLower());
if(!tagQuery.exec())
{
db.rollback();
Logger::error() << "Failed to insert tag " << tagQuery.lastError() << Qt::endl;
return false;
}
QSqlQuery fileTagQuery(db);
fileTagQuery.prepare(
"INSERT INTO filetag(fileid, tagid) VALUES((SELECT id FROM file WHERE path = ?), (SELECT id "
"FROM tag WHERE name = ?))");
fileTagQuery.bindValue(0, path);
fileTagQuery.bindValue(1, tag);
if(!fileTagQuery.exec())
{
db.rollback();
Logger::error() << "Failed to assign tag to file" << Qt::endl;
return false;
}
}
if(!db.commit())
{
db.rollback();
Logger::error() << "Failed to commit transaction when saving tags" << Qt::endl;
return false;
}
return true;
}
bool SqliteDbService::insertToFTS(bool useTrigrams, QSqlDatabase &db, int fileid, QVector<PageData> &pageData)
{
QString ftsInsertStatement;
QString contentInsertStatement;
if(useTrigrams)
{
ftsInsertStatement = "INSERT INTO fts_trigram(content) VALUES(?)";
contentInsertStatement = "INSERT INTO content(fileid, page, fts_trigramid) VALUES(?, ?, last_insert_rowid())";
}
else
{
ftsInsertStatement = "INSERT INTO fts(content) VALUES(?)";
contentInsertStatement = "INSERT INTO content(fileid, page, ftsid) VALUES(?, ?, last_insert_rowid())";
}
for(const PageData &data : pageData)
{
QSqlQuery ftsQuery(db);
ftsQuery.prepare(ftsInsertStatement);
ftsQuery.addBindValue(data.content);
if(!ftsQuery.exec())
{
Logger::error() << "Failed fts insertion " << ftsQuery.lastError() << Qt::endl;
return false;
}
QSqlQuery contentQuery(db);
contentQuery.prepare(contentInsertStatement);
contentQuery.addBindValue(fileid);
contentQuery.addBindValue(data.pagenumber);
if(!contentQuery.exec())
{
Logger::error() << "Failed content insertion " << contentQuery.lastError() << Qt::endl;
return false;
}
}
return true;
}
bool SqliteDbService::insertOutline(QSqlDatabase &db, int fileid, const QVector<DocumentOutlineEntry> &outlines)
{
QSqlQuery outlineQuery(db);
outlineQuery.prepare("INSERT INTO outline(fileid, text, page) VALUES(?,?,?)");
outlineQuery.addBindValue(fileid);
for(const DocumentOutlineEntry &outline : outlines)
{
outlineQuery.bindValue(1, outline.text.toLower());
outlineQuery.bindValue(2, outline.destinationPage);
if(!outlineQuery.exec())
{
Logger::error() << "Failed outline insertion " << outlineQuery.lastError() << Qt::endl;
return false;
}
if(!insertOutline(db, fileid, outline.children))
{
Logger::error() << "Failed outline insertion (children)) " << outlineQuery.lastError() << Qt::endl;
return false;
}
}
return true;
}
QSqlQuery SqliteDbService::exec(QString querystr, std::initializer_list<QVariant> args)
{
auto query = QSqlQuery(dbFactory->forCurrentThread());
query.prepare(querystr);
for(const QVariant &v : args)
{
query.addBindValue(v);
}
if(!query.exec())
{
throw LooqsGeneralException("Error while exec(): " + query.lastError().text() + " for query: " + querystr);
}
return query;
}
bool SqliteDbService::execBool(QString querystr, std::initializer_list<QVariant> args)
{
auto query = exec(querystr, args);
if(!query.next())
{
return false;
}
return query.value(0).toBool();
}
SaveFileResult SqliteDbService::saveFile(QFileInfo fileInfo, DocumentProcessResult &processResult, bool pathsOnly)
{ {
QString absPath = fileInfo.absoluteFilePath(); QString absPath = fileInfo.absoluteFilePath();
auto mtime = fileInfo.lastModified().toSecsSinceEpoch(); auto mtime = fileInfo.lastModified().toSecsSinceEpoch();
QChar fileType = fileInfo.isDir() ? 'd' : 'f'; QChar fileType = fileInfo.isDir() ? 'd' : 'c';
if(pathsOnly)
{
fileType = 'f';
}
QSqlDatabase db = dbFactory->forCurrentThread(); QSqlDatabase db = dbFactory->forCurrentThread();
QSqlQuery delQuery(db); QSqlQuery delQuery(db);
@ -148,21 +343,25 @@ SaveFileResult SqliteDbService::saveFile(QFileInfo fileInfo, QVector<PageData> &
return DBFAIL; return DBFAIL;
} }
int lastid = inserterQuery.lastInsertId().toInt(); if(!pathsOnly)
for(const PageData &data : pageData)
{ {
QSqlQuery ftsQuery(db); int lastid = inserterQuery.lastInsertId().toInt();
ftsQuery.prepare("INSERT INTO fts(content) VALUES(?)"); if(!insertToFTS(false, db, lastid, processResult.pages))
ftsQuery.addBindValue(data.content);
ftsQuery.exec();
QSqlQuery contentQuery(db);
contentQuery.prepare("INSERT INTO content(fileid, page, ftsid) VALUES(?, ?, last_insert_rowid())");
contentQuery.addBindValue(lastid);
contentQuery.addBindValue(data.pagenumber);
if(!contentQuery.exec())
{ {
db.rollback(); db.rollback();
Logger::error() << "Failed content insertion " << contentQuery.lastError() << Qt::endl; Logger::error() << "Failed to insert data to FTS index " << Qt::endl;
return DBFAIL;
}
if(!insertToFTS(true, db, lastid, processResult.pages))
{
db.rollback();
Logger::error() << "Failed to insert data to FTS index " << Qt::endl;
return DBFAIL;
}
if(!insertOutline(db, lastid, processResult.outlines))
{
db.rollback();
Logger::error() << "Failed to insert outline data " << Qt::endl;
return DBFAIL; return DBFAIL;
} }
} }
@ -175,3 +374,123 @@ SaveFileResult SqliteDbService::saveFile(QFileInfo fileInfo, QVector<PageData> &
} }
return OK; return OK;
} }
bool SqliteDbService::addTag(QString tag, QString path)
{
QVector<QString> paths;
paths.append(path);
return addTag(tag, paths);
}
bool SqliteDbService::addTag(QString tag, const QVector<QString> &paths)
{
QSqlDatabase db = dbFactory->forCurrentThread();
QSqlQuery tagQuery(db);
QSqlQuery fileTagQuery(db);
tag = tag.toLower();
tagQuery.prepare("INSERT OR IGNORE INTO tag (name) VALUES(?)");
tagQuery.addBindValue(tag);
fileTagQuery.prepare("INSERT INTO filetag(fileid, tagid) VALUES((SELECT id FROM file WHERE path = ?), (SELECT id "
"FROM tag WHERE name = ?))");
fileTagQuery.bindValue(1, tag);
if(!db.transaction())
{
Logger::error() << "Failed to open transaction to add paths for tag " << tag << " : " << db.lastError()
<< Qt::endl;
return false;
}
if(!tagQuery.exec())
{
db.rollback();
Logger::error() << "Failed INSERT query" << tagQuery.lastError() << Qt::endl;
return false;
}
for(const QString &path : paths)
{
fileTagQuery.bindValue(0, path);
if(!fileTagQuery.exec())
{
db.rollback();
Logger::error() << "Failed to add paths to tag" << Qt::endl;
return false;
}
}
if(!db.commit())
{
db.rollback();
Logger::error() << "Failed to commit tag insertion transaction" << db.lastError() << Qt::endl;
return false;
}
return true;
}
bool SqliteDbService::removePathsForTag(QString tag, const QVector<QString> &paths)
{
QSqlDatabase db = dbFactory->forCurrentThread();
QSqlQuery tagQuery(db);
QSqlQuery fileTagQuery(db);
tag = tag.toLower();
fileTagQuery.prepare(
"DELETE FROM filetag WHERE fileid = (SELECT id FROM file WHERE path = ?) AND tagid = (SELECT id "
"FROM tag WHERE name = ?)");
fileTagQuery.bindValue(1, tag);
for(const QString &path : paths)
{
fileTagQuery.bindValue(0, path);
if(!fileTagQuery.exec())
{
Logger::error() << "An error occured while trying to remove paths from tag assignment" << Qt::endl;
return false;
}
}
return true;
}
bool SqliteDbService::deleteTag(QString tag)
{
QSqlDatabase db = dbFactory->forCurrentThread();
if(!db.transaction())
{
Logger::error() << "Failed to open transaction while trying to delete tag " << tag << " : " << db.lastError()
<< Qt::endl;
return false;
}
tag = tag.toLower();
QSqlQuery assignmentDeleteQuery(db);
assignmentDeleteQuery.prepare("DELETE FROM filetag WHERE tagid = (SELECT id FROM tag WHERE name = ?)");
assignmentDeleteQuery.addBindValue(tag);
if(!assignmentDeleteQuery.exec())
{
db.rollback();
Logger::error() << "Error while trying to delete tag: " << db.lastError() << Qt::endl;
return false;
}
QSqlQuery deleteTagQuery(db);
deleteTagQuery.prepare("DELETE FROM tag WHERE name = ?");
deleteTagQuery.addBindValue(tag);
if(!deleteTagQuery.exec())
{
db.rollback();
Logger::error() << "Error while trying to delete tag: " << db.lastError() << Qt::endl;
return false;
}
if(!db.commit())
{
db.rollback();
Logger::error() << "Error while trying to delete tag: " << db.lastError() << Qt::endl;
return false;
}
return true;
}

查看文件

@ -1,9 +1,11 @@
#ifndef SQLITEDBSERVICE_H #ifndef SQLITEDBSERVICE_H
#define SQLITEDBSERVICE_H #define SQLITEDBSERVICE_H
#include <QFileInfo> #include <QFileInfo>
#include <optional>
#include "databasefactory.h" #include "databasefactory.h"
#include "utils.h" #include "utils.h"
#include "pagedata.h" #include "documentprocessresult.h"
#include "filedata.h" #include "filedata.h"
#include "../shared/sqlitesearch.h" #include "../shared/sqlitesearch.h"
#include "../shared/token.h" #include "../shared/token.h"
@ -13,15 +15,34 @@ class SqliteDbService
{ {
private: private:
DatabaseFactory *dbFactory = nullptr; DatabaseFactory *dbFactory = nullptr;
bool insertToFTS(bool useTrigrams, QSqlDatabase &db, int fileid, QVector<PageData> &pageData);
QSqlQuery exec(QString query, std::initializer_list<QVariant> args);
bool execBool(QString querystr, std::initializer_list<QVariant> args);
public: public:
SqliteDbService(DatabaseFactory &dbFactory); SqliteDbService(DatabaseFactory &dbFactory);
SaveFileResult saveFile(QFileInfo fileInfo, QVector<PageData> &pageData); SaveFileResult saveFile(QFileInfo fileInfo, DocumentProcessResult &pageData, bool pathsOnly);
unsigned int getFiles(QVector<FileData> &results, QString wildCardPattern, int offset, int limit);
bool deleteFile(QString path); bool deleteFile(QString path);
bool fileExistsInDatabase(QString path); bool fileExistsInDatabase(QString path);
bool fileExistsInDatabase(QString path, qint64 mtime); bool fileExistsInDatabase(QString path, qint64 mtime);
bool fileExistsInDatabase(QString path, qint64 mtime, QChar filetype);
unsigned int getFiles(QVector<FileData> &results, QString wildCardPattern, int offset, int limit);
bool addTag(QString tag, QString path);
bool addTag(QString tag, const QVector<QString> &paths);
QVector<QString> getTags();
QVector<QString> getTagsForPath(QString path);
QVector<QString> getPathsForTag(QString path);
bool setTags(QString path, const QSet<QString> &tags);
bool removePathsForTag(QString tag, const QVector<QString> &paths);
bool deleteTag(QString tag);
QVector<SearchResult> search(const LooqsQuery &query); QVector<SearchResult> search(const LooqsQuery &query);
std::optional<QChar> queryFileType(QString absPath);
bool insertOutline(QSqlDatabase &db, int fileid, const QVector<DocumentOutlineEntry> &outlines);
}; };
#endif // SQLITEDBSERVICE_H #endif // SQLITEDBSERVICE_H

查看文件

@ -69,7 +69,7 @@ QString SqliteSearch::createSortSql(const QVector<SortCondition> sortConditions)
QString SqliteSearch::escapeFtsArgument(QString ftsArg) QString SqliteSearch::escapeFtsArgument(QString ftsArg)
{ {
QString result; QString result;
QRegularExpression extractor(R"#("([^"]*)"|([^\s]+))#"); static QRegularExpression extractor(R"#("([^"]*)"|([^\s]+))#");
QRegularExpressionMatchIterator i = extractor.globalMatch(ftsArg); QRegularExpressionMatchIterator i = extractor.globalMatch(ftsArg);
while(i.hasNext()) while(i.hasNext())
{ {
@ -78,12 +78,16 @@ QString SqliteSearch::escapeFtsArgument(QString ftsArg)
if(value.isEmpty()) if(value.isEmpty())
{ {
value = m.captured(2); value = m.captured(2);
if(value.endsWith('*'))
{
value = value.mid(0, value.size() - 1);
}
result += "\"" + value + "\"* ";
} }
else else
{ {
value = "\"\"" + value + "\"\""; result += "\"" + value + "\" ";
} }
result += "\"" + value + "\" ";
} }
return result; return result;
} }
@ -137,48 +141,43 @@ QPair<QString, QVector<QString>> SqliteSearch::createSql(const Token &token)
} }
if(token.type == FILTER_CONTENT_CONTAINS) if(token.type == FILTER_CONTENT_CONTAINS)
{ {
return {" content.id IN (SELECT fts.ROWID FROM fts WHERE fts.content MATCH ? ORDER BY " return {" fts MATCH ? ", {escapeFtsArgument(value)}};
"rank) ",
{escapeFtsArgument(value)}};
} }
if(token.type == FILTER_TAG_ASSIGNED)
{
return {" file.id IN (SELECT fileid FROM filetag WHERE tagid = (SELECT id FROM tag WHERE name = ?)) ",
{value.toLower()}};
}
if(token.type == FILTER_OUTLINE_CONTAINS)
{
return {" outline.text LIKE '%' || ? || '%' ", {value.toLower()}};
}
throw LooqsGeneralException("Unknown token passed (should not happen)"); throw LooqsGeneralException("Unknown token passed (should not happen)");
} }
QSqlQuery SqliteSearch::makeSqlQuery(const LooqsQuery &query) QSqlQuery SqliteSearch::makeSqlQuery(const LooqsQuery &query)
{ {
QString whereSql; QString whereSql;
QString joinSql;
QVector<QString> bindValues; QVector<QString> bindValues;
bool isContentSearch = (query.getTokensMask() & FILTER_CONTENT) == FILTER_CONTENT; bool isContentSearch = (query.getTokensMask() & FILTER_CONTENT) == FILTER_CONTENT;
bool isOutlineSearch = query.hasOutlineSearch();
if(query.getTokens().isEmpty()) if(query.getTokens().isEmpty())
{ {
throw LooqsGeneralException("Nothing to search for supplied"); throw LooqsGeneralException("Nothing to search for supplied");
} }
bool ftsAlreadyJoined = false;
auto tokens = query.getTokens(); auto tokens = query.getTokens();
for(const Token &token : tokens) for(const Token &token : tokens)
{ {
if(token.type == FILTER_CONTENT_CONTAINS) auto sql = createSql(token);
{ whereSql += sql.first;
if(!ftsAlreadyJoined) bindValues.append(sql.second);
{
joinSql += " INNER JOIN fts ON content.ftsid = fts.ROWID ";
ftsAlreadyJoined = true;
}
whereSql += " fts.content MATCH ? ";
bindValues.append(escapeFtsArgument(token.value));
}
else
{
auto sql = createSql(token);
whereSql += sql.first;
bindValues.append(sql.second);
}
} }
QString prepSql; QString prepSql;
QString sortSql = createSortSql(query.getSortConditions()); QString sortSql = createSortSql(query.getSortConditions());
int bindIterations = 1;
if(isContentSearch) if(isContentSearch)
{ {
if(sortSql.isEmpty()) if(sortSql.isEmpty())
@ -186,25 +185,43 @@ QSqlQuery SqliteSearch::makeSqlQuery(const LooqsQuery &query)
if(std::find_if(tokens.begin(), tokens.end(), if(std::find_if(tokens.begin(), tokens.end(),
[](const Token &t) -> bool { return t.type == FILTER_CONTENT_CONTAINS; }) != tokens.end()) [](const Token &t) -> bool { return t.type == FILTER_CONTENT_CONTAINS; }) != tokens.end())
{ {
sortSql = "ORDER BY rank"; sortSql = "ORDER BY prio, rank";
} }
} }
prepSql = QString whereSqlTrigram = whereSql;
"SELECT file.path AS path, group_concat(content.page) AS pages, file.mtime AS mtime, file.size AS size, " whereSqlTrigram.replace("fts MATCH", "fts_trigram MATCH"); // A bit dirty...
"file.filetype AS filetype FROM file INNER JOIN content ON file.id = content.fileid " + prepSql = "SELECT DISTINCT path, page, mtime, size, filetype FROM ("
joinSql + " WHERE 1=1 AND " + whereSql + " GROUP BY file.path " + sortSql; "SELECT file.path AS path, content.page AS page, file.mtime AS mtime, file.size AS size, "
"file.filetype AS filetype, 0 AS prio, fts.rank AS rank FROM file INNER JOIN content ON file.id = "
"content.fileid "
"INNER JOIN fts ON content.ftsid = fts.ROWID WHERE 1=1 AND " +
whereSql +
"UNION ALL SELECT file.path AS path, content.page AS page, file.mtime AS mtime, file.size AS size, "
"file.filetype AS filetype, 1 as prio, fts_trigram.rank AS rank FROM file INNER JOIN content ON "
"file.id = "
"content.fileid " +
"INNER JOIN fts_trigram ON content.fts_trigramid = fts_trigram.ROWID WHERE 1=1 AND " +
whereSqlTrigram + " ) " + sortSql;
++bindIterations;
} }
else else
{ {
QString pageColumn = "'0' as page";
QString joiners = "";
if(isOutlineSearch)
{
pageColumn = "outline.page as page";
joiners = " INNER JOIN outline ON outline.fileid = file.id ";
}
if(sortSql.isEmpty()) if(sortSql.isEmpty())
{ {
sortSql = "ORDER BY file.mtime DESC"; sortSql = "ORDER BY file.mtime DESC";
} }
prepSql = "SELECT file.path AS path, '0' as pages, file.mtime AS mtime, file.size AS size, file.filetype AS " prepSql = "SELECT DISTINCT file.path AS path, " + pageColumn +
"filetype FROM file WHERE 1=1 AND " + ",file.mtime AS mtime, file.size AS size, "
whereSql + " " + sortSql; "file.filetype AS filetype FROM file" +
joiners + " WHERE 1=1 AND " + whereSql + " " + sortSql;
} }
if(query.getLimit() > 0) if(query.getLimit() > 0)
{ {
prepSql += " LIMIT " + QString::number(query.getLimit()); prepSql += " LIMIT " + QString::number(query.getLimit());
@ -212,11 +229,14 @@ QSqlQuery SqliteSearch::makeSqlQuery(const LooqsQuery &query)
QSqlQuery dbquery(*db); QSqlQuery dbquery(*db);
dbquery.prepare(prepSql); dbquery.prepare(prepSql);
for(const QString &value : bindValues) for(int i = 0; i < bindIterations; i++)
{ {
if(value != "") for(const QString &value : bindValues)
{ {
dbquery.addBindValue(value); if(value != "")
{
dbquery.addBindValue(value);
}
} }
} }
return dbquery; return dbquery;
@ -235,7 +255,7 @@ QVector<SearchResult> SqliteSearch::search(const LooqsQuery &query)
throw LooqsGeneralException("SQL Error: " + dbQuery.lastError().text()); throw LooqsGeneralException("SQL Error: " + dbQuery.lastError().text());
} }
bool contentSearch = query.hasContentSearch(); bool contentSearch = query.hasContentSearch() || query.hasOutlineSearch();
while(dbQuery.next()) while(dbQuery.next())
{ {
SearchResult result; SearchResult result;
@ -243,15 +263,7 @@ QVector<SearchResult> SqliteSearch::search(const LooqsQuery &query)
result.fileData.mtime = dbQuery.value("mtime").toUInt(); result.fileData.mtime = dbQuery.value("mtime").toUInt();
result.fileData.size = dbQuery.value("size").toUInt(); result.fileData.size = dbQuery.value("size").toUInt();
result.fileData.filetype = dbQuery.value("filetype").toChar(); result.fileData.filetype = dbQuery.value("filetype").toChar();
QString pages = dbQuery.value("pages").toString(); result.page = dbQuery.value("page").toUInt();
QStringList pagesList = pages.split(",");
for(QString &page : pagesList)
{
if(page != "")
{
result.pages.append(page.toUInt());
}
}
result.wasContentSearch = contentSearch; result.wasContentSearch = contentSearch;
results.append(result); results.append(result);
} }

66
shared/tagmanager.cpp 普通文件
查看文件

@ -0,0 +1,66 @@
#include "tagmanager.h"
TagManager::TagManager(SqliteDbService &dbService)
{
this->dbService = &dbService;
}
bool TagManager::addTagsToPath(QString path, const QSet<QString> &tags)
{
QVector<QString> currentTags = this->dbService->getTagsForPath(path);
for(const QString &tag : tags)
{
currentTags.append(tag.toLower());
}
QSet<QString> newTags{currentTags.begin(), currentTags.end()};
return this->dbService->setTags(path, newTags);
}
bool TagManager::removeTagsForPath(QString path, const QSet<QString> &tags)
{
QVector<QString> currentTags = this->dbService->getTagsForPath(path);
for(const QString &tag : tags)
{
currentTags.removeAll(tag);
}
QSet<QString> newTags{currentTags.begin(), currentTags.end()};
return this->dbService->setTags(path, newTags);
}
bool TagManager::removePathsForTag(QString tag, const QVector<QString> &paths)
{
return this->dbService->removePathsForTag(tag, paths);
}
bool TagManager::deleteTag(QString tag)
{
return this->dbService->deleteTag(tag);
}
QVector<QString> TagManager::getTags(QString path)
{
return this->dbService->getTagsForPath(path);
}
QVector<QString> TagManager::getTags()
{
return this->dbService->getTags();
}
QVector<QString> TagManager::getPaths(QString tag)
{
return this->dbService->getPathsForTag(tag);
}
bool TagManager::addTagsToPath(QString path, QString tagstring, QChar delim)
{
auto splitted = tagstring.split(delim);
return addTagsToPath(path, QSet<QString>{splitted.begin(), splitted.end()});
}
bool TagManager::addPathsToTag(QString tag, const QVector<QString> &paths)
{
return this->dbService->addTag(tag, paths);
}

28
shared/tagmanager.h 普通文件
查看文件

@ -0,0 +1,28 @@
#ifndef TAGMANAGER_H
#define TAGMANAGER_H
#include "sqlitedbservice.h"
class TagManager
{
private:
SqliteDbService *dbService = nullptr;
bool ensurePathOkay(QString inpath);
public:
TagManager(SqliteDbService &dbService);
bool addTagsToPath(QString path, const QSet<QString> &tags);
bool addTagsToPath(QString path, QString tagstring, QChar delim);
bool addPathsToTag(QString tag, const QVector<QString> &paths);
bool removeTagsForPath(QString path, const QSet<QString> &tags);
bool removePathsForTag(QString tag, const QVector<QString> &paths);
bool deleteTag(QString tag);
QVector<QString> getTags(QString path);
QVector<QString> getTags();
QVector<QString> getPaths(QString tag);
};
#endif // TAGMANAGER_H

查看文件

@ -4,11 +4,11 @@ TagStripperProcessor::TagStripperProcessor()
{ {
} }
QVector<PageData> TagStripperProcessor::process(const QByteArray &data) const DocumentProcessResult TagStripperProcessor::process(const QByteArray &data) const
{ {
auto result = DefaultTextProcessor::process(data); auto result = DefaultTextProcessor::process(data);
// TODO: does not work properly with <br> and does not deal with entities... // TODO: does not work properly with <br> and does not deal with entities...
Q_ASSERT(result.pages.size() > 0);
result[0].content.remove(QRegExp("<[^>]*>")); result.pages[0].content.remove(QRegExp("<[^>]*>"));
return result; return result;
} }

查看文件

@ -8,7 +8,7 @@ class TagStripperProcessor : public DefaultTextProcessor
TagStripperProcessor(); TagStripperProcessor();
public: public:
QVector<PageData> process(const QByteArray &data) const override; DocumentProcessResult process(const QByteArray &data) const override;
}; };
#endif // XMLSTRIPPERPROCESSOR_H #endif // XMLSTRIPPERPROCESSOR_H

查看文件

@ -19,7 +19,9 @@ enum TokenType
FILTER_PATH_SIZE, FILTER_PATH_SIZE,
FILTER_PATH_ENDS, FILTER_PATH_ENDS,
FILTER_PATH_STARTS, FILTER_PATH_STARTS,
FILTER_CONTENT = 512, FILTER_TAG_ASSIGNED,
FILTER_OUTLINE_CONTAINS,
FILTER_CONTENT = 512, /* Everything below here is content search (except LIMIT) */
FILTER_CONTENT_CONTAINS, FILTER_CONTENT_CONTAINS,
FILTER_CONTENT_PAGE, FILTER_CONTENT_PAGE,
LIMIT = 1024 LIMIT = 1024