aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-10-06 12:11:58 +0200
committerDanilo M. <danix@danix.xyz>2026-10-06 12:11:58 +0200
commit87ff20c96d9a8faa71b03eb0ca912d0ebf8aca7a (patch)
tree34d33beb87d62062ca9781455b8f42b98360f1b7
downloadwallhaven-dl-master.tar.gz
wallhaven-dl-master.zip
Initial commit: wallhaven-dl wallpaper browser and downloaderHEADmaster
Single-file PyQt6 app for wallhaven.cc: - search with purity tabs, category checkboxes, per-monitor size filter and a color swatch row; all filters sent explicitly so account preferences never leak into keyed searches - thumbnail grid with a downloaded overlay, preview panel with full image, details and download - API key from pass, sent only to the API in the X-API-Key header - client-side rate limiter (40/min) with a status bar meter, and a debounce on filter changes - library-wide duplicate detection by wallhaven id under ~/Pictures/wallpapers - low-res finder: flags images smaller than their monitor and searches replacements by first tag or by locally extracted dominant color, with a floating reference window and replace-to-trash - desktop entry and Candy-style icon Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--AGENTS.md82
-rw-r--r--CLAUDE.md6
-rw-r--r--LICENSE339
-rw-r--r--README.md59
-rw-r--r--test_wallhaven_dl.py83
-rwxr-xr-xwallhaven-dl668
-rw-r--r--wallhaven-dl.desktop11
-rw-r--r--wallhaven-dl.svg21
8 files changed, 1269 insertions, 0 deletions
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..41727e0
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,82 @@
+# AGENTS.md
+
+Guidance for AI coding agents working in this repository.
+
+## What this is
+
+`wallhaven-dl`: single-file PyQt6 desktop app to search wallhaven.cc, preview
+and download wallpapers, and find better-resolution replacements for low-res
+images already on disk. The only dependency is PyQt6 (QtWidgets, QtNetwork);
+everything else is stdlib. Keep it a single file and do not add dependencies.
+
+On the maintainer's machine the script, menu entry and icon are symlinks into
+the repo, so edits are live on the next launch:
+
+ ~/bin/wallhaven-dl -> wallhaven-dl
+ ~/.local/share/applications/wallhaven-dl.desktop -> wallhaven-dl.desktop
+ ~/.local/share/icons/hicolor/scalable/apps/wallhaven-dl.svg -> wallhaven-dl.svg
+
+## wallhaven API facts (verified, not in the docs)
+
+- Rate limit is 45 API calls per minute. The app caps itself at 40
+ (`API_LIMIT`) with a sliding-window limiter in `get()`, and debounces filter
+ changes by 400 ms. Thumbnails (`th.wallhaven.cc`) and full images
+ (`w.wallhaven.cc`) do not count. Keep test runs cheap: stub
+ `Main.search` when no network is needed, and never loop over the API.
+- With an API key, every parameter the request omits falls back to the
+ account's saved search settings (categories, resolutions, ...). That is why
+ `categories`, `purity` and `atleast` are always sent explicitly
+ (`atleast=1x1` for "any size").
+- The key goes in the `X-API-Key` header, only for URLs under `API`, never in
+ the query string. It is read from `pass` (`WALLHAVEN_PASS_ENTRY`, default
+ `wallhaven.cc/api-key`) at startup.
+- `like:<id>` similarity search is behind a Cloudflare bot challenge (403, for
+ the API and the site alike). Do not try to get around it. The low-res
+ feature uses the wallpaper's first tag (`id:<tag id>`) instead, under the
+ wallpaper's own purity.
+- `colors` accepts only the 29 palette values in `COLORS`. Each wallpaper
+ stores five colors and a color search matches any of the five. The local
+ extraction (`palette_histogram`, redmean distance) agrees with the site's
+ list well: measured on 72 wallpapers, the picked color was in the site's
+ list 72/72 times.
+- There is no reverse image search on wallhaven. Sending local images to
+ third-party services was rejected for privacy.
+
+## Library and files
+
+- `LIBRARY` (`~/Pictures/wallpapers`, recursive, hidden dirs skipped) is what
+ "downloaded" means. Files are matched by the wallhaven id in their name
+ (`WALL_ID`, also `wallhaven-<id>_<WxH>.png` copies), never by path.
+- Writes go to a `.part` file renamed into place. Replacing an original saves
+ the new file first and only then moves the old one to the desktop trash
+ (`QFile.moveToTrash`). Never delete user images outright.
+
+## Conventions
+
+- Non-GUI logic lives in module-level functions (`read_apikey`, `api_delay`,
+ `target`, `scan_library`, `nearest_color`, `search_pick`, ...) so it can be
+ tested without a display.
+- Async replies check `gen` before touching grid items: `grid.clear()` deletes
+ them, and a stale callback would hit a dead C++ object.
+- Do not name methods after `QWidget` ones (`show` once shadowed
+ `QWidget.show()` and broke startup).
+- Placeholders only in code, docs, tests and commits: no real account names,
+ file names from the maintainer's library, or `pass` entry names beyond the
+ generic default.
+
+## Testing
+
+ python3 test_wallhaven_dl.py
+
+Covers the non-GUI functions with plain asserts and a fake `pass` on `PATH`.
+For GUI checks, run headless and keep settings away from the real config:
+
+ XDG_CONFIG_HOME=/tmp/whdl-cfg QT_QPA_PLATFORM=offscreen python3 -I <script>
+
+loading the app with `importlib.machinery.SourceFileLoader` (the file has no
+`.py` extension), and `w.grab().save(...)` for screenshots.
+
+## Repo facts
+
+- License: GPLv2 only (`LICENSE`, header in each source file).
+- `origin` is the personal git server (cgit section "Generic Projects").
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..0d86339
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,6 @@
+# CLAUDE.md
+
+This file is intentionally thin. AGENTS.md is the single source of truth for
+project guidance, shared across every agent tool. Edit AGENTS.md instead.
+
+@AGENTS.md
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d159169
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..70adc4b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,59 @@
+# wallhaven-dl
+
+Small PyQt6 app to search [wallhaven.cc](https://wallhaven.cc) and download wallpapers, with a thumbnail grid for previews.
+
+## Requirements
+
+- Python 3
+- PyQt6 (QtWidgets + QtNetwork)
+
+## Install
+
+Symlink the script, menu entry and icon into your home directory, so later updates of the repo apply without reinstalling (`~/bin` must be on `PATH`):
+
+ ln -s "$PWD/wallhaven-dl" ~/bin/wallhaven-dl
+ ln -s "$PWD/wallhaven-dl.desktop" ~/.local/share/applications/wallhaven-dl.desktop
+ ln -s "$PWD/wallhaven-dl.svg" ~/.local/share/icons/hicolor/scalable/apps/wallhaven-dl.svg
+ update-desktop-database ~/.local/share/applications
+ gtk-update-icon-cache -f -t ~/.local/share/icons/hicolor
+
+To uninstall, remove the three symlinks.
+
+## Usage
+
+ ./wallhaven-dl
+
+- SFW / Sketchy / NSFW tabs at the top switch which purity level is shown.
+- The size picker lists each connected monitor. Picking one shows wallpapers at least as large as that monitor, in its orientation (portrait for a vertical screen). "any size" drops the filter.
+- General / Anime / People checkboxes filter by category.
+- The row of color swatches under the search bar filters by dominant color ("any" turns it off). The API only accepts these 29 fixed palette colors. On a narrow window the row scrolls sideways.
+- Every filter change searches after a short pause, so a burst of clicks costs one API call. Tags, `@username` or `id:<tag id>` go in the search box (press Enter).
+- "Load more" fetches the next page of results.
+- Double-click a thumbnail (or press Enter) to open a preview panel on the right. It shows the full image, its details and colors, and a link to its wallhaven page. Its "Download" button saves the already loaded image without fetching it again.
+- Select one or more thumbnails (Ctrl/Shift-click) and press "Download selected" to download several at once.
+- Ctrl+Q quits.
+- Wallpapers already in your library are dimmed, with a large green check mark and "downloaded" over the thumbnail, and downloading skips them. The library is `~/Pictures/wallpapers/` and all its subfolders (hidden ones skipped), plus the save folder if it lives elsewhere. Files are recognized by the wallhaven id in their name, `wallhaven-<id>.<ext>` or renamed copies like `wallhaven-<id>_2560x1080.png`, so the same wallpaper is never downloaded into two folders. The library is rescanned on every new search.
+- The "Folder" button picks the save folder (default `~/Pictures/wallpapers/wallhaven/`). The choice is remembered in `~/.config/wallhaven-dl/wallhaven-dl.conf`.
+- "Find low-res on disk" lists images anywhere in the library that are smaller than the monitor they match (same orientation, largest such monitor). A wallhaven wallpaper exists at one resolution only, so double-clicking one searches for alternatives at that monitor's size instead. Files with a wallhaven id in their name are searched by their first tag, under their own purity. Any other file is searched by its dominant color, extracted locally (the image never leaves your machine): every pixel is mapped to the nearest of wallhaven's 29 palette colors, and the most common chromatic one is used, falling back to grey when no color covers at least 10% of the image. The status bar shows the top three colors, so you can click another swatch, and the purity tabs and category checkboxes refine the results as usual. The original image also opens in a small floating window titled with its name and resolution. It stays on top while you browse candidates, can be moved and resized, and is replaced by the next pick. While it is open, the preview panel has a "Replace original" button: after a confirmation it saves the previewed wallpaper into the original's folder, and only once that write succeeds moves the original to the desktop trash, so it can always be restored. wallhaven's own `like:<id>` similarity search would be better, but it sits behind a Cloudflare bot check that blocks API clients.
+
+Filters are always sent explicitly, so the search preferences saved on your wallhaven account never apply. The API allows 45 requests per minute. The app caps itself at 40 and queues anything beyond that, showing the wait in the status bar. The meter at the right of the status bar shows how many API calls were made in the last 60 seconds. It is a sliding window, so each call drops off the meter one minute after it was made. Thumbnail and image downloads don't count toward the limit.
+
+## API key
+
+NSFW results need a wallhaven API key (account settings on wallhaven.cc). The key is read at startup from [pass](https://www.passwordstore.org/), from the entry `wallhaven.cc/api-key` by default, or the one named in `WALLHAVEN_PASS_ENTRY`:
+
+ WALLHAVEN_PASS_ENTRY=wallhaven.cc/you ./wallhaven-dl
+
+If the entry has an `apikey: <key>` line, that is used, so the key can live next to the site password. Otherwise the entry's first line is the key. Without a key the NSFW tab stays disabled. The key is sent only to the API, in the `X-API-Key` header.
+
+## License
+
+GPLv2-only. See [LICENSE](LICENSE).
+
+## Development Approach
+
+This project is developed using AI-assisted tools. Code is generated with the help of AI based on human-provided specifications, design decisions, and iterative feedback.
+
+All contributions are reviewed, tested, and curated by the maintainer before being included in the codebase. AI is used as a productivity and exploration tool, while human oversight remains central to all decisions.
+
+The goal is to combine the flexibility of AI-assisted development with standard open-source practices such as transparency, review, and accountability.
diff --git a/test_wallhaven_dl.py b/test_wallhaven_dl.py
new file mode 100644
index 0000000..a72ae6e
--- /dev/null
+++ b/test_wallhaven_dl.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python3
+# Checks for wallhaven-dl's non-GUI logic. Run: python3 test_wallhaven_dl.py
+#
+# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+import importlib.machinery
+import importlib.util
+import os
+import sys
+import tempfile
+from pathlib import Path
+
+sys.dont_write_bytecode = True
+loader = importlib.machinery.SourceFileLoader("whdl", str(Path(__file__).with_name("wallhaven-dl")))
+spec = importlib.util.spec_from_loader("whdl", loader)
+whdl = importlib.util.module_from_spec(spec)
+loader.exec_module(whdl)
+
+# target(): which monitor an image is meant for
+wide, tall, big = (2560, 1080), (1080, 1920), (3840, 2160)
+assert whdl.target(1920, 1080, [wide, tall]) == 0 # landscape image -> landscape monitor
+assert whdl.target(1080, 1920, [wide, tall]) == 1 # portrait image -> portrait monitor
+assert whdl.target(1920, 1080, [wide, big, tall]) == 1 # largest of the landscape ones
+assert whdl.target(1080, 1920, [wide, big]) == 1 # no portrait monitor -> largest overall
+
+# api_delay(): rate limiter
+assert whdl.api_delay([], 100.0) == 0
+assert whdl.api_delay([50.0 + i for i in range(39)], 100.0) == 0 # under the limit
+assert whdl.api_delay([50.0 + i for i in range(40)], 100.0) == 10.0 # oldest of last 40 at t=50
+assert whdl.api_delay([0.0] * 5 + [50.0 + i for i in range(39)], 100.0) == 0 # old calls expired
+
+# scan_library(): wallhaven ids anywhere under the roots, hidden folders and .part skipped
+with tempfile.TemporaryDirectory() as tmp:
+ for f in ["wallhaven-aaa111.jpg", "sub/deeper/wallhaven-bbb222.png", "sub/holiday.jpg",
+ "sub/wallhaven-eee555_2560x1080.png",
+ ".current/wallhaven-ccc333.jpg", "wallhaven-ddd444.part"]:
+ Path(tmp, f).parent.mkdir(parents=True, exist_ok=True)
+ Path(tmp, f).write_bytes(b"")
+ found = whdl.scan_library(Path(tmp), Path(tmp, "missing"))
+ assert found == {"aaa111": Path(tmp, "wallhaven-aaa111.jpg"),
+ "bbb222": Path(tmp, "sub/deeper/wallhaven-bbb222.png"),
+ "eee555": Path(tmp, "sub/wallhaven-eee555_2560x1080.png")}, found
+
+# nearest_color() / palette_histogram(): local color extraction mapped onto wallhaven's palette
+assert whdl.COLORS[whdl.nearest_color(0, 0, 0)] == "000000"
+assert whdl.COLORS[whdl.nearest_color(255, 255, 250)] == "ffffff"
+assert whdl.COLORS[whdl.nearest_color(10, 100, 210)] == "0066cc" # a slightly off blue
+assert whdl.COLORS[whdl.nearest_color(250, 0, 5)] == "cc0000" # pure-ish red
+hist = whdl.palette_histogram([(10, 100, 210)] * 60 + [(0, 0, 0)] * 30 + [(255, 255, 0)] * 10)
+assert [whdl.COLORS[i] for i, _ in hist.most_common()] == ["0066cc", "000000", "ffff00"], hist
+
+# search_pick(): prefers a chromatic color over greys when it covers enough of the image
+grey, brown, blue, black = (whdl.COLORS.index(c) for c in ("999999", "996633", "0066cc", "000000"))
+assert whdl.search_pick(whdl.Counter({grey: 47, brown: 35, blue: 18})) == brown
+assert whdl.search_pick(whdl.Counter({grey: 60, black: 35, blue: 5})) == grey # blue under 10%
+
+# read_apikey(): parses a fake `pass` put first on PATH
+with tempfile.TemporaryDirectory() as tmp:
+ fake = Path(tmp, "pass")
+ fake.write_text('#!/bin/sh\ncase "$2" in\n'
+ " multi) printf 'sitepassword\\nlogin: someone\\nAPIKey: abc123\\n' ;;\n"
+ " plain) printf 'xyz789\\n' ;;\n"
+ " *) exit 1 ;;\nesac\n")
+ fake.chmod(0o755)
+ os.environ["PATH"] = f"{tmp}:{os.environ['PATH']}"
+ assert whdl.read_apikey("multi") == "abc123"
+ assert whdl.read_apikey("plain") == "xyz789"
+ assert whdl.read_apikey("missing") == ""
+
+print("ok")
diff --git a/wallhaven-dl b/wallhaven-dl
new file mode 100755
index 0000000..1f30f49
--- /dev/null
+++ b/wallhaven-dl
@@ -0,0 +1,668 @@
+#!/usr/bin/env python3
+# wallhaven-dl: search wallhaven.cc and download wallpapers, with thumbnail previews.
+#
+# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+import json
+import os
+from collections import Counter
+import re
+import subprocess
+import sys
+import time
+from pathlib import Path
+from urllib.parse import urlencode
+
+from PyQt6.QtCore import QFile, QSettings, QSize, Qt, QTimer, QUrl
+from PyQt6.QtGui import QColor, QIcon, QImageReader, QKeySequence, QPainter, QPixmap, QShortcut
+from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
+from PyQt6.QtWidgets import (QAbstractItemView, QApplication, QButtonGroup, QCheckBox,
+ QComboBox, QDialog, QFileDialog, QHBoxLayout, QLabel, QLineEdit,
+ QListView, QListWidget, QListWidgetItem, QMainWindow,
+ QMessageBox, QProgressBar, QPushButton, QScrollArea, QSplitter, QStyle,
+ QTabBar, QToolButton, QVBoxLayout, QWidget)
+
+API = "https://wallhaven.cc/api/v1/"
+LIBRARY = Path.home() / "Pictures" / "wallpapers" # a wallpaper anywhere under here counts as downloaded
+DEFAULT_DIR = LIBRARY / "wallhaven"
+SORTS = ["date_added", "toplist", "views", "favorites", "random", "relevance"]
+ROLE = Qt.ItemDataRole.UserRole
+THUMB = ROLE.value + 1 # item data: the bare thumbnail, so the overlay can be added or removed
+SAVED = QColor("#6fcf6f") # overlay color of wallpapers already in the save folder
+# the only values the API's colors filter accepts
+COLORS = ["660000", "990000", "cc0000", "cc3333", "ea4c88", "993399", "663399", "333399",
+ "0066cc", "0099cc", "66cccc", "77cc33", "669900", "336600", "666600", "999900",
+ "cccc33", "ffff00", "ffcc33", "ff9900", "ff6600", "cc6633", "996633", "663300",
+ "000000", "999999", "cccccc", "ffffff", "424153"]
+PALETTE = [tuple(int(c[k:k + 2], 16) for k in (0, 2, 4)) for c in COLORS]
+# wallhaven's own file names carry the id, also kept in renamed copies like wallhaven-<id>_2560x1080.png
+WALL_ID = re.compile(r"wallhaven-([a-z0-9]+)[._]")
+PASS_ENTRY = os.environ.get("WALLHAVEN_PASS_ENTRY", "wallhaven.cc/api-key")
+APIKEY = "" # filled from pass at startup, needed for NSFW results
+API_LIMIT = 40 # calls per minute; wallhaven allows 45, keep some headroom
+
+
+def read_apikey(entry=PASS_ENTRY):
+ """API key from pass: the entry's 'apikey:' line if it has one, else its first line."""
+ try:
+ out = subprocess.run(["pass", "show", entry], capture_output=True,
+ text=True, check=True).stdout
+ except (OSError, subprocess.CalledProcessError):
+ return "" # no pass or no entry: run SFW/Sketchy only
+ lines = out.splitlines()
+ for line in lines:
+ key, sep, value = line.partition(":")
+ if sep and key.strip().lower() == "apikey":
+ return value.strip()
+ return lines[0].strip() if lines else ""
+
+
+def api_delay(sent, now, limit=API_LIMIT, window=60.0):
+ """Seconds to wait before the next API call, given the send times of earlier ones."""
+ recent = [t for t in sent if now - t < window]
+ return 0.0 if len(recent) < limit else window - (now - recent[-limit])
+
+
+def nearest_color(r, g, b):
+ """Index into COLORS of the palette color closest to r, g, b. Uses the "redmean"
+ weighted RGB distance, a cheap approximation of how different colors look."""
+ def dist(c):
+ rm = (r + c[0]) / 2
+ return ((2 + rm / 256) * (r - c[0]) ** 2 + 4 * (g - c[1]) ** 2
+ + (2 + (255 - rm) / 256) * (b - c[2]) ** 2)
+ return min(range(len(PALETTE)), key=lambda i: dist(PALETTE[i]))
+
+
+def palette_histogram(pixels):
+ """Counter of COLORS indexes over an iterable of (r, g, b) pixels."""
+ return Counter(nearest_color(*px) for px in pixels)
+
+
+NEUTRALS = {COLORS.index(c) for c in ("000000", "999999", "cccccc", "ffffff", "424153")}
+
+
+def search_pick(hist, min_share=0.10):
+ """Palette color to search by: the top chromatic one if it covers min_share of the
+ image, else the top overall. Greys dominate most images and make a vague search."""
+ total = sum(hist.values())
+ for i, n in hist.most_common():
+ if i not in NEUTRALS and n >= total * min_share:
+ return i
+ return hist.most_common(1)[0][0]
+
+
+def target(w, h, monitors):
+ """Index of the monitor a w x h image is meant for: the largest one in the same
+ orientation, or the largest overall when no monitor shares its orientation."""
+ same = [i for i, (mw, mh) in enumerate(monitors) if (mh > mw) == (h > w)]
+ return max(same or range(len(monitors)), key=lambda i: monitors[i][0] * monitors[i][1])
+
+
+def downloaded_overlay(pix):
+ """Copy of pix, dimmed, with a big green check mark over the word "downloaded"."""
+ out = QPixmap(pix)
+ w, h = out.width(), out.height()
+ p = QPainter(out)
+ p.fillRect(out.rect(), QColor(0, 0, 0, 140))
+ p.setPen(SAVED)
+ font = p.font()
+ font.setBold(True)
+ font.setPixelSize(h * 2 // 5)
+ p.setFont(font)
+ p.drawText(0, 0, w, h * 3 // 5, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignBottom, "✓")
+ font.setPixelSize(h // 9)
+ p.setFont(font)
+ p.drawText(0, h * 3 // 5, w, h * 2 // 5, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop,
+ "downloaded")
+ p.end()
+ return out
+
+
+def library_files(*roots):
+ """Every file under roots, skipping hidden folders and unfinished .part downloads."""
+ for root in roots:
+ for dirpath, dirs, files in os.walk(root):
+ dirs[:] = sorted(d for d in dirs if not d.startswith("."))
+ for f in sorted(files):
+ if not f.endswith(".part"):
+ yield Path(dirpath, f)
+
+
+def scan_library(*roots):
+ """Map wallhaven id -> path for every wallhaven-named file under roots."""
+ found = {}
+ for p in library_files(*roots):
+ m = WALL_ID.match(p.name)
+ if m:
+ found.setdefault(m[1], p)
+ return found
+
+
+def make_grid():
+ grid = QListWidget()
+ grid.setViewMode(QListView.ViewMode.IconMode)
+ grid.setResizeMode(QListView.ResizeMode.Adjust)
+ grid.setMovement(QListView.Movement.Static)
+ grid.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
+ grid.setIconSize(QSize(300, 200))
+ grid.setGridSize(QSize(310, 232)) # fixed cells: icons load late, so items can't size themselves
+ return grid
+
+
+class Reference(QLabel):
+ """Floating window showing the local image a low-res search started from, so it stays
+ in view while browsing candidates. Move and resize it freely, close it when done."""
+
+ def __init__(self, parent):
+ super().__init__(parent, Qt.WindowType.Tool) # stays above the main window
+ self.setAlignment(Qt.AlignmentFlag.AlignCenter)
+ self.setMinimumSize(160, 100) # explicit, so the pixmap's size can't stop shrinking
+ self.pix = QPixmap()
+
+ def show_image(self, path):
+ self.path = path
+ self.pix = QPixmap(path)
+ self.setWindowTitle(f"original: {Path(path).name} ({self.pix.width()}x{self.pix.height()})")
+ if not self.isVisible():
+ self.resize(self.pix.size().scaled(360, 360, Qt.AspectRatioMode.KeepAspectRatio))
+ self.show()
+ self.fit()
+
+ def fit(self):
+ if not self.pix.isNull():
+ self.setPixmap(self.pix.scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatio,
+ Qt.TransformationMode.SmoothTransformation))
+
+ def resizeEvent(self, event):
+ super().resizeEvent(event)
+ self.fit()
+
+ def closeEvent(self, event):
+ super().closeEvent(event)
+ self.parent().replace.hide() # nothing left to replace
+
+
+class Main(QMainWindow):
+ def __init__(self):
+ super().__init__()
+ self.setWindowTitle("wallhaven-dl")
+ self.resize(1300, 850)
+ self.net = QNetworkAccessManager(self)
+ self.gen = 0 # bumped on each new search, so stale replies are dropped
+ self.page = self.last_page = 1
+ self.seed = None
+ self.sent = [] # send times of API calls, for the rate limit
+ self.later = QTimer(self, singleShot=True, interval=400) # debounces filter changes
+ self.settings = QSettings("wallhaven-dl", "wallhaven-dl") # ~/.config/wallhaven-dl/
+ self.save_dir = Path(self.settings.value("save_dir", str(DEFAULT_DIR)))
+ self.have = {} # wallhaven id -> file on disk, see refresh_library()
+ self.reference = Reference(self)
+
+ self.purity = QTabBar()
+ for name in ("SFW", "Sketchy", "NSFW"):
+ self.purity.addTab(name)
+ self.purity.setTabEnabled(2, bool(APIKEY))
+ if not APIKEY:
+ self.purity.setTabToolTip(2, f"no API key found in pass entry {PASS_ENTRY}")
+
+ self.query = QLineEdit(placeholderText="tags, @user, id:<tag id>")
+ self.sort = QComboBox()
+ self.sort.addItems(SORTS)
+ # one entry per monitor: wallpapers at least as big as it, in its orientation
+ self.fit = QComboBox()
+ screens = QApplication.screens()
+ self.monitors = []
+ for s in screens:
+ r = s.devicePixelRatio()
+ w, h = round(s.size().width() * r), round(s.size().height() * r)
+ self.monitors.append((w, h))
+ self.fit.addItem(f"fits {s.name()} ({w}x{h})",
+ {"atleast": f"{w}x{h}", "ratios": "portrait" if h > w else "landscape"})
+ # explicit 1x1 rather than nothing, so the account's own resolution filter never applies
+ self.fit.addItem("any size", {"atleast": "1x1"})
+ self.fit.setCurrentIndex(screens.index(QApplication.primaryScreen()))
+ # color swatches, one exclusive row: id 0 is "any", id i is COLORS[i - 1]
+ self.color = QButtonGroup(self)
+ swatches = QHBoxLayout()
+ swatches.setContentsMargins(0, 0, 0, 0)
+ swatches.setSpacing(4)
+ swatches.addStretch() # with the one after the buttons: centered when it fits
+ for i, hexcode in enumerate([None, *COLORS]):
+ b = QToolButton(checkable=True, checked=not i)
+ b.setFixedSize(30 if i else 46, 30) # "any" needs room for its text inside the thick border
+ b.setText("any" if not i else "")
+ b.setToolTip("any color" if not i else f"#{hexcode}")
+ b.setAccessibleName(b.toolTip())
+ bg = ""
+ if hexcode:
+ r, g, bl = (int(hexcode[k:k + 2], 16) for k in (0, 2, 4))
+ ink = "black" if 0.299 * r + 0.587 * g + 0.114 * bl > 150 else "white"
+ bg = f"background: #{hexcode}; color: {ink}; font-weight: bold;"
+ # a check mark in a contrasting ink, the border alone vanishes on similar colors
+ b.toggled.connect(lambda on, b=b: b.setText("✓" if on else ""))
+ b.setStyleSheet(f"QToolButton {{ {bg} border: 1px solid palette(mid); border-radius: 4px; }}"
+ "QToolButton:checked { border: 3px solid palette(highlight); }")
+ self.color.addButton(b, i)
+ swatches.addWidget(b)
+ swatches.addStretch()
+ row = QWidget()
+ row.setLayout(swatches)
+ # fits on wide windows, scrolls sideways on narrow ones
+ self.colors_row = QScrollArea(widgetResizable=True, frameShape=QScrollArea.Shape.NoFrame)
+ self.colors_row.setWidget(row)
+ self.colors_row.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
+ self.colors_row.setFixedHeight(
+ 34 + self.style().pixelMetric(QStyle.PixelMetric.PM_ScrollBarExtent))
+ # always sent, so the account's category preferences never apply either
+ self.cats = [QCheckBox(name, checked=True) for name in ("General", "Anime", "People")]
+ search = QPushButton("Search")
+ self.more = QPushButton("Load more", enabled=False)
+ lowres = QPushButton("Find low-res on disk")
+ self.folder = QPushButton()
+ self.folder.setToolTip("folder downloads are saved to")
+ self.show_folder()
+ download = QPushButton("Download selected")
+
+ self.grid = make_grid()
+ self.blank = QPixmap(300, 200) # placeholder until the thumbnail arrives
+ self.blank.fill(Qt.GlobalColor.transparent)
+
+ tabs = QHBoxLayout()
+ tabs.addStretch()
+ tabs.addWidget(self.purity)
+ tabs.addStretch()
+ bar = QHBoxLayout()
+ bar.setSpacing(10)
+ bar.addWidget(self.query, stretch=1)
+ for w in (self.sort, self.fit):
+ bar.addWidget(w)
+ bar.addSpacing(10)
+ for w in (*self.cats, search):
+ bar.addWidget(w)
+ bottom = QHBoxLayout()
+ bottom.setSpacing(10)
+ bottom.addWidget(self.more)
+ bottom.addStretch()
+ for w in (lowres, self.folder, download):
+ bottom.addWidget(w)
+ box = QVBoxLayout()
+ box.setContentsMargins(14, 12, 14, 8)
+ box.setSpacing(12)
+ for row in (tabs, bar):
+ box.addLayout(row)
+ box.addWidget(self.colors_row)
+ self.preview = self.make_preview()
+ self.split = QSplitter()
+ self.split.addWidget(self.grid)
+ self.split.addWidget(self.preview)
+ self.split.setStretchFactor(0, 1)
+ self.split.splitterMoved.connect(self.fit_preview)
+ box.addWidget(self.split)
+ box.addLayout(bottom)
+ central = QWidget()
+ central.setLayout(box)
+ self.setCentralWidget(central)
+
+ # every filter change searches, after a short pause so a burst of clicks costs one API call
+ self.later.timeout.connect(self.search)
+ for sig in (self.purity.currentChanged, self.sort.currentIndexChanged,
+ self.fit.currentIndexChanged, self.color.idClicked,
+ *(c.toggled for c in self.cats)):
+ sig.connect(lambda *_: self.later.start())
+ self.query.returnPressed.connect(self.search)
+ search.clicked.connect(self.search)
+ self.more.clicked.connect(lambda: self.search(page=self.page + 1))
+ lowres.clicked.connect(self.find_lowres)
+ self.folder.clicked.connect(self.choose_folder)
+ download.clicked.connect(self.download)
+ self.grid.itemActivated.connect(self.show_preview) # double-click/Enter
+ QShortcut(QKeySequence("Ctrl+Q"), self, activated=self.close)
+
+ # API calls in the last minute, the same sliding window the rate limiter uses
+ self.meter_label = QLabel()
+ self.meter = QProgressBar(maximum=API_LIMIT, textVisible=False, maximumWidth=140)
+ self.statusBar().addPermanentWidget(self.meter_label)
+ self.statusBar().addPermanentWidget(self.meter)
+ QTimer(self, interval=1000, timeout=self.update_meter).start()
+ self.update_meter()
+ self.search()
+
+ def update_meter(self):
+ now = time.monotonic()
+ self.sent = [t for t in self.sent if now - t < 60]
+ self.meter.setValue(len(self.sent))
+ self.meter_label.setText(f"{len(self.sent)}/{API_LIMIT} api calls")
+
+ def make_preview(self):
+ panel = QWidget(visible=False)
+ self.pv_image = QLabel(alignment=Qt.AlignmentFlag.AlignCenter, minimumWidth=320)
+ self.pv_info = QLabel(openExternalLinks=True, wordWrap=True,
+ textFormat=Qt.TextFormat.RichText)
+ dl, close = QPushButton("Download"), QPushButton("Close")
+ # shown only while a low-res original is open in the reference window
+ self.replace = QPushButton("Replace original", visible=False)
+ self.replace.setToolTip("save this wallpaper next to the original, then move the original to the trash")
+ dl.clicked.connect(self.download_preview)
+ self.replace.clicked.connect(self.replace_original)
+ close.clicked.connect(panel.hide)
+ buttons = QHBoxLayout()
+ for b in (dl, self.replace, close):
+ buttons.addWidget(b)
+ box = QVBoxLayout(panel)
+ box.setContentsMargins(8, 0, 0, 0)
+ box.addWidget(self.pv_image, stretch=1)
+ box.addWidget(self.pv_info)
+ box.addLayout(buttons)
+ return panel
+
+ def show_preview(self, item):
+ w = item.data(ROLE)
+ self.pv = {"w": w, "item": item, "gen": self.gen, "data": None, "pix": QPixmap()}
+ self.replace.setVisible(self.reference.isVisible())
+ swatches = "".join(f'<span style="background:{c}">&nbsp;&nbsp;&nbsp;&nbsp;</span> '
+ for c in w["colors"])
+ self.pv_info.setText(
+ f'<b>{w["resolution"]}</b> · {w["file_size"] / 2**20:.1f} MiB · '
+ f'★{w["favorites"]} · {w["views"]} views · {w["category"]} · {w["purity"]}<br>'
+ f'{swatches}<br><a href="{w["url"]}">open on wallhaven</a>')
+ self.pv_image.setText("loading full image...")
+ if not self.preview.isVisible():
+ self.preview.show()
+ self.split.setSizes([self.width() - 520, 520])
+ # the full image doubles as the download, the panel's Download button reuses it
+ self.get(w["path"], lambda data, pv=self.pv: self.preview_loaded(pv, data))
+
+ def preview_loaded(self, pv, data):
+ if pv is not self.pv:
+ return # another wallpaper was opened meanwhile
+ pv["data"] = data
+ pv["pix"].loadFromData(data)
+ self.fit_preview()
+
+ def fit_preview(self, *_):
+ if self.preview.isVisible() and getattr(self, "pv", None) and not self.pv["pix"].isNull():
+ self.pv_image.setPixmap(self.pv["pix"].scaled(
+ self.pv_image.size(), Qt.AspectRatioMode.KeepAspectRatio,
+ Qt.TransformationMode.SmoothTransformation))
+
+ def resizeEvent(self, event):
+ super().resizeEvent(event)
+ self.fit_preview()
+
+ def download_preview(self):
+ pv = self.pv
+ if pv["w"]["id"] in self.have:
+ self.already(pv["w"])
+ elif pv["data"]:
+ self.save_dir.mkdir(parents=True, exist_ok=True)
+ self.save(self.dest(pv["w"]), pv["data"], pv["item"], pv["gen"], pv["w"]["id"])
+ else:
+ self.statusBar().showMessage("full image still loading, try again in a moment")
+
+ def get(self, url, done):
+ if url.startswith(API): # thumbnails and full images don't count toward the limit
+ now = time.monotonic()
+ self.sent = [t for t in self.sent if now - t < 60]
+ wait = api_delay(self.sent, now)
+ if wait:
+ self.statusBar().showMessage(f"API limit reached, waiting {wait:.0f}s...")
+ QTimer.singleShot(int(wait * 1000) + 50, lambda: self.get(url, done))
+ return
+ self.sent.append(now)
+ self.update_meter()
+ req = QNetworkRequest(QUrl(url))
+ req.setHeader(QNetworkRequest.KnownHeaders.UserAgentHeader, "wallhaven-dl")
+ if APIKEY and url.startswith(API): # header, not ?apikey=, so it never lands in URLs or logs
+ req.setRawHeader(b"X-API-Key", APIKEY.encode())
+ reply = self.net.get(req)
+
+ def finished():
+ reply.deleteLater()
+ if reply.error() != QNetworkReply.NetworkError.NoError:
+ self.statusBar().showMessage(f"{url}: {reply.errorString()}")
+ else:
+ done(bytes(reply.readAll()))
+ reply.finished.connect(finished)
+
+ def search(self, *_, page=1):
+ cats = "".join("1" if c.isChecked() else "0" for c in self.cats)
+ if cats == "000":
+ self.statusBar().showMessage("pick at least one category")
+ return
+ if page == 1:
+ self.gen += 1
+ self.seed = None
+ self.refresh_library() # pick up files moved or deleted since the last search
+ params = {"q": self.query.text().strip(), "sorting": self.sort.currentText(),
+ "page": page, "seed": self.seed, "categories": cats,
+ "purity": "".join("1" if i == self.purity.currentIndex() else "0" for i in range(3)),
+ "colors": COLORS[self.color.checkedId() - 1] if self.color.checkedId() else None,
+ **self.fit.currentData()}
+ params = {k: v for k, v in params.items() if v}
+ self.more.setEnabled(False)
+ self.statusBar().showMessage("searching...")
+ gen = self.gen
+ self.get(f"{API}search?{urlencode(params)}", lambda data: self.show_results(data, gen))
+
+ def show_results(self, data, gen):
+ if gen != self.gen:
+ return
+ res = json.loads(data)
+ meta = res["meta"]
+ self.page, self.last_page = meta["current_page"], meta["last_page"]
+ self.seed = meta.get("seed")
+ if self.page == 1:
+ self.grid.clear()
+ for w in res["data"]:
+ item = QListWidgetItem()
+ item.setData(ROLE, w)
+ item.setToolTip(f'{w["id"]} {w["resolution"]} {w["file_size"] // 1024} KiB')
+ self.mark(item)
+ self.grid.addItem(item)
+ self.get(w["thumbs"]["small"], lambda d, item=item: self.thumb(item, d, gen))
+ self.more.setEnabled(self.page < self.last_page)
+ self.statusBar().showMessage(f'page {self.page}/{self.last_page}, {meta["total"]} results')
+
+ def thumb(self, item, data, gen):
+ if gen == self.gen: # grid not cleared since, so item still alive
+ pix = QPixmap()
+ pix.loadFromData(data)
+ item.setData(THUMB, pix)
+ self.mark(item)
+
+ def dest(self, w):
+ return self.save_dir / w["path"].rsplit("/", 1)[1]
+
+ def roots(self):
+ """The library, plus the save folder when it lives outside it."""
+ return (LIBRARY,) if self.save_dir.is_relative_to(LIBRARY) else (LIBRARY, self.save_dir)
+
+ def refresh_library(self):
+ self.have = scan_library(*self.roots())
+
+ def already(self, w):
+ where = str(self.have[w["id"]]).replace(str(Path.home()), "~", 1)
+ self.statusBar().showMessage(f"already have {where}")
+
+ def mark(self, item):
+ """Label a result, with the downloaded overlay if it is anywhere in the library."""
+ w = item.data(ROLE)
+ item.setText(f'{w["resolution"]} ★{w["favorites"]}')
+ pix = item.data(THUMB)
+ pix = self.blank if pix is None else pix
+ item.setIcon(QIcon(downloaded_overlay(pix) if w["id"] in self.have else pix))
+
+ def show_folder(self):
+ self.folder.setText("Folder: " + str(self.save_dir).replace(str(Path.home()), "~", 1))
+
+ def choose_folder(self):
+ d = QFileDialog.getExistingDirectory(self, "Save wallpapers to", str(self.save_dir))
+ if not d:
+ return
+ self.save_dir = Path(d)
+ self.settings.setValue("save_dir", d)
+ self.show_folder()
+ self.refresh_library()
+ for i in range(self.grid.count()):
+ self.mark(self.grid.item(i))
+
+ def download(self):
+ self.save_dir.mkdir(parents=True, exist_ok=True)
+ gen = self.gen
+ for item in self.grid.selectedItems():
+ w = item.data(ROLE)
+ if w["id"] in self.have:
+ self.already(w)
+ continue
+ self.get(w["path"], lambda d, w=w, item=item: self.save(self.dest(w), d, item, gen, w["id"]))
+
+ def save(self, dest, data, item, gen, wid):
+ if wid in self.have:
+ return # selected twice, or preview and grid download raced
+ # write to a temp name first, so a crash never leaves a truncated wallpaper behind
+ tmp = dest.with_suffix(".part")
+ tmp.write_bytes(data)
+ tmp.rename(dest)
+ self.have[wid] = dest
+ self.statusBar().showMessage(f"saved {dest.name}")
+ if gen == self.gen: # grid not cleared since, so item still alive
+ self.mark(item)
+
+ def find_lowres(self):
+ """List images in the library smaller than the monitor they are meant for."""
+ lst = make_grid()
+ # ponytail: scans and decodes thumbnails synchronously, the UI stalls on folders of
+ # thousands of images; move to a QThread if that ever hurts
+ for p in library_files(*self.roots()):
+ reader = QImageReader(str(p))
+ size = reader.size()
+ if not size.isValid():
+ continue # not an image
+ w, h = size.width(), size.height()
+ i = target(w, h, self.monitors)
+ mw, mh = self.monitors[i]
+ if w >= mw and h >= mh:
+ continue
+ reader.setScaledSize(size.scaled(300, 200, Qt.AspectRatioMode.KeepAspectRatio))
+ item = QListWidgetItem(QIcon(QPixmap.fromImage(reader.read())), f"{w}x{h} < {mw}x{mh}")
+ item.setToolTip(str(p).replace(str(Path.home()), "~", 1))
+ item.setData(ROLE, (str(p), i))
+ lst.addItem(item)
+ if not lst.count():
+ self.statusBar().showMessage("every image in the library covers its monitor")
+ return
+
+ dlg = QDialog(self)
+ dlg.setWindowTitle(f"{lst.count()} low-res wallpapers in the library")
+ dlg.resize(1000, 700)
+ box = QVBoxLayout(dlg)
+ box.addWidget(QLabel("Smaller than the monitor they match. Double-click one to search wallhaven "
+ "at that monitor's size: by its main tag for wallhaven files, by its "
+ "dominant color for anything else."))
+ box.addWidget(lst)
+
+ def similar(item):
+ path, i = item.data(ROLE)
+ m = WALL_ID.match(Path(path).name)
+ dlg.accept()
+ self.reference.show_image(path)
+ self.replace.setVisible(self.preview.isVisible())
+ self.fit.blockSignals(True) # set quietly, the search below runs once
+ self.fit.setCurrentIndex(i)
+ self.fit.blockSignals(False)
+ if m:
+ self.get(f"{API}w/{m[1]}", lambda data: self.search_tag(m[1], data))
+ else:
+ self.search_color(path)
+ lst.itemActivated.connect(similar)
+ dlg.exec()
+
+ def replace_original(self):
+ """Swap the low-res original for the previewed wallpaper: save the new file into the
+ original's folder first, and only then move the original to the trash."""
+ pv, orig = self.pv, Path(self.reference.path)
+ if not self.reference.isVisible() or not orig.exists():
+ self.statusBar().showMessage("no original to replace, open one from \"Find low-res on disk\"")
+ return
+ if not pv["data"]:
+ self.statusBar().showMessage("full image still loading, try again in a moment")
+ return
+ if pv["w"]["id"] in self.have:
+ self.already(pv["w"])
+ return
+ dest = orig.parent / self.dest(pv["w"]).name
+ old = f"{orig.name} ({self.reference.pix.width()}x{self.reference.pix.height()})"
+ folder = str(orig.parent).replace(str(Path.home()), "~", 1)
+ if QMessageBox.question(self, "Replace original",
+ f"Save {dest.name} ({pv['w']['resolution']}) in {folder}\n"
+ f"and move {old} to the trash?") != QMessageBox.StandardButton.Yes:
+ return
+ self.save(dest, pv["data"], pv["item"], pv["gen"], pv["w"]["id"])
+ ok, _ = QFile.moveToTrash(str(orig))
+ if not ok: # the new file is saved either way, nothing is lost
+ self.statusBar().showMessage(f"saved {dest.name}, but could not move {orig.name} to the trash")
+ return
+ self.reference.close()
+ self.replace.hide()
+ self.refresh_library() # the original may have been a wallhaven file too
+ self.statusBar().showMessage(f"replaced {orig.name} with {dest.name}, original is in the trash")
+
+ def search_color(self, path):
+ """Search by the palette color covering most of a local image, wallhaven's own
+ colors filter only takes palette colors. Purity and categories stay as set."""
+ reader = QImageReader(path)
+ reader.setScaledSize(QSize(64, 64)) # plenty for a color histogram
+ img = reader.read()
+ hist = palette_histogram((c.red(), c.green(), c.blue())
+ for c in (img.pixelColor(x, y)
+ for y in range(img.height()) for x in range(img.width())))
+ top = hist.most_common(3)
+ pick = search_pick(hist)
+ self.color.button(pick + 1).setChecked(True) # button ids are offset by "any"
+ self.query.clear()
+ self.search()
+ total = sum(hist.values())
+ self.statusBar().showMessage(f"{Path(path).name}: searching #{COLORS[pick]}, top colors "
+ + ", ".join(f"#{COLORS[i]} {n * 100 // total}%" for i, n in top)
+ + ", click another swatch to change")
+
+ def search_tag(self, wid, data):
+ # ponytail: wallhaven's like:<id> similarity search sits behind a Cloudflare bot
+ # challenge, so search by the wallpaper's first tag instead (usually its most specific)
+ info = json.loads(data)["data"]
+ tags = info["tags"]
+ if not tags:
+ self.statusBar().showMessage(f"wallhaven-{wid} has no tags to search by")
+ return
+ # search the wallpaper's own purity: an NSFW tag finds next to nothing under SFW
+ self.purity.blockSignals(True)
+ self.purity.setCurrentIndex(["sfw", "sketchy", "nsfw"].index(info["purity"]))
+ self.purity.blockSignals(False)
+ self.query.setText(f'id:{tags[0]["id"]}')
+ self.search()
+ self.statusBar().showMessage(f'searching tag "{tags[0]["name"]}" of wallhaven-{wid}...')
+
+
+if __name__ == "__main__":
+ APIKEY = read_apikey()
+ app = QApplication(sys.argv)
+ app.setDesktopFileName("wallhaven-dl") # ties windows to wallhaven-dl.desktop (Wayland app id)
+ # installed theme icon first, else the svg beside the real script (resolve() follows a symlink)
+ app.setWindowIcon(QIcon.fromTheme("wallhaven-dl",
+ QIcon(str(Path(__file__).resolve().with_name("wallhaven-dl.svg")))))
+ win = Main()
+ win.show()
+ sys.exit(app.exec())
diff --git a/wallhaven-dl.desktop b/wallhaven-dl.desktop
new file mode 100644
index 0000000..dad2d0e
--- /dev/null
+++ b/wallhaven-dl.desktop
@@ -0,0 +1,11 @@
+[Desktop Entry]
+Type=Application
+Name=wallhaven-dl
+GenericName=Wallpaper Downloader
+Comment=Search wallhaven.cc and download wallpapers
+Exec=wallhaven-dl
+Icon=wallhaven-dl
+Terminal=false
+Categories=Graphics;Qt;
+Keywords=wallpaper;wallhaven;background;download;
+StartupWMClass=wallhaven-dl
diff --git a/wallhaven-dl.svg b/wallhaven-dl.svg
new file mode 100644
index 0000000..a91df6b
--- /dev/null
+++ b/wallhaven-dl.svg
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- wallhaven-dl icon, styled after the Candy icon theme. Copyright (C) 2026 Danilo M. <danix@danix.xyz>, GPLv2-only. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48">
+ <defs>
+ <linearGradient id="candy" x1="4" y1="6" x2="44" y2="44" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="#ff6fb5"/>
+ <stop offset="0.5" stop-color="#a77bf3"/>
+ <stop offset="1" stop-color="#43d9f0"/>
+ </linearGradient>
+ </defs>
+ <g fill="none" stroke="url(#candy)" stroke-width="4" stroke-linecap="round" stroke-linejoin="round">
+ <!-- picture frame, open at the bottom right where the arrow breaks out -->
+ <path d="M28 39 H10 A6 6 0 0 1 4 33 V12 A6 6 0 0 1 10 6 H38 A6 6 0 0 1 44 12 V22"/>
+ <!-- mountains -->
+ <path d="M10 32 L18 23 L24 29 L28 25"/>
+ <!-- download arrow -->
+ <path d="M37 26 V42 M31.5 36.5 L37 42 L42.5 36.5"/>
+ </g>
+ <!-- sun -->
+ <circle cx="33" cy="15" r="3.5" fill="url(#candy)"/>
+</svg>