pax_global_header 0000666 0000000 0000000 00000000064 15271130355 0014514 g ustar 00root root 0000000 0000000 52 comment=98e70ee4b245d4e92b482b900749ee3297f535f3
phototonic-3.3.0/ 0000775 0000000 0000000 00000000000 15271130355 0013705 5 ustar 00root root 0000000 0000000 phototonic-3.3.0/.gitignore 0000664 0000000 0000000 00000000137 15271130355 0015676 0 ustar 00root root 0000000 0000000 *.exe
phototonic
moc_*.cpp
*.o
*.obj
.qmake.stash
qrc_phototonic.cpp
*.pro.user
Makefile
mingw
phototonic-3.3.0/.travis.yml 0000664 0000000 0000000 00000000513 15271130355 0016015 0 ustar 00root root 0000000 0000000 os: linux
dist: trusty
sudo: true
compiler:
- gcc
addons:
apt:
packages:
- libexiv2-dev
before_install:
- sudo add-apt-repository ppa:beineri/opt-qt58-trusty -y
- sudo apt-get update -q
- sudo apt-get install -y qt58-meta-minimal
script:
- source /opt/qt58/bin/qt58-env.sh
- qmake
- make -j2
phototonic-3.3.0/Bookmarks.cpp 0000664 0000000 0000000 00000005530 15271130355 0016344 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include "Bookmarks.h"
#include "Settings.h"
BookMarks::BookMarks(QWidget *parent) : QTreeWidget(parent) {
setAcceptDrops(true);
setDragEnabled(false);
setDragDropMode(QAbstractItemView::DropOnly);
connect(this, SIGNAL(expanded(const QModelIndex &)),
this, SLOT(resizeTreeColumn(const QModelIndex &)));
connect(this, SIGNAL(collapsed(const QModelIndex &)),
this, SLOT(resizeTreeColumn(const QModelIndex &)));
setColumnCount(1);
setHeaderHidden(true);
reloadBookmarks();
}
void BookMarks::reloadBookmarks() {
clear();
QSetIterator it(Settings::bookmarkPaths);
while (it.hasNext()) {
QString itemPath = it.next();
QTreeWidgetItem *item = new QTreeWidgetItem(this);
item->setText(0, QFileInfo(itemPath).fileName());
item->setIcon(0, QIcon(":/images/bookmarks.png"));
item->setToolTip(0, itemPath);
insertTopLevelItem(0, item);
}
}
void BookMarks::resizeTreeColumn(const QModelIndex &) {
resizeColumnToContents(0);
}
void BookMarks::removeBookmark() {
if (selectedItems().size() == 1) {
Settings::bookmarkPaths.remove(selectedItems().at(0)->toolTip(0));
reloadBookmarks();
}
}
void BookMarks::dragEnterEvent(QDragEnterEvent *event) {
QModelIndexList selectedDirs = selectionModel()->selectedRows();
if (selectedDirs.size() > 0) {
dndOrigSelection = selectedDirs.at(0);
}
event->acceptProposedAction();
}
void BookMarks::dragMoveEvent(QDragMoveEvent *event) {
setCurrentIndex(indexAt(event->position().toPoint()));
}
void BookMarks::dropEvent(QDropEvent *event) {
if (event->source()) {
QString fileSystemTreeStr("FileSystemTree");
bool dirOp = (event->source()->metaObject()->className() == fileSystemTreeStr);
QString path;
if (event->mimeData()->hasUrls())
path = event->mimeData()->urls().at(0).toLocalFile();
emit dropOp(event->modifiers(), dirOp, path);
}
}
phototonic-3.3.0/Bookmarks.h 0000664 0000000 0000000 00000002536 15271130355 0016014 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef BOOKMARKS_H
#define BOOKMARKS_H
#include
class BookMarks : public QTreeWidget {
Q_OBJECT
public:
BookMarks(QWidget *parent);
void reloadBookmarks();
public slots:
void removeBookmark();
private:
QModelIndex dndOrigSelection;
private slots:
void resizeTreeColumn(const QModelIndex &);
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
signals:
void dropOp(Qt::KeyboardModifiers keyMods, bool dirOp, QString cpMvDirPath);
};
#endif // BOOKMARKS_H
phototonic-3.3.0/COPYING 0000664 0000000 0000000 00000104513 15271130355 0014744 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
phototonic-3.3.0/ColorsDialog.cpp 0000664 0000000 0000000 00000023633 15271130355 0017001 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "ImageViewer.h"
#include "ColorsDialog.h"
#include "Settings.h"
ColorsDialog::ColorsDialog(QWidget *parent, ImageViewer *imageViewer) : QDialog(parent), dontApply(false) {
setWindowTitle(tr("Colors"));
setWindowIcon(QIcon(":/images/colors.png"));
resize(350, 300);
this->imageViewer = imageViewer;
QHBoxLayout *buttonsHbox = new QHBoxLayout;
QPushButton *resetButton = new QPushButton(tr("Reset"));
resetButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(resetButton, SIGNAL(clicked()), this, SLOT(reset()));
buttonsHbox->addWidget(resetButton, 0, Qt::AlignLeft);
QPushButton *okButton = new QPushButton(tr("OK"));
okButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(okButton, SIGNAL(clicked()), this, SLOT(ok()));
buttonsHbox->addWidget(okButton, 0, Qt::AlignRight);
okButton->setDefault(true);
auto makeSlider = [this](QString label, QSlider **slider) {
*slider = new QSlider(Qt::Horizontal);
(*slider)->setTickPosition(QSlider::TicksAbove);
(*slider)->setTickInterval(25);
(*slider)->setRange(-100, 100);
(*slider)->setTracking(false);
(*slider)->setToolTip("0");
connect(*slider, &QSlider::valueChanged, [this,slider](int v) {
(*slider)->setToolTip(QString::number(v));
applyColors();
});
connect(*slider, &QSlider::sliderMoved, [this,slider](int v) {
const QString n = QString::number(v);
(*slider)->setToolTip(n);
QToolTip::showText(QCursor::pos(), n, nullptr, QRect(), 0);
});
QAction *zero = new QAction(*slider);
zero->setShortcut(Qt::Key_0);
zero->setShortcutContext(Qt::WidgetWithChildrenShortcut);
connect(zero, &QAction::triggered, [this,slider]() { (*slider)->setValue(0); });
(*slider)->addAction(zero);
return new QLabel(label);
};
/* hue saturation */
QLabel *hueLab = makeSlider(tr("Hue"), &hueSlider);
QLabel *satLab = makeSlider(tr("Saturation"), &saturationSlider);
QLabel *lightLab = makeSlider(tr("Lightness"), &lightnessSlider);
colorizeCheckBox = new QCheckBox(tr("Colorize"), this);
colorizeCheckBox->setCheckState(Settings::colorizeEnabled ? Qt::Checked : Qt::Unchecked);
connect(colorizeCheckBox, SIGNAL(stateChanged(int)), this, SLOT(applyColors()));
rNegateCheckBox = new QCheckBox(tr("Negative"), this);
rNegateCheckBox->setCheckState(Settings::rNegateEnabled ? Qt::Checked : Qt::Unchecked);
connect(rNegateCheckBox, SIGNAL(stateChanged(int)), this, SLOT(applyColors()));
gNegateCheckBox = new QCheckBox(tr("Negative"), this);
gNegateCheckBox->setCheckState(Settings::gNegateEnabled ? Qt::Checked : Qt::Unchecked);
connect(gNegateCheckBox, SIGNAL(stateChanged(int)), this, SLOT(applyColors()));
bNegateCheckBox = new QCheckBox(tr("Negative"), this);
bNegateCheckBox->setCheckState(Settings::bNegateEnabled ? Qt::Checked : Qt::Unchecked);
connect(bNegateCheckBox, SIGNAL(stateChanged(int)), this, SLOT(applyColors()));
QHBoxLayout *channelsHbox = new QHBoxLayout;
redCheckBox = new QCheckBox(tr("Red"));
redCheckBox->setCheckable(true);
redCheckBox->setChecked(Settings::hueRedChannel);
connect(redCheckBox, SIGNAL(clicked()), this, SLOT(applyColors()));
channelsHbox->addWidget(redCheckBox, 0, Qt::AlignLeft);
greenCheckBox = new QCheckBox(tr("Green"));
greenCheckBox->setCheckable(true);
greenCheckBox->setChecked(Settings::hueGreenChannel);
connect(greenCheckBox, SIGNAL(clicked()), this, SLOT(applyColors()));
channelsHbox->addWidget(greenCheckBox, 0, Qt::AlignLeft);
blueCheckBox = new QCheckBox(tr("Blue"));
blueCheckBox->setCheckable(true);
blueCheckBox->setChecked(Settings::hueBlueChannel);
connect(blueCheckBox, SIGNAL(clicked()), this, SLOT(applyColors()));
channelsHbox->addWidget(blueCheckBox, 0, Qt::AlignLeft);
channelsHbox->addStretch(1);
QGridLayout *hueSatLay = new QGridLayout;
hueSatLay->addWidget(hueLab, 1, 0, 1, 1);
hueSatLay->addWidget(hueSlider, 1, 1, 1, 1);
hueSatLay->addWidget(colorizeCheckBox, 2, 1, 1, 1);
hueSatLay->addWidget(satLab, 3, 0, 1, 1);
hueSatLay->addWidget(saturationSlider, 3, 1, 1, 1);
hueSatLay->addWidget(lightLab, 4, 0, 1, 1);
hueSatLay->addWidget(lightnessSlider, 4, 1, 1, 1);
hueSatLay->setColumnMinimumWidth(0, 70);
QGroupBox *hueSatGroup = new QGroupBox(tr("Hue and Saturation"));
hueSatGroup->setLayout(hueSatLay);
QGridLayout *channelsLay = new QGridLayout;
channelsLay->addLayout(channelsHbox, 5, 1, 1, 1);
channelsLay->setColumnMinimumWidth(0, 70);
QGroupBox *channelsGroup = new QGroupBox(tr("Affected Channels"));
channelsGroup->setLayout(channelsLay);
/* brightness contrast */
QLabel *brightLab = makeSlider(tr("Brightness"), &brightSlider);
QLabel *contrastLab = makeSlider(tr("Contrast"), &contrastSlider);
contrastSlider->setInvertedAppearance(true);
QGridLayout *brightContrastbox = new QGridLayout;
brightContrastbox->addWidget(brightLab, 1, 0, 1, 1);
brightContrastbox->addWidget(brightSlider, 1, 1, 1, 1);
brightContrastbox->addWidget(contrastLab, 2, 0, 1, 1);
brightContrastbox->addWidget(contrastSlider, 2, 1, 1, 1);
brightContrastbox->setColumnMinimumWidth(0, 70);
QGroupBox *brightContrastGroup = new QGroupBox(tr("Brightness and Contrast"));
brightContrastGroup->setLayout(brightContrastbox);
/* Channel mixer */
QLabel *redLab = makeSlider(tr("Red"), &redSlider);
QLabel *greenLab = makeSlider(tr("Green"), &greenSlider);
QLabel *blueLab = makeSlider(tr("Blue"), &blueSlider);
QGridLayout *channelMixbox = new QGridLayout;
channelMixbox->addWidget(redLab, 1, 0, 1, 1);
channelMixbox->addWidget(redSlider, 1, 1, 1, 1);
channelMixbox->addWidget(rNegateCheckBox, 1, 2, 1, 1);
channelMixbox->addWidget(greenLab, 2, 0, 1, 1);
channelMixbox->addWidget(greenSlider, 2, 1, 1, 1);
channelMixbox->addWidget(gNegateCheckBox, 2, 2, 1, 1);
channelMixbox->addWidget(blueLab, 3, 0, 1, 1);
channelMixbox->addWidget(blueSlider, 3, 1, 1, 1);
channelMixbox->addWidget(bNegateCheckBox, 3, 2, 1, 1);
channelMixbox->setColumnMinimumWidth(0, 70);
QGroupBox *channelMixGroup = new QGroupBox(tr("Color Balance"));
channelMixGroup->setLayout(channelMixbox);
QVBoxLayout *mainVbox = new QVBoxLayout;
mainVbox->addWidget(brightContrastGroup);
mainVbox->addWidget(channelMixGroup);
mainVbox->addWidget(hueSatGroup);
mainVbox->addWidget(channelsGroup);
mainVbox->addStretch(1);
mainVbox->addLayout(buttonsHbox);
setLayout(mainVbox);
}
void ColorsDialog::applyColors() {
if (dontApply)
return;
if (brightSlider->value() >= 0) {
Settings::brightVal = (brightSlider->value() * 500 / 100) + 100;
} else {
Settings::brightVal = brightSlider->value() + 100;
}
if (contrastSlider->value() >= 0) {
Settings::contrastVal = (contrastSlider->value() * 79 / 100) + 78;
} else {
Settings::contrastVal = contrastSlider->value() + 79;
}
Settings::hueVal = hueSlider->value() * 127 / 100;
if (saturationSlider->value() >= 0) {
Settings::saturationVal = (saturationSlider->value() * 500 / 100) + 100;
} else {
Settings::saturationVal = saturationSlider->value() + 100;
}
if (lightnessSlider->value() >= 0) {
Settings::lightnessVal = (lightnessSlider->value() * 200 / 100) + 100;
} else {
Settings::lightnessVal = lightnessSlider->value() + 100;
}
Settings::redVal = redSlider->value();
Settings::greenVal = greenSlider->value();
Settings::blueVal = blueSlider->value();
Settings::colorizeEnabled = colorizeCheckBox->isChecked();
Settings::rNegateEnabled = rNegateCheckBox->isChecked();
Settings::gNegateEnabled = gNegateCheckBox->isChecked();
Settings::bNegateEnabled = bNegateCheckBox->isChecked();
Settings::hueRedChannel = redCheckBox->isChecked();
Settings::hueGreenChannel = greenCheckBox->isChecked();
Settings::hueBlueChannel = blueCheckBox->isChecked();
imageViewer->refresh();
}
void ColorsDialog::ok() {
Settings::dialogLastX = pos().x();
Settings::dialogLastY = pos().y();
accept();
}
void ColorsDialog::reset() {
dontApply = true;
hueSlider->setValue(0);
colorizeCheckBox->setChecked(false);
rNegateCheckBox->setChecked(false);
gNegateCheckBox->setChecked(false);
bNegateCheckBox->setChecked(false);
saturationSlider->setValue(0);
lightnessSlider->setValue(0);
redCheckBox->setChecked(true);
greenCheckBox->setChecked(true);
blueCheckBox->setChecked(true);
Settings::hueRedChannel = true;
Settings::hueGreenChannel = true;
Settings::hueBlueChannel = true;
contrastSlider->setValue(0);
brightSlider->setValue(0);
redSlider->setValue(0);
greenSlider->setValue(0);
blueSlider->setValue(0);
dontApply = false;
if (isVisible())
applyColors();
}
phototonic-3.3.0/ColorsDialog.h 0000664 0000000 0000000 00000003126 15271130355 0016441 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef COLORS_DIALOG_H
#define COLORS_DIALOG_H
class ImageViewer;
class QCheckBox;
class QSlider;
#include
class ColorsDialog : public QDialog {
Q_OBJECT
public:
ColorsDialog(QWidget *parent, ImageViewer *imageViewer);
public slots:
void reset();
private slots:
void applyColors();
void ok();
private:
ImageViewer *imageViewer;
QSlider *hueSlider;
QCheckBox *colorizeCheckBox;
QSlider *saturationSlider;
QSlider *lightnessSlider;
QCheckBox *redCheckBox;
QCheckBox *greenCheckBox;
QCheckBox *blueCheckBox;
QSlider *brightSlider;
QSlider *contrastSlider;
QSlider *redSlider;
QSlider *greenSlider;
QSlider *blueSlider;
QCheckBox *rNegateCheckBox;
QCheckBox *gNegateCheckBox;
QCheckBox *bNegateCheckBox;
bool dontApply;
};
#endif // COLORS_DIALOG_H phototonic-3.3.0/CopyMoveDialog.cpp 0000664 0000000 0000000 00000041240 15271130355 0017273 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "CopyMoveDialog.h"
#include "MessageBox.h"
#include "MetadataCache.h"
#include "Settings.h"
#include "ThumbsViewer.h"
static QString autoRename(const QString &destDir, const QString &currFile) {
int extSep = currFile.lastIndexOf(".");
QString nameOnly = currFile.left(extSep);
QString extOnly = currFile.right(currFile.size() - extSep - 1);
QString newFile;
int idx = 1;
do {
newFile = QString(nameOnly + "_copy_%1." + extOnly).arg(idx);
++idx;
} while (idx && (QFile::exists(destDir + QDir::separator() + newFile)));
return newFile;
}
int CopyOrMove::file(const QString &srcPath, QString &dstPath, bool copy) {
int res = 0;
if (copy) {
res = QFile::copy(srcPath, dstPath);
} else {
res = QFile::rename(srcPath, dstPath);
}
if (!res && QFile::exists(dstPath)) {
QFileInfo info(dstPath);
QString newName = autoRename(info.absolutePath(), info.fileName());
QString newDestPath = info.absolutePath() + QDir::separator() + newName;
if (copy) {
res = QFile::copy(srcPath, newDestPath);
} else {
res = QFile::rename(srcPath, newDestPath);
}
dstPath = newDestPath;
}
if (res && !copy) {
ThumbsViewer::moveCache(srcPath, dstPath);
Metadata::rename(srcPath, dstPath);
}
return res;
}
static QPixmap loadPreview(QString path, QSize &realSize) {
QImageReader reader;
reader.setQuality(50);
reader.setFileName(path);
realSize = reader.size();
QSize thumbSize = realSize;
thumbSize.scale(QSize(256,256), Qt::KeepAspectRatio);
reader.setScaledSize(thumbSize);
reader.setAutoTransform(false);
return QPixmap::fromImageReader(&reader);
}
struct ImagePrint {
QPixmap pix;
QString stats;
};
class EnterGuard : public QObject {
public:
EnterGuard(QWidget *guarded) : QObject(guarded), watch(false), m_guarded(guarded) {}
bool watch;
protected:
bool eventFilter(QObject *o, QEvent *e) {
if (o == m_guarded && (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease)) {
int key = static_cast(e)->key();
if (key == Qt::Key_Enter || key == Qt::Key_Return) {
e->accept();
return watch;
}
}
return false;
}
private:
QWidget *m_guarded;
};
QDialog::DialogCode CopyOrMove::resolveConflicts(QMap &collisions, QWidget *parent) {
QDialog *dlg = new QDialog(parent);
QLabel *srcPreview = new QLabel, *dstPreview = new QLabel, *srcStats = new QLabel, *dstStats = new QLabel;
QLabel *arrow = new QLabel(">");
arrow->setAlignment(Qt::AlignCenter);
QFont fnt = arrow->font();
fnt.setBold(true);
fnt.setPointSize(fnt.pointSize()*4);
arrow->setFont(fnt);
srcStats->setAlignment(Qt::AlignRight);
QStringList headers = QObject::tr("Skip,Replace,Index,Rename,Filename").split(',');
QTableWidget *table = new QTableWidget(collisions.size(), headers.size()); // skip, overwrite, autoRename, rename, src, dst
table->setHorizontalHeaderLabels(headers);
table->setVerticalHeader(nullptr);
int i = 0;
for (auto c = collisions.cbegin(), end = collisions.cend(); c != end; ++c, ++i) {
for (int j = 0; j < table->columnCount() - 1; ++j) {
QTableWidgetItem *item = new QTableWidgetItem;
item->setFlags(j ? Qt::ItemIsEnabled|Qt::ItemIsUserCheckable : Qt::ItemIsEnabled);
item->setCheckState(j ? Qt::Unchecked : Qt::Checked);
if (!j)
item->setToolTip(c.key());
table->setItem(i, j, item);
}
QTableWidgetItem *item = new QTableWidgetItem(QFileInfo(*c).fileName());
item->setToolTip(*c);
item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable|Qt::ItemIsEditable);
table->setItem(i, table->columnCount() - 1, item);
}
table->verticalHeader()->setVisible(false);
table->horizontalHeader()->setStretchLastSection(true);
table->resizeColumnsToContents();
table->setShowGrid(false);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::SingleSelection);
EnterGuard *enterGuard = new EnterGuard(table);
table->installEventFilter(enterGuard);
auto setArrow = [=](int col) {
if (col == 0) {
arrow->setText("><<");
dstPreview->setGraphicsEffect(nullptr);
} else if (col == 1) {
QGraphicsOpacityEffect *magic = new QGraphicsOpacityEffect(dstPreview);
dstPreview->setGraphicsEffect(magic);
magic->setOpacity(0.5);
arrow->setText("<<<");
} else {
arrow->setText("^_^");
dstPreview->setGraphicsEffect(nullptr);
}
};
QObject::connect(table, &QTableWidget::cellChanged, [=](int row, int column) {
QTableWidgetItem *it = table->item(row, column);
if (column == table->columnCount() - 1) {
// name changed, toggle rename
QFileInfo info(table->item(row, column)->toolTip());
if (QFileInfo::exists(info.absolutePath() + QDir::separator() + table->item(row, column)->text())) {
MessageBox(dlg).warning(QObject::tr("New file also exists"),
QObject::tr("The new filename also conflicts with an existing file.\n"
"The existing file would be overwritten!"));
table->item(row, 0)->setCheckState(Qt::Checked);
} else {
table->item(row, column - 1)->setCheckState(Qt::Checked);
}
} else {
// radio feature
if (it->checkState() != Qt::Checked)
return;
table->blockSignals(true);
if (column == table->columnCount()-2) {
int dst = table->columnCount()-1;
QTableWidgetItem *dit = table->item(row, dst);
QFileInfo info(dit->toolTip());
// allow user to fix the destination
if (QFileInfo::exists(info.absolutePath() + QDir::separator() + dit->text())) {
dit->setText("0_0 " + dit->text());
table->setCurrentItem(dit);
table->setFocus();
enterGuard->watch = true;
table->editItem(dit);
}
}
it->setFlags((it->flags() & ~Qt::ItemIsUserCheckable));
for (int j = 0; j < table->columnCount() - 1; ++j) {
if (j == column)
continue;
it = table->item(row, j);
it->setCheckState(Qt::Unchecked);
it->setFlags((it->flags() | Qt::ItemIsUserCheckable));
}
if (row == table->currentRow())
setArrow(column);
table->blockSignals(false);
}
});
static QMap pixMap;
QObject::connect(table, &QTableWidget::currentCellChanged, [=](int row, int /* column */, int prevR, int /* prevC */) {
enterGuard->watch = false;
if (row != prevR) {
for (int i = 0; i < 4; ++i) {
if (table->item(row, i)->checkState() == Qt::Checked) {
setArrow(i);
break;
}
}
for (int i : { 0, 4 }) {
QString path = table->item(row, i)->toolTip();
ImagePrint ip = pixMap.value(path);
if (ip.pix.isNull()) {
QSize sz;
ip.pix = loadPreview(path, sz);
QFileInfo info(path);
QFile f(path);
Q_UNUSED(f.open(QFile::ReadOnly));
QCryptographicHash md5(QCryptographicHash::Md5);
md5.addData(&f);
ip.stats = QString::number(info.size() / 1024.0, 'f', 2) + "K\n"
+ info.lastModified().toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat)) + "\n"
+ QString::number(sz.width()) + "x" + QString::number(sz.height()) + "\n"
+ QString::fromLatin1(md5.result().toHex());
f.close();
pixMap[path] = ip;
}
i ? dstPreview->setPixmap(ip.pix) : srcPreview->setPixmap(ip.pix);
i ? dstStats->setText(ip.stats) : srcStats->setText(ip.stats);
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
});
dlg->setModal(true);
dlg->setWindowTitle(QObject::tr("File collision resolver"));
QVBoxLayout *vl = new QVBoxLayout(dlg);
vl->addWidget(new QLabel(QObject::tr("Some of the destination files already exist
"
"You can resolve the conflicts here or abort the entire copy/move operation.
"
"By default, the conflicting files will be skipped.
"
"You can also replace or rename the destination, or automatically add a counter for a conflict-free filename."), dlg));
vl->addWidget(table);
QGridLayout *glt = new QGridLayout;
glt->addWidget(dstPreview, 0, 0);
glt->addWidget(arrow, 0, 1, Qt::AlignCenter);
glt->addWidget(srcPreview, 0, 2);
glt->addWidget(dstStats, 1, 0);
QLabel *legend = new QLabel(QObject::tr("Size") + "\n" + QObject::tr("Modified") + "\n" + QObject::tr("Resolution") + "\n" + QObject::tr("MD5"));
legend->setAlignment(Qt::AlignHCenter);
glt->addWidget(legend, 1, 1);
glt->addWidget(srcStats, 1, 2);
vl->addLayout(glt);
QDialogButtonBox *btns = new QDialogButtonBox(QDialogButtonBox::Abort|QDialogButtonBox::Ok, dlg);
vl->addWidget(btns);
QObject::connect(btns, &QDialogButtonBox::accepted, dlg, &QDialog::accept);
QObject::connect(btns, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
const QSizeF sz = QFontMetrics(dlg->font()).boundingRect('o').size();
dlg->resize(sz.width() * 100, sz.width() * 100);
int ret = dlg->exec();
pixMap.clear();
// fix collisions regardless of return, nobody knows what the client code wants with this
i = 0;
for (auto c = collisions.begin(), end = collisions.end(); c != end; ++i) {
if (table->item(i, 0)->checkState() == Qt::Checked) { // skip
c = collisions.erase(c);
continue;
} else if (table->item(i, 2)->checkState() == Qt::Checked) { // auto-rename
QFileInfo info(*c);
*c = info.absolutePath() + QDir::separator() + autoRename(info.absolutePath(), info.fileName());
} else if (table->item(i, 3)->checkState() == Qt::Checked) { // manual rename
QFileInfo info(*c);
*c = info.absolutePath() + QDir::separator() + table->item(i, 4)->text();
}
++c;
}
dlg->deleteLater();
return QDialog::DialogCode(ret);
}
int CopyOrMove::list(ThumbsViewer *thumbView, QString &destDir, bool pasteInCurrDir, QWidget *parent) {
QList rowList; // Only for !pasteInCurrDir
QElapsedTimer duration;
int totalTime = 0;
duration.start();
int cycle = 1;
QProgressDialog *pdlg = nullptr;
QLabel *pdlg_label = nullptr;
int n = pasteInCurrDir ? Settings::copyCutFileList.size() : Settings::copyCutIndexList.size();
QMap collisions;
for (int i = 0; i < n; ++i) {
QString sourceFile = pasteInCurrDir ? Settings::copyCutFileList.at(i)
: thumbView->fullPathOf(Settings::copyCutIndexList.at(i).row());
QString destFile = destDir + QDir::separator() + QFileInfo(sourceFile).fileName();
if (QFileInfo::exists(destFile))
collisions[sourceFile] = destFile;
}
if (!collisions.isEmpty()) {
if (resolveConflicts(collisions, parent) == QDialog::Rejected)
return -1;
}
QFileInfoList newThumbs;
for (int i = pasteInCurrDir ? 0 : n-1; pasteInCurrDir ? i < n : i >= 0; pasteInCurrDir ? ++i : --i) {
QString sourceFile = pasteInCurrDir ? Settings::copyCutFileList.at(i)
: thumbView->fullPathOf(Settings::copyCutIndexList.at(i).row());
QString destFile = destDir + QDir::separator() + QFileInfo(sourceFile).fileName();
if (duration.elapsed() > 30) {
const int count = pasteInCurrDir ? i : n - i;
if ((totalTime += duration.elapsed()) > 250) {
totalTime = 0;
if (float(count)/n < 1.0f-1.0f/++cycle) {
if (!pdlg) {
pdlg = new QProgressDialog(parent);
pdlg->setMaximum(n);
QLabel *l = new QLabel(pdlg);
pdlg_label = l;
l->setWordWrap(true);
l->setFixedWidth(QFontMetrics(l->font()).averageCharWidth()*80);
pdlg->setLabel(l);
}
pdlg->show();
}
}
if (pdlg && pdlg->isVisible()) {
pdlg->setValue(count);
QFontMetrics fm(pdlg_label->font());
QString text =
(Settings::isCopyOperation ? QObject::tr("Copying \"%1\" to \"%2\".") : QObject::tr("Moving \"%1\" to \"%2\"."))
.arg(fm.elidedText(sourceFile, Qt::ElideMiddle, pdlg_label->width(), Qt::TextWordWrap))
.arg(fm.elidedText(destFile, Qt::ElideMiddle, pdlg_label->width(), Qt::TextWordWrap));
pdlg->setLabelText(text);
}
thumbView->addThumbs(newThumbs);
newThumbs.clear();
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
duration.restart();
}
if (QFileInfo::exists(destFile)) {
destFile = collisions.value(sourceFile);
if (destFile.isEmpty() || sourceFile == destFile)
continue; // skipped
if (QFileInfo::exists(destFile)) { // overwrite
if (pasteInCurrDir) {
QModelIndexList indexList = thumbView->model()->match(thumbView->model()->index(0, 0), ThumbsViewer::FileNameRole, destFile);
if (indexList.size())
thumbView->model()->removeRow(indexList.at(0).row());
}
QFile::remove(destFile); // prevent subsequent autorename by copyOrMoveFile
}
}
int res = CopyOrMove::file(sourceFile, destFile, Settings::isCopyOperation);
if (!res || (pdlg && pdlg->wasCanceled()))
break;
if (pasteInCurrDir) {
Settings::copyCutFileList[i] = destFile;
newThumbs << QFileInfo(destFile);
} else {
rowList.append(Settings::copyCutIndexList.at(i).row());
}
}
thumbView->addThumbs(newThumbs);
int latestRow = -1;
if (!pasteInCurrDir) {
if (!Settings::isCopyOperation) {
std::sort(rowList.begin(), rowList.end());
QSignalBlocker scrollbarBlocker(thumbView->verticalScrollBar()); // to not trigger thumb loading
for (int t = rowList.size() - 1; t >= 0; --t)
thumbView->model()->removeRow(rowList.at(t));
}
latestRow = rowList.size() ? rowList.at(0) : -1;
}
if (pdlg)
pdlg->deleteLater();
pdlg = nullptr;
return latestRow;
}
phototonic-3.3.0/CopyMoveDialog.h 0000664 0000000 0000000 00000002700 15271130355 0016736 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef COPY_MOVE_DIALOG_H
#define COPY_MOVE_DIALOG_H
class ThumbsViewer;
namespace CopyOrMove {
int file(const QString &srcPath, QString &dstPath, bool copy);
inline int copyFile(const QString &srcPath, QString &dstPath) {
return CopyOrMove::file(srcPath, dstPath, true);
}
inline int moveFile(const QString &srcPath, QString &dstPath) {
return CopyOrMove::file(srcPath, dstPath, false);
}
QDialog::DialogCode resolveConflicts(QMap &collisions, QWidget *parent = nullptr);
/** @return latestRow **/
int list(ThumbsViewer *thumbView, QString &destDir, bool pasteInCurrDir, QWidget *parent = nullptr);
}
#endif // COPY_MOVE_DIALOG_H
phototonic-3.3.0/CopyMoveToDialog.cpp 0000664 0000000 0000000 00000014361 15271130355 0017602 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov - oferkv@live.com
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include "CopyMoveToDialog.h"
#include "Settings.h"
#if __cplusplus >= 202002L
#define _LCD_ =,this
#else
#define _LCD_ =
#endif
static QStringList gs_tmpPaths;
void CopyMoveToDialog::savePaths() {
Settings::bookmarkPaths.clear();
for (int i = 0; i < pathsTableModel->rowCount(); ++i) {
if (QStandardItem *bookmark = pathsTableModel->item(i))
Settings::bookmarkPaths.insert(bookmark->text());
}
}
static QIcon &folderIcon() {
static QIcon icon = QIcon::fromTheme("folder");
return icon;
}
void CopyMoveToDialog::add() {
QString dirName = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), currentPath,
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dirName.isEmpty()) {
return;
}
if (!gs_tmpPaths.contains(dirName))
gs_tmpPaths << dirName;
QStandardItem *item = new QStandardItem(folderIcon(), dirName);
pathsTableModel->insertRow(pathsTableModel->rowCount(), item);
pathsTable->selectionModel()->clearSelection();
pathsTable->selectionModel()->select(pathsTableModel->index(pathsTableModel->rowCount() - 1, 0),
QItemSelectionModel::Select);
}
void CopyMoveToDialog::closeEvent(QCloseEvent *event) {
savePaths();
QDialog::closeEvent(event);
}
CopyMoveToDialog::CopyMoveToDialog(QWidget *parent, QString thumbsPath, bool copyOp) : QDialog(parent) {
if (copyOp) {
setWindowTitle(tr("Copy to..."));
setWindowIcon(QIcon::fromTheme("edit-copy"));
} else {
setWindowTitle(tr("Move to..."));
setWindowIcon(QIcon::fromTheme("go-next"));
}
const int w = QFontMetrics(font()).averageCharWidth()*60;
resize(w, 10*w/16);
currentPath = thumbsPath;
pathsTable = new QTableView(this);
pathsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
pathsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
pathsTable->setSelectionMode(QAbstractItemView::SingleSelection);
pathsTableModel = new QStandardItemModel(this);
pathsTable->setModel(pathsTableModel);
pathsTable->verticalHeader()->setVisible(false);
pathsTable->horizontalHeader()->setVisible(false);
pathsTable->verticalHeader()->setDefaultSectionSize(pathsTable->verticalHeader()->minimumSectionSize());
pathsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
pathsTable->horizontalHeader()->setStretchLastSection(true);
pathsTable->setShowGrid(false);
connect(pathsTable->selectionModel(), &QItemSelectionModel::selectionChanged, [this](){
m_destination = QString();
QModelIndexList indexesList;
QStandardItem *item;
if ((indexesList = pathsTable->selectionModel()->selectedIndexes()).size() &&
(item = pathsTableModel->itemFromIndex(indexesList.first())))
m_destination = item->text();
destinationLabel->setText(m_destination);
});
connect(pathsTable, &QTableView::doubleClicked, this, [this](){ m_destination.isEmpty() ? reject() : accept(); });
QVBoxLayout *addRemoveBox = new QVBoxLayout;
QPushButton *addButton = new QPushButton(tr("Browse..."));
connect(addButton, SIGNAL(clicked()), this, SLOT(add()));
addRemoveBox->addWidget(addButton, 0);
QPushButton *removeButton = new QPushButton(tr("Delete Bookmark"));
connect(removeButton, &QPushButton::clicked, this, [_LCD_]() {
QModelIndexList indexesList;
if ((indexesList = pathsTable->selectionModel()->selectedIndexes()).size())
pathsTableModel->removeRow(indexesList.first().row());
});
addRemoveBox->addWidget(removeButton, 0);
addRemoveBox->addStretch(1);
QHBoxLayout *buttonsHbox = new QHBoxLayout;
QPushButton *cancelButton = new QPushButton(tr("Cancel"));
connect(cancelButton, &QPushButton::clicked, this, [this](){ reject(); });
QPushButton *okButton = new QPushButton(copyOp ? tr("Copy") : tr("Move"));
okButton->setDefault(true);
connect(addButton, SIGNAL(clicked()), okButton, SLOT(setFocus()));
connect(okButton, &QPushButton::clicked, this, [this](){ m_destination.isEmpty() ? reject() : accept(); });
buttonsHbox->addStretch(1);
buttonsHbox->addWidget(cancelButton, 0);
buttonsHbox->addWidget(okButton, 0);
destinationLabel = new QLabel(this);
destinationLabel->setAlignment(Qt::AlignCenter);
QFont fnt = destinationLabel->font();
if (fnt.pointSize() > 0)
fnt.setPointSize(8*fnt.pointSize()/5);
else
fnt.setPixelSize(8*fnt.pixelSize()/5);
destinationLabel->setFont(fnt);
QHBoxLayout *pathsBox = new QHBoxLayout;
pathsBox->addWidget(pathsTable);
pathsBox->addLayout(addRemoveBox);
QVBoxLayout *mainVbox = new QVBoxLayout;
mainVbox->addLayout(pathsBox);
mainVbox->addWidget(new QLabel(tr("Destination:")));
mainVbox->addWidget(destinationLabel);
mainVbox->addLayout(buttonsHbox);
setLayout(mainVbox);
// Load paths list
for (const QString &s : Settings::bookmarkPaths)
pathsTableModel->insertRow(pathsTableModel->rowCount(), new QStandardItem(QIcon(":/images/bookmarks.png"), s));
for (const QString &s : gs_tmpPaths)
pathsTableModel->insertRow(pathsTableModel->rowCount(), new QStandardItem(folderIcon(), s));
pathsTableModel->sort(0);
}
phototonic-3.3.0/CopyMoveToDialog.h 0000664 0000000 0000000 00000002644 15271130355 0017250 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov - oferkv@live.com
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef COPY_MOVE_TO_DIALOG_H
#define COPY_MOVE_TO_DIALOG_H
class QLabel;
class QStandardItemModel;
class QTableView;
#include
#include
class CopyMoveToDialog : public QDialog {
Q_OBJECT
public:
CopyMoveToDialog(QWidget *parent, QString thumbsPath, bool copyOp);
const QString &destination() const { return m_destination; }
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void add();
private:
void savePaths();
QTableView *pathsTable;
QStandardItemModel *pathsTableModel;
QString currentPath;
QString m_destination;
QLabel *destinationLabel;
};
#endif // COPY_MOVE_TO_DIALOG_H phototonic-3.3.0/CropDialog.cpp 0000664 0000000 0000000 00000010732 15271130355 0016437 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include "CropDialog.h"
#include "Settings.h"
CropDialog::CropDialog(QWidget *parent) : QDialog(parent) {
//: Like a bad dvd where you get a black frame around the image
setWindowTitle(tr("Letterbox"));
setWindowIcon(QIcon(":/images/crop.png"));
resize(350, 100);
if (Settings::dialogLastX)
move(Settings::dialogLastX, Settings::dialogLastY);
QHBoxLayout *buttonsHbox = new QHBoxLayout;
QPushButton *resetButton = new QPushButton(tr("Reset"));
connect(resetButton, SIGNAL(clicked()), this, SLOT(reset()));
QPushButton *okButton = new QPushButton(tr("OK"));
connect(okButton, SIGNAL(clicked()), this, SLOT(ok()));
okButton->setDefault(true);
buttonsHbox->addWidget(resetButton, 0, Qt::AlignLeft);
buttonsHbox->addWidget(okButton, 0, Qt::AlignRight);
QSlider *topSlide = nullptr, *bottomSlide = nullptr, *leftSlide = nullptr, *rightSlide = nullptr;
auto setupSliders = [this](QSlider **sliderp, QSpinBox **spinboxp) {
QSlider *slider = new QSlider(Qt::Horizontal, this);
slider->setTickPosition(QSlider::TicksAbove);
slider->setTickInterval(10);
slider->setTracking(true);
slider->setRange(0, 100);
QSpinBox *spinbox = new QSpinBox(this);
spinbox->setPrefix("% ");
spinbox->setRange(0, 100);
connect(slider, &QSlider::valueChanged, spinbox, &QSpinBox::setValue);
connect(spinbox, &QSpinBox::valueChanged, slider, &QSlider::setValue);
connect(spinbox, &QSpinBox::valueChanged, this, &CropDialog::emitValues);
*sliderp = slider;
*spinboxp = spinbox;
};
setupSliders(&leftSlide, &leftSpinBox);
setupSliders(&topSlide, &topSpinBox);
setupSliders(&rightSlide, &rightSpinBox);
setupSliders(&bottomSlide, &bottomSpinBox);
QGridLayout *mainGbox = new QGridLayout;
mainGbox->addWidget(new QLabel(tr("Left"), this), 0, 0, 1, 1);
mainGbox->addWidget(leftSlide, 0, 1, 1, 1);
mainGbox->addWidget(leftSpinBox, 0, 2, 1, 1);
mainGbox->addWidget(new QLabel(tr("Right"), this), 1, 0, 1, 1);
mainGbox->addWidget(rightSlide, 1, 1, 1, 1);
mainGbox->addWidget(rightSpinBox, 1, 2, 1, 1);
mainGbox->addWidget(new QLabel(tr("Top"), this), 2, 0, 1, 1);
mainGbox->addWidget(topSlide, 2, 1, 1, 1);
mainGbox->addWidget(topSpinBox, 2, 2, 1, 1);
mainGbox->addWidget(new QLabel(tr("Bottom"), this), 3, 0, 1, 1);
mainGbox->addWidget(bottomSlide, 3, 1, 1, 1);
mainGbox->addWidget(bottomSpinBox, 3, 2, 1, 1);
QVBoxLayout *mainVbox = new QVBoxLayout;
mainVbox->addLayout(mainGbox);
mainVbox->addLayout(buttonsHbox);
setLayout(mainVbox);
}
void CropDialog::emitValues()
{
if (sender() == leftSpinBox && leftSpinBox->value() + rightSpinBox->value() > 100)
rightSpinBox->setValue(100-leftSpinBox->value());
if (sender() == rightSpinBox && leftSpinBox->value() + rightSpinBox->value() > 100)
leftSpinBox->setValue(100-rightSpinBox->value());
if (sender() == topSpinBox && topSpinBox->value() + bottomSpinBox->value() > 100)
bottomSpinBox->setValue(100-topSpinBox->value());
if (sender() == bottomSpinBox && topSpinBox->value() + bottomSpinBox->value() > 100)
topSpinBox->setValue(100-bottomSpinBox->value());
emit valuesChanged(leftSpinBox->value(), topSpinBox->value(), rightSpinBox->value(), bottomSpinBox->value());
}
void CropDialog::ok() {
Settings::dialogLastX = pos().x();
Settings::dialogLastY = pos().y();
accept();
}
void CropDialog::reset() {
leftSpinBox->setValue(0);
rightSpinBox->setValue(0);
topSpinBox->setValue(0);
bottomSpinBox->setValue(0);
} phototonic-3.3.0/CropDialog.h 0000664 0000000 0000000 00000002344 15271130355 0016104 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef CROP_DIALOG_H
#define CROP_DIALOG_H
class ImageViewer;
class QSpinBox;
#include
class CropDialog : public QDialog {
Q_OBJECT
public:
CropDialog(QWidget *parent);
signals:
void valuesChanged(int left, int top, int right, int bottom);
private slots:
void ok();
void reset();
void emitValues();
private:
QSpinBox *topSpinBox;
QSpinBox *bottomSpinBox;
QSpinBox *leftSpinBox;
QSpinBox *rightSpinBox;
};
#endif // CROP_DIALOG_H phototonic-3.3.0/CropRubberband.cpp 0000664 0000000 0000000 00000013537 15271130355 0017314 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov - oferkv@live.com
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include "CropRubberband.h"
CropRubberBand::CropRubberBand(QWidget *parent) : QWidget(parent) {
setWindowFlags(Qt::SubWindow);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setContentsMargins(0, 0, 0, 0);
QHBoxLayout *topLayout = new QHBoxLayout();
topLayout->setContentsMargins(0, 0, 0, 0);
QHBoxLayout *bottomLayout = new QHBoxLayout();
bottomLayout->setContentsMargins(0, 0, 0, 0);
QSizeGrip *grip = new QSizeGrip(this);
QPalette pal = grip->palette();
pal.setColor(grip->backgroundRole(), Qt::transparent);
pal.setColor(grip->foregroundRole(), Qt::transparent);
grip->setPalette(pal);
topLayout->addWidget(grip, 0, Qt::AlignTop | Qt::AlignLeft);
grip = new QSizeGrip(this); grip->setPalette(pal);
topLayout->addWidget(grip, 1, Qt::AlignTop | Qt::AlignRight);
grip = new QSizeGrip(this); grip->setPalette(pal);
bottomLayout->addWidget(grip, 0, Qt::AlignBottom | Qt::AlignLeft);
grip = new QSizeGrip(this); grip->setPalette(pal);
bottomLayout->addWidget(grip, 1, Qt::AlignBottom | Qt::AlignRight);
mainLayout->addLayout(topLayout);
mainLayout->addLayout(bottomLayout);
setFocusPolicy(Qt::ClickFocus);
rubberband = new QRubberBand(QRubberBand::Rectangle, this);
rubberband->show();
}
void CropRubberBand::showEvent(QShowEvent *) {
setFocus();
}
void CropRubberBand::keyPressEvent(QKeyEvent *event) {
QPoint cursorPosGlobal = QCursor::pos();
QPoint cursorPos = mapFromGlobal(cursorPosGlobal);
QRect geom = geometry();
// qDebug() << "cursor" << cursorPos << "geom" << geom;
switch (event->key()) {
case Qt::LeftArrow:
case Qt::Key_H:
if (cursorPos.x() > -10 && cursorPos.x() < 10) {
geom.setLeft(geom.left() - 1);
QCursor::setPos(cursorPosGlobal.x() - 1, cursorPosGlobal.y());
} else if (cursorPos.x() > width() - 10 && cursorPos.x() < width() + 10) {
geom.setRight(geom.right() - 1);
QCursor::setPos(cursorPosGlobal.x() - 1, cursorPosGlobal.y());
} else if (QRect(geom).translated(-geom.x(), -geom.y()).contains(cursorPos)) {
geom.moveLeft(geom.x() - 1);
}
setGeometry(geom);
emit selectionChanged(geom);
event->accept();
break;
case Qt::DownArrow:
case Qt::Key_J:
if (cursorPos.y() > -10 && cursorPos.y() < 10) {
geom.setTop(geom.top() + 1);
QCursor::setPos(cursorPosGlobal.x(), cursorPosGlobal.y() + 1);
} else if (cursorPos.y() > height() - 10 && cursorPos.y() < height() + 10) {
geom.setBottom(geom.bottom() + 1);
QCursor::setPos(cursorPosGlobal.x(), cursorPosGlobal.y() + 1);
} else if (QRect(geom).translated(-geom.x(), -geom.y()).contains(cursorPos)) {
geom.moveTop(geom.top() + 1);
}
setGeometry(geom);
emit selectionChanged(geom);
event->accept();
break;
case Qt::UpArrow:
case Qt::Key_K:
if (cursorPos.y() > -10 && cursorPos.y() < 10) {
geom.setTop(geom.top() - 1);
QCursor::setPos(cursorPosGlobal.x(), cursorPosGlobal.y() - 1);
} else if (cursorPos.y() > height() - 10 && cursorPos.y() < height() + 10) {
geom.setBottom(geom.bottom() - 1);
QCursor::setPos(cursorPosGlobal.x(), cursorPosGlobal.y() - 1);
} else if (QRect(geom).translated(-geom.x(), -geom.y()).contains(cursorPos)) {
geom.moveTop(geom.top() - 1);
}
setGeometry(geom);
emit selectionChanged(geom);
event->accept();
break;
case Qt::RightArrow:
case Qt::Key_L:
if (cursorPos.x() > -10 && cursorPos.x() < 10) {
geom.setLeft(geom.left() + 1);
QCursor::setPos(cursorPosGlobal.x() + 1, cursorPosGlobal.y());
} else if (cursorPos.x() > width() - 10 && cursorPos.x() < width() + 10) {
geom.setRight(geom.right() + 1);
QCursor::setPos(cursorPosGlobal.x() + 1, cursorPosGlobal.y());
} else if (QRect(geom).translated(-geom.x(), -geom.y()).contains(cursorPos)) {
geom.moveLeft(geom.x() + 1);
}
setGeometry(geom);
emit selectionChanged(geom);
event->accept();
break;
}
}
void CropRubberBand::resizeEvent(QResizeEvent *) {
rubberband->resize(size());
emit selectionChanged(geometry());
}
void CropRubberBand::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
emit cropConfirmed();
hide();
}
}
void CropRubberBand::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
prevPos = event->globalPosition().toPoint();
else if (event->button() == Qt::RightButton)
hide();
}
void CropRubberBand::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
move(pos() + (event->globalPosition().toPoint() - prevPos));
prevPos = event->globalPosition().toPoint();
emit selectionChanged(geometry());
}
}
phototonic-3.3.0/CropRubberband.h 0000664 0000000 0000000 00000002666 15271130355 0016762 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov - oferkv@live.com
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef CROPRUBBERBAND_H
#define CROPRUBBERBAND_H
class QRubberBand;
#include
class CropRubberBand : public QWidget {
Q_OBJECT
public:
CropRubberBand(QWidget *parent = nullptr);
signals:
void cropConfirmed();
void selectionChanged(QRect sel);
protected:
void showEvent(QShowEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void resizeEvent(QResizeEvent *) override;
private:
QRubberBand *rubberband;
QPoint prevPos;
};
#endif // CROPRUBBERBAND_H
phototonic-3.3.0/DirCompleter.cpp 0000664 0000000 0000000 00000002427 15271130355 0017007 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2015 Thomas Lübking
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include "DirCompleter.h"
DirCompleter::DirCompleter(QObject *parent, QFileSystemModel *model) : QCompleter(parent)
{
setModel(model);
}
QString DirCompleter::pathFromIndex(const QModelIndex &index) const
{
return QCompleter::pathFromIndex(index) + "/";
}
QStringList DirCompleter::splitPath(const QString &path) const
{
if (path.startsWith("~")) {
return QCompleter::splitPath(QString(path).replace(0, 1, QDir::homePath()));
}
return QCompleter::splitPath(path);
}
phototonic-3.3.0/DirCompleter.h 0000664 0000000 0000000 00000002210 15271130355 0016442 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2015 Thomas Lübking
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef DIR_COMPLETER_H
#define DIR_COMPLETER_H
class QFileSystemModel;
#include
class DirCompleter : public QCompleter {
Q_OBJECT
public:
DirCompleter(QObject *parent = 0, QFileSystemModel *model = 0);
QString pathFromIndex(const QModelIndex &index) const;
public slots:
QStringList splitPath(const QString &path) const;
};
#endif // DIR_COMPLETER_H
phototonic-3.3.0/ExternalAppsDialog.cpp 0000664 0000000 0000000 00000015216 15271130355 0020144 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "ExternalAppsDialog.h"
#include "Settings.h"
ExternalAppsDialog::ExternalAppsDialog(QWidget *parent) : QDialog(parent) {
setWindowTitle(tr("Manage External Applications"));
setWindowIcon(QIcon::fromTheme("preferences-other", QIcon(":/images/phototonic.png")));
resize(512, 256);
appsTable = new QTableView(this);
appsTable->setSelectionBehavior(QAbstractItemView::SelectItems);
appsTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
appsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
appsTableModel = new QStandardItemModel(this);
appsTable->setModel(appsTableModel);
appsTable->verticalHeader()->setVisible(false);
appsTable->verticalHeader()->setDefaultSectionSize(appsTable->verticalHeader()->minimumSectionSize());
appsTableModel->setHorizontalHeaderItem(0, new QStandardItem(QString(tr("Name"))));
appsTableModel->setHorizontalHeaderItem(1,
new QStandardItem(QString(tr("Application path and arguments"))));
appsTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);
appsTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
appsTable->setShowGrid(false);
QVBoxLayout *externalAppsLayout = new QVBoxLayout;
//: open an existing executable
QPushButton *addButton = new QPushButton(tr("Pick Executable..."));
connect(addButton, SIGNAL(clicked()), this, SLOT(add()));
externalAppsLayout->addWidget(addButton, 0, Qt::AlignTop);
QPushButton *entryButton = new QPushButton(tr("Add manually"));
connect(entryButton, SIGNAL(clicked()), this, SLOT(entry()));
externalAppsLayout->addWidget(entryButton, 0, Qt::AlignTop);
QPushButton *removeButton = new QPushButton(tr("Delete"));
connect(removeButton, SIGNAL(clicked()), this, SLOT(remove()));
externalAppsLayout->addWidget(removeButton, 0, Qt::AlignTop);
externalAppsLayout->addStretch(1);
QHBoxLayout *wrapperLayout = new QHBoxLayout;
wrapperLayout->addWidget(appsTable);
wrapperLayout->addLayout(externalAppsLayout);
QHBoxLayout *wallpaperLayout = new QHBoxLayout;
wallpaperLayout->addWidget(new QLabel(tr("Wallpaper command")));
wallpaperLayout->addWidget(m_wallpaperCommand = new QComboBox);
QHBoxLayout *buttonsLayout = new QHBoxLayout;
QPushButton *okButton = new QPushButton(tr("OK"));
okButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(okButton, SIGNAL(clicked()), this, SLOT(ok()));
buttonsLayout->addWidget(okButton, 0, Qt::AlignRight);
QVBoxLayout *externalAppsMainLayout = new QVBoxLayout;
externalAppsMainLayout->addWidget(new QLabel(
tr("· %f and %tf will be substituted with the single image and thumbnail paths\n"
"· %u and %tu with their respective URIs (file:///path/to/file)\n"
"· %lat %lon and %alt with the GPS location in signed decimals (\"altitude\"…)\n"
"· by default the selected images are appended to the command"), this));
externalAppsMainLayout->addLayout(wrapperLayout);
externalAppsMainLayout->addLayout(wallpaperLayout);
externalAppsMainLayout->addLayout(buttonsLayout);
setLayout(externalAppsMainLayout);
// Load external apps list
m_wallpaperCommand->setEditable(true);
QStringList wpcomm;
wpcomm << "feh --bg-fill"
<< "pcmanfm-qt --set-wallpaper"
<< "pcmanfm --set-wallpaper"
<< "gsettings set org.gnome.desktop.background picture-uri \'%u\'"
<< "gsettings set org.gnome.desktop.background picture-uri-dark \'%u\'";
if (Settings::wallpaperCommand.isEmpty() && !wpcomm.contains(Settings::wallpaperCommand))
m_wallpaperCommand->addItem(Settings::wallpaperCommand);
m_wallpaperCommand->addItems(wpcomm);
m_wallpaperCommand->setCurrentText(Settings::wallpaperCommand);
QString key, val;
QMapIterator it(Settings::externalApps);
while (it.hasNext()) {
it.next();
key = it.key();
val = it.value();
addTableModelItem(appsTableModel, key, val);
}
}
void ExternalAppsDialog::ok() {
Settings::wallpaperCommand = m_wallpaperCommand->currentText();
int row = appsTableModel->rowCount();
Settings::externalApps.clear();
for (int i = 0; i < row; ++i) {
if (!appsTableModel->itemFromIndex(appsTableModel->index(i, 1))->text().isEmpty()) {
Settings::externalApps[appsTableModel->itemFromIndex(appsTableModel->index(i, 0))->text()] =
appsTableModel->itemFromIndex(appsTableModel->index(i, 1))->text();
}
}
accept();
}
void ExternalAppsDialog::add() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose Application"), "", "");
if (fileName.isEmpty())
return;
QFileInfo fileInfo = QFileInfo(fileName);
QString appName = fileInfo.fileName();
addTableModelItem(appsTableModel, appName, fileName);
}
void ExternalAppsDialog::entry() {
int atRow = appsTableModel->rowCount();
QStandardItem *itemKey = new QStandardItem(QString(tr("New Application")));
appsTableModel->insertRow(atRow, itemKey);
}
void ExternalAppsDialog::remove() {
QModelIndexList indexesList;
while ((indexesList = appsTable->selectionModel()->selectedIndexes()).size()) {
appsTableModel->removeRow(indexesList.first().row());
}
}
void ExternalAppsDialog::addTableModelItem(QStandardItemModel *model, QString &key, QString &val) {
int atRow = model->rowCount();
QStandardItem *itemKey = new QStandardItem(key);
QStandardItem *itemKey2 = new QStandardItem(val);
model->insertRow(atRow, itemKey);
model->setItem(atRow, 1, itemKey2);
}
phototonic-3.3.0/ExternalAppsDialog.h 0000664 0000000 0000000 00000002503 15271130355 0017604 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef EXTERNAL_APPS_DIALOG_H
#define EXTERNAL_APPS_DIALOG_H
class QComboBox;
class QTableView;
class QStandardItemModel;
#include
class ExternalAppsDialog : public QDialog {
Q_OBJECT
public:
ExternalAppsDialog(QWidget *parent);
private slots:
void add();
void entry();
void ok();
void remove();
private:
void addTableModelItem(QStandardItemModel *model, QString &key, QString &val);
private:
QTableView *appsTable;
QStandardItemModel *appsTableModel;
QComboBox *m_wallpaperCommand;
};
#endif // EXTERNAL_APPS_DIALOG_H phototonic-3.3.0/FileSystemTree.cpp 0000664 0000000 0000000 00000004777 15271130355 0017334 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include "FileSystemTree.h"
FileSystemTree::FileSystemTree(QWidget *parent) : QTreeView(parent) {
setAcceptDrops(true);
setDragEnabled(true);
setDragDropMode(QAbstractItemView::InternalMove);
setHeaderHidden(true);
connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(resizeTreeColumn(const QModelIndex &)));
connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(resizeTreeColumn(const QModelIndex &)));
}
QModelIndex FileSystemTree::getCurrentIndex() {
return selectedIndexes().first();
}
void FileSystemTree::setModel(QAbstractItemModel *m) {
if (model())
disconnect(model());
QTreeView::setModel(m);
connect(m, &QFileSystemModel::layoutChanged, this, [this]() { scrollTo(currentIndex()); }, Qt::QueuedConnection);
}
void FileSystemTree::resizeTreeColumn(const QModelIndex &index) {
resizeColumnToContents(0);
scrollTo(index);
}
void FileSystemTree::dragEnterEvent(QDragEnterEvent *event) {
QModelIndexList selectedDirs = selectionModel()->selectedRows();
if (selectedDirs.size() > 0) {
dndOrigSelection = selectedDirs[0];
event->acceptProposedAction();
}
}
void FileSystemTree::dragMoveEvent(QDragMoveEvent *event) {
setCurrentIndex(indexAt(event->position().toPoint()));
}
void FileSystemTree::dropEvent(QDropEvent *event) {
if (event->source()) {
QString fileSystemTreeStr = "FileSystemTree";
bool dirOp = (event->source()->metaObject()->className() == fileSystemTreeStr);
emit dropOp(event->modifiers(), dirOp, event->mimeData()->urls().at(0).toLocalFile());
setCurrentIndex(dndOrigSelection);
}
}
phototonic-3.3.0/FileSystemTree.h 0000664 0000000 0000000 00000002652 15271130355 0016767 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef FILE_SYSTEM_TREE_H
#define FILE_SYSTEM_TREE_H
class QFileSystemModel;
#include
class FileSystemTree : public QTreeView {
Q_OBJECT
public:
FileSystemTree(QWidget *parent);
QModelIndex getCurrentIndex();
virtual void setModel(QAbstractItemModel *model) override;
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
signals:
void dropOp(Qt::KeyboardModifiers keyMods, bool dirOp, QString cpMvDirPath);
private:
QModelIndex dndOrigSelection;
private slots:
void resizeTreeColumn(const QModelIndex &);
};
#endif // FILE_SYSTEM_TREE_H
phototonic-3.3.0/GuideWidget.cpp 0000664 0000000 0000000 00000005250 15271130355 0016614 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2018 Shawn Rutledge
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include "GuideWidget.h"
#include
#include
#include
static const int RuleWidgetWidth = 5; // determines the active area for dragging
GuideWidget::GuideWidget(QWidget *parent, Qt::Orientation o, int offset) : QWidget(parent), m_vertical(o == Qt::Vertical)
{
if (!parent) {
qWarning() << "GuideWidget requires a parent to guide around! I'm gonna die and you're gonna crash…";
deleteLater();
return;
}
resizeToParent();
parent->installEventFilter(this);
if (offset)
offset -= RuleWidgetWidth / 2;
setCursor(m_vertical ? Qt::SplitHCursor : Qt::SplitVCursor);
move(m_vertical ? offset : 0, m_vertical ? 0 : offset);
//: The guide is a visible line for orientation
m_deleteAction = new QAction(tr("Remove Guide"), this);
addAction(m_deleteAction);
setContextMenuPolicy(Qt::ActionsContextMenu);
connect(m_deleteAction, &QAction::triggered, this, &QObject::deleteLater);
show();
}
bool GuideWidget::eventFilter(QObject *o, QEvent *e)
{
if (o == parent() && e->type() == QEvent::Resize)
resizeToParent();
return false;
}
void GuideWidget::resizeToParent()
{
if (m_vertical)
resize(RuleWidgetWidth, parentWidget()->height());
else
resize(parentWidget()->width(), RuleWidgetWidth);
}
void GuideWidget::mouseMoveEvent(QMouseEvent *event)
{
if (event->modifiers() != Qt::NoModifier) {
QWidget::mouseMoveEvent(event);
return; // don't interfere with crop selection etc.
}
if (m_vertical)
move(x() + event->pos().x() - RuleWidgetWidth/2, 0);
else
move(0, y() + event->pos().y() - RuleWidgetWidth/2);
}
void GuideWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setPen(Qt::cyan);
int xy = RuleWidgetWidth / 2;
if (m_vertical)
painter.drawLine(xy, 0, xy, height());
else
painter.drawLine(0, xy, width(), xy);
}
phototonic-3.3.0/GuideWidget.h 0000664 0000000 0000000 00000002402 15271130355 0016255 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2018 Shawn Rutledge
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef GUIDEWIDGET_H
#define GUIDEWIDGET_H
class QAction;
#include
class GuideWidget : public QWidget
{
Q_OBJECT
public:
explicit GuideWidget(QWidget *parent, Qt::Orientation o = Qt::Horizontal, int offset = 0);
protected:
bool eventFilter(QObject *o, QEvent *e) override;
void mouseMoveEvent(QMouseEvent *event) override;
void paintEvent(QPaintEvent *event) override;
private:
void resizeToParent();
bool m_vertical;
QAction *m_deleteAction;
};
#endif // GUIDEWIDGET_H
phototonic-3.3.0/HISTORY.md 0000664 0000000 0000000 00000015032 15271130355 0015371 0 ustar 00root root 0000000 0000000 # Phototonic Image Viewer
### History:
##### 11 Mar 2018 - v2.1
+ Rotate preview by Exif rotation
+ Fixed bug in image filtering
+ Bug fixes for multiple UI issues and actions
+ Add shortcuts for all missing actions
##### 28 Feb 2018 - v2.0
+ Move to Trash
+ File List support
+ Bug fixes
##### 15 Jan 2018 - v2.0 - Snapshot
+ Back after a long break
+ Code cleanup and removal of useless features
+ Lots of bug fixes
+ Added Remove Image Metadata action
+ Enhanced keyboard settings
+ Enhanced image info
##### 12 Nov 2015 - v1.7.1
+ Changes to the way layouts are being switched, now faster and more efficient
+ Fixed issue with not reading image tags correctly when exif data was missing from image
+ Added Negate option to image tags filtering
+ Docks can now be nested to create more customized layouts
+ Some enhancements to Tags user experience and icons
+ Fixed issue with limited zoom functionality
+ Better error handling when reading corrupted images
+ New translations added
##### 8 Aug 2015 - v1.6.17
+ Image tags improvements and bug fixes
+ Changes to default key mapping
+ Small fixes to image extensions
+ Fixed issue with thumb label appearing after rename when labels are not displayed
+ Improvements to image feedback
+ Some dialog usability fixes
+ Added Negativity settings per color channel
+ Fixed colors manipulations for images with alpha channel and non animated GIF images
+ Other Bug fixes
##### 4 Jul 2015 - v1.6.6
+ Improved tags usability and performance
+ Bug fixes
##### 6 Jun 2015 - v1.6.2
+ Image tags, tagging images and filtering images by tags
+ Delete confirmation is now configurable
+ Improvements to drag and drop
+ A more sophisticated Dir-completer
+ Many many more fixes and improvements, thanks to the contributors!
##### 6 Feb 2015 - v1.5.54
+ Keyboard Shortcuts are now comfortably edited in a table
+ Enhancements to Find Duplicates feature
+ Many enhancements to translations and translations functionality
+ Fixes to the way key bindings are saved
+ Fixes to invalid behavior when deleting elements
+ Fixed folders expand indicator showing when there are no sub-folders
+ Fixed to the way bookmarks are saved
+ Added Changelog
##### 21 Nov 2014 - v1.5.1
+ New toolbar in viewer mode for image manipulation actions
+ Added Bookmarks feature
+ Fixed sorting order when sorting by time and size
+ Added Find Duplicate Images feature
+ Added shortcuts for changing the focus to the Find and Path text areas
+ Enhancements to Copy to and Move to dialogs
+ Can now set thumbnails background image
+ Enhancements to Colors dialog, added color balance feature
+ Added Crop to Selection feature
+ Added mouse shortcuts for Reset/Original Zoom
+ Added feedback notification for transformation actions in viewer
+ Changed Cropping dialog orientation to percentage cropping for continuous image cropping
+ Image data now showed in sections
+ Many other fixes
##### 19 Sep 2014 - v1.4
+ Viewer is now available in the thumbnails layout as a Dock
+ Thumbnails can now also be rotated according Exif orientation
+ Added Debian packaging scripts
+ Enhances to external application dialog
+ Added Czech translation
+ Added French translation
+ Better feedback when starting external applications
+ Settings dialog controls are now grouped in tabs
+ Added 16px size application icon
+ Improvements to German translation
+ Can now rename an image when in viewer
+ Added busy indicator for some actions in thumbnails layout
+ Changes to version scheme
+ Open image action now toggles closing the image when in viewer
+ Consolidate feedback in viewer to bubbles
+ Tool bars icon size is now custom
+ Confirmation is asked when moving folders around in the tree
+ Fixes to slowness and other bugs when closing image from full screen
+ Fixed folder focus stealing issue when creating a new folder
+ Fixes for some untranslated dialogs
+ Fix dialogs creating shadow over image under KDE
+ Fixes for wrong dock sizes when toggling layouts
+ Fixed slowness when inverting selection
+ Many other fixes
##### 8 Aug 2014 - v1.03
+ Added translations for Polish, German and Russian. Many thanks to the translators!
+ Added Startup Folder options
+ Added Brightness and Contrast controls
+ Added Scale Image feature
+ Added option to show image name in full screen
+ Can now show/hide thumbnail labels in Classic and Compact modes
+ Added menu for docks and toolbars visibility
+ Improved rename dialog
+ Optimizations to thumbnail layouts
+ Fixed zooming with mouse wheel direction
+ Fixes thumbnails sorting case sensitivity
+ Fixes to menu visibility in Ubuntu
+ Fixes to Slide show
+ Many more small bug fixes
##### 14 Jul 2014 - v1.01
+ Fixed image saving failure in some cases
+ Fixed tool bars and docks non persistent visibility state
##### 12 Jul 2014 - v1.00
+ Thumbnails can be loaded and browsed recursively on a folder tree
+ Thumbnails are now loaded dynamically, enabling browsing very large folders
+ Enhancements to thumbnails filtering
+ Added "Copy/Move Images to..." Dialog
+ Can now open image with multiple external programs
+ Added customization for mouse behavior
+ Added Show Hidden Files option
+ Enhancements to crop dialog
+ Image zooming can now be controlled with mouse wheel+ctrl key
+ Enhancements to thumbnails loading UX
+ Fixes to slide show starting offset
+ Fixed file management issues
+ Fixed issues with docks state not being saved
+ Fixed issue with window size when exiting Phototonic while in full screen
+ Fixed invalid image movement when moving with keyboard
##### 17 May 2014 - v0.99
+ Images can+ now be rotated freely to any angle
+ Added file name filtering option
+ Added Exif support (Exiv2 is now a dependency), metadata retained when saving images
+ New Image features: New Image, Copy and Paste image data
+ File system tree and Image Info panes can now be removed or docked anywhere
+ Many other small fixes and enhancements
+
##### 27 Apr 2014 - v0.98
+ New Colors dialog with Hue and Saturation settings
+ Added support for animated GIFs
+ Large images can now be moved around with keyboard as well as the mouse
+ Added notifications while in viewer
##### 11 Apr 2014 - v0.97
+ Moved to Qt5
+ Fixed missing icons when not in a DE
+ Added additional image info in status and title bars
##### 29 Mar 2014 - v0.96
+ Fixed thumbnails navigation usability issues
##### 28 Mar 2014 - v0.95
+ Added Open with external application option and other enhancements
##### 25 Mar 2014 - v0.94
+ Icons now loaded from theme.
+ Added Copy Image option.
##### 22 Mar 2014 - v0.93
+ Added keyboard shortcuts customization
+ Fixed issues related to image formats
+ New web site, under construction
phototonic-3.3.0/IconProvider.cpp 0000664 0000000 0000000 00000001612 15271130355 0017014 0 ustar 00root root 0000000 0000000 #include "IconProvider.h"
QIcon IconProvider::icon(const QFileInfo &info) const
{
if (info.filePath().endsWith('/') || info.isDir()) {
return m_dirIcon;
}
return m_unknownIcon;
/*
const QString fileName = info.fileName();
const int lastDot = info.fileName().lastIndexOf('.');
if (lastDot != -1 && lastDot != 0) {
const QString suffix = fileName.mid(lastDot);
QIcon &icon = m_cache[suffix];
if (!icon.isNull()) {
return icon;
}
QMimeType mime = m_mimeDb.mimeTypeForFile(info, QMimeDatabase::MatchExtension);
icon = QIcon::fromTheme(mime.iconName());
if (icon.isNull()) {
icon = QIcon::fromTheme(mime.genericIconName());
}
if (icon.isNull()) {
icon = m_unknownIcon;
}
m_cache[suffix] = icon;
return icon;
}
return m_unknownIcon;
*/
}
phototonic-3.3.0/IconProvider.h 0000664 0000000 0000000 00000001146 15271130355 0016463 0 ustar 00root root 0000000 0000000
#ifndef ICONPROVIDER_H
#define ICONPROVIDER_H
#pragma once
#include
#include
class IconProvider : public QFileIconProvider
{
public:
IconProvider() : QFileIconProvider(),
m_dirIcon(QIcon::fromTheme(QLatin1String("inode-directory"))),
m_unknownIcon(QIcon::fromTheme("unknown"))
{}
//icon(QFileIconProvider::IconType type) const override;
QIcon icon(const QFileInfo &info) const override;
private:
QIcon m_dirIcon;
QIcon m_unknownIcon;
mutable QHash m_cache;
QMimeDatabase m_mimeDb;
};
#endif // ICONPROVIDER_H phototonic-3.3.0/ImageViewer.cpp 0000664 0000000 0000000 00000152305 15271130355 0016623 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov - oferkv@live.com
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "CropDialog.h"
#include "CropRubberband.h"
#include "ImageViewer.h"
#include "MessageBox.h"
#include "MetadataCache.h"
#include "Settings.h"
#define CLIPBOARD_IMAGE_NAME "clipboard.png"
#define ROUND(x) ((int) ((x) + 0.5))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#if __cplusplus >= 202002L
#define _LCD_ =,this
#else
#define _LCD_ =
#endif
namespace { // anonymous, not visible outside of this file
class ClickToClose : public QObject {
public:
ClickToClose() : QObject() {}
protected:
bool eventFilter(QObject *o, QEvent *e) {
if (e->type() == QEvent::MouseButtonRelease)
static_cast(o)->hide();
return false;
}
};
} // anonymous namespace
ClickToClose *gs_clickToClose = nullptr;
ImageViewer::ImageViewer(QWidget *parent) : QOpenGLWidget(parent) {
if (!gs_clickToClose)
gs_clickToClose = new ClickToClose;
m_letterbox = QRect(QPoint(0,0), QPoint(100,100));
myContextMenu = nullptr;
cursorIsHidden = false;
moveImageLocked = false;
m_crossfade = false;
m_loading = false;
animation = nullptr;
m_zoomMode = ZoomToFit;
m_zoom = 1.0;
m_lockZoom = false;
m_edited = false;
m_editMode = Crop;
m_fadeout = 0.0;
m_crossfade = false;
m_showGrid = false;
m_keepTransform = false;
setAutoFillBackground(true);
setBackgroundColor();
myFilenameLabel = new QLabel(this);
myFilenameLabel->setVisible(Settings::showImageName);
myFilenameLabel->setMargin(3);
myFilenameLabel->move(10, 10);
myFilenameLabel->setAutoFillBackground(true);
myFilenameLabel->setFrameStyle(QFrame::Plain|QFrame::NoFrame);
QPalette pal = myFilenameLabel->palette();
pal.setColor(myFilenameLabel->backgroundRole(), QColor(0,0,0,128));
pal.setColor(myFilenameLabel->foregroundRole(), QColor(255,255,255,128));
myFilenameLabel->setPalette(pal);
feedbackLabel = new QLabel(this);
feedbackLabel->setVisible(false);
feedbackLabel->setMargin(3);
feedbackLabel->setFrameStyle(QFrame::Plain|QFrame::NoFrame);
feedbackLabel->setAutoFillBackground(true);
feedbackLabel->setPalette(pal);
feedbackLabel->installEventFilter(gs_clickToClose);
mouseMovementTimer = new QTimer(this);
connect(mouseMovementTimer, SIGNAL(timeout()), this, SLOT(monitorCursorState()));
Settings::hueVal = 0;
Settings::saturationVal = 100;
Settings::lightnessVal = 100;
Settings::hueRedChannel = true;
Settings::hueGreenChannel = true;
Settings::hueBlueChannel = true;
Settings::contrastVal = 78;
Settings::brightVal = 100;
Settings::dialogLastX = Settings::dialogLastY = 0;
Settings::mouseRotateEnabled = false;
newImage = false;
cropRubberBand = 0;
m_preloadThread = nullptr;
}
void ImageViewer::lockZoom(bool locked) {
m_lockZoom = locked;
setFeedback(locked ? tr("Zoom Locked") : tr("Zoom Unlocked"));
}
void ImageViewer::zoomTo(float goal, QPoint focus, int duration) {
static QVariantAnimation *zoominator = nullptr;
if (goal == m_zoom && (!zoominator || zoominator->state() != QAbstractAnimation::Running))
return; // idempotent
if (focus.x() < 0)
focus = rect().center();
m_zoomMode = ZoomOriginal;
if (!zoominator) {
zoominator = new QVariantAnimation(this);
connect(zoominator, &QVariantAnimation::valueChanged, [_LCD_](const QVariant &value) {
if (zoominator->state() != QAbstractAnimation::Running)
return;
m_zoom = value.toFloat();
resizeImage(zoominator->property("zoomfocus").toPoint());
});
connect(zoominator, &QObject::destroyed, [_LCD_]() {zoominator = nullptr;});
}
zoominator->setDuration(duration);
zoominator->setProperty("zoomfocus", focus);
zoominator->setStartValue(m_zoom);
zoominator->setEndValue(goal);
zoominator->start();
}
void ImageViewer::zoomTo(ImageViewer::ZoomMode mode, QPoint focus, int duration) {
QSize imageSize = m_currentImage.size();
if (imageSize.isEmpty())
return;
float factor = 1.0;
if (mode == ZoomToFit) {
QSize targetSize = imageSize.scaled(size(), Qt::KeepAspectRatio);
factor = targetSize.width()/float(imageSize.width());
setFeedback(tr("Fit View"));
}
else if (mode == ZoomToFill) {
QSize targetSize = imageSize.scaled(size(), Qt::KeepAspectRatioByExpanding);
factor = targetSize.width()/float(imageSize.width());
setFeedback(tr("Fill View"));
} else {
setFeedback(tr("Original Size"));
}
zoomTo(factor, focus, duration);
QTimer::singleShot(duration, this, [_LCD_]() {m_zoomMode = mode;});
}
void ImageViewer::rotateTo(qreal r, Rotate direction) {
if (direction == Direct) {
m_rotation = r;
update();
return;
}
// wrap the starting angle for the animation, so we don't rotate backwards
if (direction == CW && r < m_rotation)
m_rotation -= 360.0;
if (direction == CCW && r > m_rotation)
m_rotation += 360.0;
static QVariantAnimation *rotator = nullptr;
if (!rotator) {
rotator = new QVariantAnimation(this);
rotator->setEasingCurve(QEasingCurve::InOutCubic);
connect(rotator, &QVariantAnimation::valueChanged, [_LCD_](const QVariant &value) {
if (rotator->state() != QAbstractAnimation::Running)
return;
m_rotation = value.toReal();
update();
});
connect(rotator, &QObject::destroyed, [_LCD_]() {rotator = nullptr;});
}
rotator->setDuration(2*qAbs(r - m_rotation));
rotator->setStartValue(m_rotation);
rotator->setEndValue(r);
rotator->start();
}
void ImageViewer::resizeImage(QPoint focus) {
QSize imageSize = m_currentImage.size();
if (imageSize.isEmpty())
return;
if (m_zoomMode == ZoomToFit) {
QSize oSize = imageSize;
imageSize.scale(size(), Qt::KeepAspectRatio);
m_zoom = imageSize.width()/float(oSize.width());
}
else if (m_zoomMode == ZoomToFill) {
QSize oSize = imageSize;
imageSize.scale(size(), Qt::KeepAspectRatioByExpanding);
m_zoom = imageSize.width()/float(oSize.width());
} else {
imageSize = QSize(qRound(imageSize.width() * m_zoom),
qRound(imageSize.height() * m_zoom));
}
if (imageSize.width() < width() || imageSize.height() < height()) {
centerImage(imageSize);
} else {
const double fx = double(imageSize.width())/m_currentImageSize.width(),
fy = double(imageSize.height())/m_currentImageSize.height();
int x,y;
if (focus.x() > -1 && focus.y() > -1) {
x = qRound(fx*(m_currentImagePos.x() - focus.x()) + focus.x());
y = qRound(fy*(m_currentImagePos.y() - focus.y()) + focus.y());
} else {
x = qRound(m_currentImagePos.x()*fx);
y = qRound(m_currentImagePos.y()*fy);
}
if (imageSize.width() >= width())
x = qMax(qMin(x, 0), width() - imageSize.width());
if (imageSize.height() >= height())
y = qMax(qMin(y, 0), height() - imageSize.height());
setImagePosition(QPoint(x,y));
}
m_currentImageSize = imageSize;
update();
}
void ImageViewer::scaleImage(QSize newSize) {
origImage = origImage.scaled(newSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
refresh();
setFeedback(tr("New image size: %1x%2").arg(origImage.width()).arg(origImage.height()));
emit imageEdited(true);
}
void ImageViewer::resizeEvent(QResizeEvent *event) {
QOpenGLWidget::resizeEvent(event);
const bool mapCrop = cropRubberBand && cropRubberBand->isVisibleTo(this);
QRect isoCropRect;
if (mapCrop) {
QTransform matrix = transformation().inverted();
isoCropRect = matrix.mapRect(cropRubberBand->geometry());
}
resizeImage();
if (mapCrop) {
QTransform matrix = transformation();
cropRubberBand->setGeometry(matrix.mapRect(isoCropRect));
}
}
void ImageViewer::showEvent(QShowEvent *event) {
QOpenGLWidget::showEvent(event);
resizeImage();
}
void ImageViewer::centerImage(QSize imgSize) {
setImagePosition(QPoint((width() - imgSize.width())/2, (height() - imgSize.height())/2));
}
static inline int bound0To255(int val) {
return ((val > 255) ? 255 : (val < 0) ? 0 : val);
}
static inline int hslValue(float n1, float n2, int hue) {
double value;
if (hue > 255) {
hue -= 255;
} else if (hue < 0) {
hue += 255;
}
if (hue < 42.5f) {
value = n1 + (n2 - n1) * (hue / 42.5f);
} else if (hue < 127.5f) {
value = n2;
} else if (hue < 170) {
value = n1 + (n2 - n1) * ((170 - hue) / 42.5f);
} else {
value = n1;
}
return ROUND(value * 255.0f);
}
void rgbToHsl(int r, int g, int b, unsigned char *hue, unsigned char *sat, unsigned char *light) {
float h, s, l;
int min, max;
int delta;
if (r > g) {
max = MAX(r, b);
min = MIN(g, b);
} else {
max = MAX(g, b);
min = MIN(r, b);
}
l = (max + min) / 2.0f;
if (max == min) {
s = 0.0;
h = 0.0;
} else {
delta = (max - min);
if (l < 128) {
s = 255 * delta / float(max + min);
} else {
s = 255 * delta / float(511 - max - min);
}
if (r == max) {
h = (g - b) / float(delta);
} else if (g == max) {
h = 2 + (b - r) / float(delta);
} else {
h = 4 + (r - g) / float(delta);
}
h = h * 42.5f;
if (h < 0) {
h += 255;
} else if (h > 255) {
h -= 255;
}
}
*hue = ROUND(h);
*sat = ROUND(s);
*light = ROUND(l);
}
void hslToRgb(int h, int s, int l,
unsigned char *red, unsigned char *green, unsigned char *blue) {
if (s == 0) {
/* achromatic case */
*red = l;
*green = l;
*blue = l;
} else {
float m1, m2;
if (l < 128)
m2 = (l * (255 + s)) / 65025.0f;
else
m2 = (l + s - (l * s) / 255.0f) / 255.0f;
m1 = (l / 127.5f) - m2;
/* chromatic case */
*red = hslValue(m1, m2, h + 85);
*green = hslValue(m1, m2, h);
*blue = hslValue(m1, m2, h - 85);
}
}
static int linesDone = 0;
void ImageViewer::colorize(uchar *bits, int bytesPerLine, int startLine, int endLine, const unsigned char (*contrastTransform)[256], const unsigned char (*brightTransform)[256]) {
unsigned char hr, hg, hb;
unsigned char h, s, l;
int r, g, b;
QRgb *line;
bool hasAlpha = viewerImage.hasAlphaChannel();
// int ciddqd = 0;
QRgb iddqd[2] = {qRgba(0,0,0,0), qRgba(0,0,0,0)};
for (int y = startLine; y < endLine; ++y) {
line = reinterpret_cast(bits + (y * bytesPerLine));
for (int x = 0; x < viewerImage.width(); ++x) {
// Cheat, maybe the pixel is the same as the previous
QRgb rgb = qRgb(qRed(line[x]), qGreen(line[x]), qBlue(line[x]));
if (iddqd[0] == rgb) {
// ++ciddqd;
rgb = iddqd[1];
line[x] = hasAlpha ? qRgba(qRed(rgb), qGreen(rgb), qBlue(rgb), qAlpha(line[x])) : rgb;
continue;
}
r = qRed(rgb);
if (Settings::hueRedChannel) {
if (Settings::rNegateEnabled)
r = 255 - r;
r = bound0To255((r * (Settings::redVal + 100)) / 100);
r = (*brightTransform)[r];
r = (*contrastTransform)[r];
}
g = qGreen(rgb);
if (Settings::hueGreenChannel) {
if (Settings::gNegateEnabled)
g = 255 - g;
g = bound0To255((g * (Settings::greenVal + 100)) / 100);
g = (*brightTransform)[g];
g = (*contrastTransform)[g];
}
b = qBlue(rgb);
if (Settings::hueBlueChannel) {
if (Settings::bNegateEnabled)
b = 255 - b;
b = bound0To255((b * (Settings::blueVal + 100)) / 100);
b = (*brightTransform)[b];
b = (*contrastTransform)[b];
}
if (Settings::hueVal != 0 || Settings::saturationVal != 100 || Settings::lightnessVal != 100) {
rgbToHsl(r, g, b, &h, &s, &l);
h = Settings::colorizeEnabled ? Settings::hueVal : h + Settings::hueVal;
s = bound0To255(((s * Settings::saturationVal) / 100));
l = bound0To255(((l * Settings::lightnessVal) / 100));
hslToRgb(h, s, l, &hr, &hg, &hb);
if (Settings::hueRedChannel)
r = hr;
if (Settings::hueGreenChannel)
g = hg;
if (Settings::hueBlueChannel)
b = hb;
}
iddqd[0] = rgb;
iddqd[1] = rgb = qRgb(r, g, b);
line[x] = hasAlpha ? qRgba(r, g, b, qAlpha(line[x])) : rgb;
linesDone = y;
}
}
}
void ImageViewer::colorize() {
switch(viewerImage.format()) {
case QImage::Format_RGB32:
case QImage::Format_ARGB32:
case QImage::Format_ARGB32_Premultiplied:
break;
default:
viewerImage = viewerImage.convertToFormat(QImage::Format_RGB32);
}
float contrast = ((float) Settings::contrastVal / 100.0);
float brightness = ((float) Settings::brightVal / 100.0);
static unsigned char contrastTransform[256];
static unsigned char brightTransform[256];
for (int i = 0; i < 256; ++i) {
if (i < (int) (128.0f + 128.0f * tan(contrast)) && i > (int) (128.0f - 128.0f * tan(contrast))) {
contrastTransform[i] = bound0To255((i - 128) / tan(contrast) + 128);
} else if (i >= (int) (128.0f + 128.0f * tan(contrast))) {
contrastTransform[i] = 255;
} else {
contrastTransform[i] = 0;
}
}
for (int i = 0; i < 256; ++i) {
brightTransform[i] = bound0To255(int((255.0 * pow(i / 255.0, 1.0 / brightness)) + 0.5));
}
// QElapsedTimer profiler;
// profiler.start();
const int threadCount = qMin(QThread::idealThreadCount(), viewerImage.height()/512);
uchar *bits;
if (viewerImage.constBits() == origImage.constBits()) {
bits = viewerImage.bits(); // detach to preserve origImage
} else {
bits = const_cast(viewerImage.constBits());
}
const int bpl = viewerImage.bytesPerLine();
if (!threadCount) {
colorize(bits, bpl, 0, viewerImage.height(), &contrastTransform, &brightTransform);
} else {
QThread **threads = new QThread*[threadCount];
int batch = viewerImage.height()/threadCount;
if (threadCount > 1) {
for (int i = 0; i < threadCount-1; ++i) {
threads[i] = QThread::create([_LCD_](){colorize(bits, bpl, i*batch, (i+1)*batch, &contrastTransform, &brightTransform);});
threads[i]->start();
}
}
threads[threadCount-1] = QThread::create([_LCD_](){colorize(bits, bpl, (threadCount-1)*batch, viewerImage.height(), &contrastTransform, &brightTransform);});
threads[threadCount-1]->start();
#if 1
// live updates make things slower but give the user the comfort that sth's going on
bool done = false;
int cycle = 1;
while (!done) {
done = true;
for (int i = 0; i < threadCount; ++i) {
if (!threads[i]->wait(250)) {
done = false;
// the threads update linesDone independently and we just guess that they run at
// the same speed, then predict how long this is gonna take and avoid "late" previews
// that would cause overall slowdown
if (float(threadCount*linesDone)/viewerImage.height() < 1.0f-1.0f/++cycle) {
// we need to wrap the altered bits in a new image to make Qt/QGLWidget
// understand/believe that there's sth. to update here
// the final update in ::refresh is fine because viewerImage got detached
setImage(QImage(viewerImage.constBits(), viewerImage.width(),
viewerImage.height(), viewerImage.bytesPerLine(),
viewerImage.format()));
resizeImage();
repaint();
}
break;
}
}
}
#else
for (int i = 0; i < threadCount; ++i)
threads[i]->wait();
#endif
for (int i = 0; i < threadCount; ++i)
delete threads[i];
delete [] threads;
}
// qDebug() << profiler.elapsed() << threadCount; // << "IDDQD:" << ciddqd;
emit imageEdited(true);
}
void ImageViewer::refresh() {
if (animation)
return;
viewerImage = origImage;
if (Settings::colorsActive) {
colorize();
}
setImage(viewerImage);
resizeImage();
}
void ImageViewer::setCrossfade(bool yesno)
{
m_crossfade = yesno;
if (!m_crossfade)
m_prevImage = QImage();
}
void ImageViewer::setImage(const QImage &i)
{
if (m_crossfade) {
m_prevImage = m_currentImage;
m_prevImagePos = m_currentImagePos;
m_prevImageSize = m_currentImageSize;
}
m_currentImage = i;
if (m_crossfade) {
m_fadeout = 1.0;
static QVariantAnimation *fadeAnimator = nullptr;
if (!fadeAnimator) {
fadeAnimator = new QVariantAnimation(this);
fadeAnimator->setStartValue(1.0);
fadeAnimator->setEndValue(0.0);
fadeAnimator->setDuration(250);
connect(fadeAnimator, &QVariantAnimation::valueChanged, [_LCD_](const QVariant &value) {
if (fadeAnimator->state() != QAbstractAnimation::Running)
return;
m_fadeout = value.toFloat();
update();
});
connect(fadeAnimator, &QVariantAnimation::finished, [this]() {m_prevImage = QImage();});
connect(fadeAnimator, &QObject::destroyed, [_LCD_]() {fadeAnimator = nullptr;});
}
fadeAnimator->start();
} else {
update();
}
}
QTransform ImageViewer::transformation() const {
return transformation(m_currentImage, m_currentImageSize, m_currentImagePos);
}
QTransform ImageViewer::transformation(const QImage &img, const QSize &sz, const QPoint &pos) const {
float scale = qMax(float(sz.width()) / img.width(), float(sz.height()) / img.height());
QTransform matrix;
QPoint center(width() / 2, height() / 2);
matrix.translate(center.x(), center.y());
matrix.rotate(m_rotation);
matrix.translate(-center.x(), -center.y());
// translate
QPoint origin;
if (m_flip & Qt::Horizontal)
origin.setX(sz.width());
if (m_flip & Qt::Vertical)
origin.setY(sz.height());
origin += pos;
matrix.translate(origin.x(), origin.y());
// scale
matrix.scale((m_flip & Qt::Horizontal) ? -scale : scale, (m_flip & Qt::Vertical) ? -scale : scale);
return matrix;
}
void ImageViewer::setImagePosition(const QPoint &p) {
m_currentImagePos = p;
update();
}
void ImageViewer::reload() {
emit imageEdited(false);
static bool s_busy = false;
static bool s_abort = false;
if (s_busy) {
s_abort = true;
QMetaObject::invokeMethod(this, "reload", Qt::QueuedConnection);
return;
}
// setFeedback("",false);
if (Settings::showImageName) {
if (fullImagePath.left(1) == ":") {
setInfo("No Image");
} else if (fullImagePath.isEmpty()) {
setInfo("Clipboard");
} else {
setInfo(QFileInfo(fullImagePath).fileName());
}
}
if (!batchMode && !m_keepTransform) {
m_rotation = 0;
m_flip = Qt::Orientations();
}
if (!batchMode) {
Settings::mouseRotateEnabled = false;
emit toolsUpdated();
if (newImage || fullImagePath.isEmpty()) {
newImage = true;
fullImagePath = CLIPBOARD_IMAGE_NAME;
origImage.load(":/images/no_image.png");
viewerImage = origImage;
setImage(viewerImage);
pasteImage();
return;
}
}
QImageReader imageReader(fullImagePath);
if (batchMode && imageReader.supportsAnimation()) {
//: this is a warning on the console
qWarning() << tr("skipping animation in batch mode:") << fullImagePath;
return;
}
if (Settings::enableAnimations && imageReader.supportsAnimation()) {
delete animation;
animation = new QMovie(fullImagePath);
if (animation->frameCount() > 1) {
viewerImage = origImage = QImage();
animation->setParent(this);
// animation->start();
// setImage(animation->currentImage());
connect(animation, &QMovie::updated, this, [_LCD_]() {
// QImage preImg = m_prevImage;
// m_prevImage = QImage();
const bool crossfade = m_crossfade;
// if (preImg.isNull())
m_crossfade = false;
setImage(animation->currentImage());
// m_prevImage = preImg;
m_crossfade = crossfade;
});
animation->start();
resizeImage();
centerImage(m_currentImageSize);
return;
}
}
// clean up - don't waste memory and bogus 1-frame gifs will otherwise kill resizeImage()
delete animation;
animation = nullptr;
auto loadThreaded = [_LCD_](QThread *thread) {
s_busy = true;
while (!thread->wait(30)) {
QApplication::processEvents();
if (s_abort) {
thread->terminate();
thread->wait();
break;
}
}
s_busy = false;
thread->deleteLater();
if (s_abort) {
s_abort = false;
return false;
}
return true;
};
// It's not a movie
if (fullImagePath == m_preloadedPath) {
bool ok = true;
if (m_preloadThread) {
ok = loadThreaded(m_preloadThread);
m_preloadThread = nullptr; // clean up
}
if (ok)
viewerImage = origImage = m_preloadedImage;
m_preloadedImage = QImage();
m_preloadedPath.clear();
if (!ok)
return;
} else if (imageReader.size().isValid()) {
QSize sz = imageReader.size();
if (sz.width() * sz.height() > 8192*8192) { // allocation limit
/// @todo this and the correct sqrt(double…) of the below still runs into the size limts?
// perhaps because qimagereader overreads and needs some extra memory
// sz.scale(8192,8192, Qt::KeepAspectRatio);
double factor = double(8192*8192)/(sz.width() * sz.height());
// the sqrt is correct, but too large - the square of the true factor will over"punish" large images
// so we draw an average - this is by "shows the most annoying supersize image I have"
factor = (2*factor + sqrt(factor))/3.0;
sz *= factor;
imageReader.setScaledSize(sz);
setFeedback(tr( "Warning
Original image size %1x%2 exceeds limits
"
"Downscaled to %3x%4
Saving edits will save the smaller image!
")
.arg(imageReader.size().width()).arg(imageReader.size().height())
.arg(sz.width()).arg(sz.height()), 10000);
}
bool imageOk = false;
if (batchMode) {
imageOk = imageReader.read(&origImage);
} else {
QThread *thread = QThread::create([&](){imageOk = imageReader.read(&origImage);});
thread->start();
if (!loadThreaded(thread))
return;
}
if (imageOk) {
if (Settings::exifRotationEnabled) {
m_exifTransformation = Metadata::transformation(fullImagePath);
origImage = origImage.transformed(Metadata::transformation(fullImagePath), Qt::SmoothTransformation);
}
viewerImage = origImage;
if (Settings::colorsActive) {
colorize();
}
} else {
viewerImage = QImage(":/images/error_image.png");
setFeedback(QFileInfo(imageReader.fileName()).fileName() + ": " + imageReader.errorString());
}
}
setImage(viewerImage);
resizeImage();
centerImage(m_currentImageSize);
if (Settings::setWindowIcon) {
window()->setWindowIcon(QPixmap::fromImage(viewerImage.scaled(WINDOW_ICON_SIZE, WINDOW_ICON_SIZE,
Qt::KeepAspectRatio, Qt::SmoothTransformation)));
}
}
void ImageViewer::setInfo(QString infoString) {
myFilenameLabel->setText(infoString);
myFilenameLabel->adjustSize();
}
void ImageViewer::unsetFeedback() {
if (m_permanentFeedback.isEmpty()) {
feedbackLabel->clear();
feedbackLabel->setVisible(false);
} else {
setFeedback(m_permanentFeedback, false);
}
}
void ImageViewer::setFeedback(QString feedbackString, int timeLimited) {
if (!timeLimited)
m_permanentFeedback = feedbackString;
if (feedbackString.isEmpty()) {
unsetFeedback();
return;
}
feedbackLabel->setText(feedbackString);
feedbackLabel->setVisible(true);
int margin = myFilenameLabel->isVisible() ? (myFilenameLabel->height() + 15) : 10;
feedbackLabel->move(10, margin);
feedbackLabel->adjustSize();
if (timeLimited) {
static QTimer *unsetFeedbackTimer = nullptr;
if (!unsetFeedbackTimer) {
unsetFeedbackTimer = new QTimer(this);
unsetFeedbackTimer->setSingleShot(true);
connect (unsetFeedbackTimer, &QTimer::timeout, this, &ImageViewer::unsetFeedback);
}
unsetFeedbackTimer->setInterval(timeLimited);
unsetFeedbackTimer->start();
}
}
void ImageViewer::loadImage(QString imageFileName, const QImage &preview) {
if (fullImagePath == imageFileName)
return;
secureEdits();
unsetFeedback();
newImage = false;
fullImagePath = imageFileName;
const QSize fullSize = QImageReader(fullImagePath).size();
const bool largeImage = !fullSize.isValid() || fullSize.width() >= width() || fullSize.height() >= height();
if (!m_lockZoom) {
m_zoomMode = ZoomToFit;
if (!largeImage) {
m_zoomMode = ZoomOriginal;
m_zoom = 1.0f;
}
}
if (!preview.isNull()) {
// don't preview small images w/ a huge thumbnail upscale
// it's pointless and causes ugly flicker
if (largeImage) {
if (!m_keepTransform) {
m_rotation = 0;
m_flip = Qt::Orientations();
}
setImage(preview);
const float o_zoom = m_zoom;
if (m_zoomMode == ZoomOriginal && fullSize.isValid())
m_zoom *= (fullSize.width()/float(preview.width()) + fullSize.height()/float(preview.height()))/2.0f;
resizeImage();
centerImage(m_currentImageSize);
m_zoom = o_zoom;
}
}
QApplication::processEvents();
m_loading = true;
reload();
m_loading = false;
if (!m_preloadPath.isEmpty()) {
preload(m_preloadPath);
}
emit imageLoaded();
}
void ImageViewer::preload(QString imageFileName) {
if (m_preloadedPath == imageFileName)
return;
if (m_loading) {
m_preloadPath = imageFileName;
return;
}
if (m_preloadThread) {
while (!m_preloadThread->wait(15)) { // we're already preloading stuff, so maybe wait a moment…
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
if (!m_preloadThread)
break; // we've lost this to the main loader or below
}
QTimer::singleShot(0, this, [_LCD_](){ preload(imageFileName); }); // allow event processing, notably reload
return;
}
m_preloadPath = QString();
m_preloadedPath = imageFileName;
// reload current one - maybe the file has changed on disk?
/*if (m_preloadedPath == fullImagePath) {
m_preloadedImage = origImage;
return;
}*/
QImageReader imageReader(m_preloadedPath);
if (m_preloadedPath.isEmpty() || imageReader.supportsAnimation()) {
m_preloadedImage = QImage();
m_preloadedPath.clear();
return; // no preloading of animations
}
bool imageOk = false;
if (imageReader.size().isValid()) {
m_preloadThread = QThread::create([&](){
// usleep(8000000);
imageOk = imageReader.read(&m_preloadedImage);
if (imageOk && Settings::exifRotationEnabled)
m_preloadedImage = m_preloadedImage.transformed(Metadata::transformation(fullImagePath), Qt::SmoothTransformation);
});
m_preloadThread->start();
while (!m_preloadThread->wait(15)) {
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
if (!m_preloadThread)
return; // we've been taken over by the main loader
}
m_preloadThread->deleteLater();
m_preloadThread = nullptr;
}
if (!imageOk) {
m_preloadedImage = QImage();
m_preloadedPath.clear();
}
}
void ImageViewer::secureEdits() {
if (m_edited) {
if (MessageBox(this, MessageBox::Save|MessageBox::Discard, MessageBox::Save).ask(
tr("Save edits?"),tr("The image was edited.\nDo you want to save a copy?"))
== MessageBox::Save)
saveImageAs();
m_edited = false;
}
}
void ImageViewer::clearImage() {
secureEdits();
fullImagePath.clear();
origImage.load(":/images/no_image.png");
viewerImage = origImage;
setImage(viewerImage);
}
void ImageViewer::setContextMenu(QMenu *menu) {
delete myContextMenu;
myContextMenu = menu;
myContextMenu->setParent(this);
}
void ImageViewer::monitorCursorState() {
static QPoint lastPos;
if (QCursor::pos() != lastPos) {
lastPos = QCursor::pos();
if (cursorIsHidden) {
QApplication::restoreOverrideCursor();
cursorIsHidden = false;
}
} else {
if (!cursorIsHidden) {
QApplication::setOverrideCursor(Qt::BlankCursor);
cursorIsHidden = true;
}
}
}
void ImageViewer::setCursorHiding(bool hide) {
if (hide) {
mouseMovementTimer->start(500);
} else {
mouseMovementTimer->stop();
if (cursorIsHidden) {
QApplication::restoreOverrideCursor();
cursorIsHidden = false;
}
}
}
void ImageViewer::mouseDoubleClickEvent(QMouseEvent *event) {
QOpenGLWidget::mouseDoubleClickEvent(event);
while (QApplication::overrideCursor()) {
QApplication::restoreOverrideCursor();
}
}
void ImageViewer::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
if (event->modifiers() == Qt::ShiftModifier && !animation) {
cropOrigin = event->pos();
if (!cropRubberBand) {
cropRubberBand = new CropRubberBand(this);
connect(cropRubberBand, &CropRubberBand::selectionChanged,
this, &ImageViewer::updateRubberBandFeedback);
connect(cropRubberBand, &CropRubberBand::cropConfirmed,
this, &ImageViewer::applyCropAndRotation);
}
cropRubberBand->show();
cropRubberBand->setGeometry(QRect(cropOrigin, event->pos()).normalized());
} else if (!(Settings::mouseRotateEnabled || event->modifiers() == Qt::ControlModifier)) {
if (cropRubberBand && cropRubberBand->isVisible()) {
cropRubberBand->hide();
setFeedback("", false);
}
}
QPointF fulcrum(QPointF(width() / 2.0, height() / 2.0));
QLineF vector(fulcrum, event->position());
initialRotation = m_rotation + vector.angle();
setMouseMoveData(true, event->position().x(), event->position().y());
QApplication::setOverrideCursor(Qt::ClosedHandCursor);
event->accept();
}
QOpenGLWidget::mousePressEvent(event);
}
void ImageViewer::mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton) {
setMouseMoveData(false, 0, 0);
while (QApplication::overrideCursor()) {
QApplication::restoreOverrideCursor();
}
}
QOpenGLWidget::mouseReleaseEvent(event);
}
void ImageViewer::updateRubberBandFeedback(QRect geom) {
if (animation)
return;
bool ok;
QTransform matrix = transformation().inverted(&ok);
if (!ok)
qDebug() << "something's fucked up about the transformation matrix!";
m_isoCropRect = geom = matrix.mapRect(geom);
setFeedback(tr("Selection: ") + QString("%1x%2").arg(geom.width()).arg(geom.height())
+ QString(geom.x() < 0 ? "%1" : "+%1").arg(geom.x())
+ QString(geom.y() < 0 ? "%1" : "+%1").arg(geom.y()), false);
static QTimer *doubleclickhint = nullptr;
if (!doubleclickhint) {
doubleclickhint = new QTimer(this);
doubleclickhint->setInterval(2000);
doubleclickhint->setSingleShot(true);
connect(doubleclickhint, &QTimer::timeout, [this]() {
if (cropRubberBand && cropRubberBand->isVisible())
setFeedback(tr("Doubleclick to crop, right click to abort"), 10000);
});
}
doubleclickhint->start();
}
void ImageViewer::setEditMode(Edit mode) {
m_editMode = mode;
QString msg;
switch (m_editMode) {
case Crop:
msg = tr("Select the crop area with Shift + left mouse button"); break;
case Blackout:
msg = tr("Select the blackout area with Shift + left mouse button"); break;
case Cartouche:
msg = tr("Select the cartouche area with Shift + left mouse button"); break;
case Annotate:
msg = tr("Select the annotation area with Shift + left mouse button"); break;
default:
qDebug() << "wtf";
break;
}
setFeedback(msg, 5000);
}
void ImageViewer::edit() {
if (animation || !cropRubberBand)
return;
cropRubberBand->hide();
bool ok;
QTransform matrix = transformation().inverted(&ok);
if (!ok) {
qDebug() << "something's fucked up about the transformation matrix! Not cropping";
return;
}
QPainter p(&origImage);
p.setTransform(matrix);
p.setRenderHint(QPainter::Antialiasing);
const QRect rect = cropRubberBand->geometry();
switch (m_editMode) {
case Blackout:
case Cartouche: {
QColor c = QColorDialog::getColor(Qt::black, this, tr("Pick a color"));
if (!c.isValid())
return setFeedback("", false);
if (m_editMode == Blackout) {
p.setPen(Qt::transparent);
p.setBrush(c);
} else {
p.setBrush(Qt::transparent);
p.setPen(QPen(c, 4));
}
const int radius = qMin(rect.width(), rect.height())/2;
p.drawRoundedRect(rect, radius, radius);
break;
}
case Annotate: {
QDialog dlg(this);
QColor c = Qt::black;
QVBoxLayout *vl = new QVBoxLayout(&dlg);
QHBoxLayout *hl = new QHBoxLayout;
QFontComboBox *fonts = new QFontComboBox(&dlg);
hl->addWidget(fonts);
QPushButton *cb = new QPushButton(tr("Color"), &dlg);
connect(cb, &QPushButton::clicked, [_LCD_,&c]() { c = QColorDialog::getColor(Qt::black, this, tr("Pick a color")); });
hl->addWidget(cb);
vl->addLayout(hl);
QTextEdit *te = new QTextEdit(&dlg);
vl->addWidget(te);
QDialogButtonBox *btns = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, &dlg);
connect(btns, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
connect(btns, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
vl->addWidget(btns);
dlg.setLayout(vl);
if (dlg.exec() == QDialog::Rejected)
return setFeedback("", false);
QString text = te->toPlainText();
if (text.isEmpty())
return setFeedback("", false);
QFont fnt = fonts->currentFont();
QSize ts = QFontMetrics(fnt).size(0, text);
qreal factor = qMin(rect.width() / qreal(ts.width()), rect.height() / qreal(ts.height()));
if (factor != 1.0)
fnt.setPointSize(fnt.pointSize()*factor);
p.setPen(c);
p.setFont(fnt);
p.drawText(rect, Qt::AlignCenter, text);
break;
}
default:
break;
}
p.end();
refresh();
setFeedback("", false);
m_edited = true;
emit imageEdited(true);
}
void ImageViewer::applyCropAndRotation() {
if (m_editMode != Crop)
return edit();
if (animation || !cropRubberBand)
return;
cropRubberBand->hide();
QTransform matrix = transformation();
bool ok;
// the inverted mapping of the crop area matches the coordinates of the original image
m_isoCropRect = matrix.inverted(&ok).mapRect(cropRubberBand->geometry());
if (!ok) {
qDebug() << "something's fucked up about the transformation matrix! Not cropping";
return;
}
if (!matrix.isRotating()) {
// … we can just copy the area, later apply flips and be done
origImage = origImage.copy(m_isoCropRect);
} else {
// The rotated case is more involved. The inverted matrix still maps image coordinates
// but that's not what the user sees or expects.
//
// This is inherently lossy because of the pixel transpositon, so special-case it
const QSize visualSize = m_currentImageSize;
float scale = qMax(float(visualSize.width()) / viewerImage.width(), float(visualSize.height()) / viewerImage.height());
if (scale <= 0.0) {
qDebug() << "something is seriously wrong with the scale, not cropping" << scale;
return;
}
// The new image size must be the size of the visible crop area, compensated for the current scale factor
QImage target(cropRubberBand->geometry().size()/scale, origImage.format());
// but still be at the same position
QRect sourceRect = target.rect();
sourceRect.moveCenter(m_isoCropRect.center());
target.fill(Qt::black /* Qt::green */);
QPainter painter(&target);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
// rotate in relation to the paint device
QPoint center(target.width() / 2, target.height() / 2);
painter.translate(center);
// onedirectional flipping inverts the rotation
if (m_flip == Qt::Horizontal || m_flip == Qt::Vertical)
painter.rotate(360.0 - m_rotation);
else
painter.rotate(m_rotation);
painter.translate(-center);
// offset by crop rect
painter.translate(-sourceRect.topLeft());
// crop
painter.drawImage(0,0, origImage);
painter.end();
origImage = target;
}
// apply flip-flop
#if QT_VERSION < QT_VERSION_CHECK(6, 9, 0)
origImage.mirror(m_flip & Qt::Horizontal, m_flip & Qt::Vertical);
#else
origImage.flip(m_flip);
#endif
// reset transformations for the new image
if (!batchMode) {
m_flip = Qt::Orientations();
m_rotation = 0;
if (!m_lockZoom) {
m_zoomMode = ZoomToFit;
}
m_isoCropRect = QRect(); // invalidate
}
refresh();
setFeedback("", false);
setFeedback(tr("New image size: %1x%2").arg(origImage.width()).arg(origImage.height()));
m_edited = true;
emit imageEdited(true);
}
bool ImageViewer::flip(Qt::Orientations o) {
m_flip ^= o;
update();
QStringList feedback;
if (o & Qt::Horizontal)
feedback << ((m_flip & Qt::Horizontal) ? tr("Flipped Horizontally") : tr("Unflipped Horizontally"));
if (o & Qt::Vertical)
feedback << ((m_flip & Qt::Vertical) ? tr("Flipped Vertically") : tr("Unflipped Vertically"));
setFeedback(feedback.join("\n"));
return (m_flip & o) == o;
}
void ImageViewer::configureLetterbox() {
static CropDialog *dlg = nullptr;
if (!dlg) {
dlg = new CropDialog(this);
connect(dlg, &CropDialog::valuesChanged, [this](int left, int top, int right, int bottom) {
m_letterbox = QRect(QPoint(left, top), QPoint(100-right, 100-bottom));
update();
});
}
dlg->exec();
}
QSize ImageViewer::currentImageSize() const {
return origImage.size();
}
void ImageViewer::setMouseMoveData(bool lockMove, int lMouseX, int lMouseY) {
moveImageLocked = lockMove;
mouseX = lMouseX;
mouseY = lMouseY;
layoutX = m_currentImagePos.x();
layoutY = m_currentImagePos.y();
}
void ImageViewer::mouseMoveEvent(QMouseEvent *event) {
if (event->modifiers() == Qt::ShiftModifier) {
if (!cropRubberBand || !cropRubberBand->isVisible()) {
return;
}
QRect newRect;
newRect = QRect(cropOrigin, event->pos());
/*** @todo this doesn't work at all and also the resize typically happens unconstrained using the qsizegrip
figure whether to keep this at all
// Force square
if (event->modifiers() & Qt::ControlModifier) {
const int deltaX = cropOrigin.x() - event->pos().x();
const int deltaY = cropOrigin.y() - event->pos().y();
newRect.setSize(QSize(-deltaX, deltaY < 0 ? qAbs(deltaX) : -qAbs(deltaX)));
}
**/
cropRubberBand->setGeometry(newRect.normalized());
} else if (Settings::mouseRotateEnabled || event->modifiers() == Qt::ControlModifier) {
QPointF fulcrum(QPointF(width() / 2.0, height() / 2.0));
QLineF vector(fulcrum, event->position());
m_rotation = initialRotation - vector.angle();
if (qAbs(m_rotation) > 360.0)
m_rotation -= int(360*m_rotation)/360;
if (m_rotation < 0)
m_rotation += 360.0;
update();
setFeedback(tr("Rotation %1°").arg(qRound(m_rotation)));
// qDebug() << "image center" << fulcrum << "line" << vector << "angle" << vector.angle() << "geom" << geometry();
} else if (moveImageLocked) {
int newX = layoutX;
int newY = layoutY;
if (m_rotation != 0) {
QPointF fulcrum(QPointF(width() / 2.0, height() / 2.0));
QLineF vector(fulcrum, event->pos());
vector.setAngle(vector.angle() + m_rotation);
newX += qRound(vector.x2());
newY += qRound(vector.y2());
vector.setP2(QPoint(mouseX, mouseY));
vector.setAngle(vector.angle() + m_rotation);
newX -= qRound(vector.x2());
newY -= qRound(vector.y2());
} else {
newX += event->pos().x() - mouseX;
newY += event->pos().y() - mouseY;
}
bool needToMove = m_rotation != 0;
if (!needToMove) {
if (m_currentImageSize.width() > size().width()) {
if (newX > 0) {
newX = 0;
} else if (newX < (size().width() - m_currentImageSize.width())) {
newX = (size().width() - m_currentImageSize.width());
}
needToMove = true;
} else {
newX = layoutX;
}
if (m_currentImageSize.height() > size().height()) {
if (newY > 0) {
newY = 0;
} else if (newY < (size().height() - m_currentImageSize.height())) {
newY = (size().height() - m_currentImageSize.height());
}
needToMove = true;
} else {
newY = layoutY;
}
}
if (needToMove) {
setImagePosition(QPoint(newX, newY));
}
}
}
void ImageViewer::slideImage(QPoint delta) {
QPoint newPos = m_currentImagePos + delta;
layoutX = newPos.x();
layoutY = newPos.y();
if (m_rotation != 0) {
QPointF fulcrum(QPointF(width() / 2.0, height() / 2.0));
QLineF vector(QPoint(0,0), delta);
vector.setAngle(vector.angle() + m_rotation);
newPos = m_currentImagePos + vector.p2().toPoint();
}
bool needToMove = m_rotation != 0;
if (!needToMove) {
if (m_currentImageSize.width() > size().width()) {
if (newPos.x() > 0) {
newPos.setX(0);
} else if (newPos.x() < (size().width() - m_currentImageSize.width())) {
newPos.setX(size().width() - m_currentImageSize.width());
}
needToMove = true;
}
if (m_currentImageSize.height() > size().height()) {
if (newPos.y() > 0) {
newPos.setY(0);
} else if (newPos.y() < (size().height() - m_currentImageSize.height())) {
newPos.setY(size().height() - m_currentImageSize.height());
}
needToMove = true;
}
}
if (needToMove) {
setImagePosition(newPos);
}
}
void ImageViewer::saveImage() {
if (newImage) {
saveImageAs();
return;
}
setFeedback(tr("Saving..."));
QImageReader imageReader(fullImagePath);
QString savePath = fullImagePath;
if (!Settings::saveDirectory.isEmpty()) {
QDir saveDir(Settings::saveDirectory);
savePath = saveDir.filePath(QFileInfo(fullImagePath).fileName());
}
bool exifError = false;
if (savePath == fullImagePath)
exifError = !Metadata::buffer(fullImagePath);
QTransform matrix;
if (Settings::exifRotationEnabled) // undo previous exif rotation for saving
matrix = Metadata::transformation(fullImagePath).inverted();
int rotation = qRound(m_rotation);
if (!batchMode && (m_flip || !(rotation % 90))) {
matrix.scale(m_flip & Qt::Horizontal ? -1 : 1, m_flip & Qt::Vertical ? -1 : 1);
if (!(rotation % 90))
matrix.rotate((m_flip == Qt::Horizontal || m_flip == Qt::Vertical) ? 360-rotation : rotation);
viewerImage = viewerImage.transformed(matrix);
}
if (!viewerImage.save(savePath, imageReader.format().toUpper(), Settings::defaultSaveQuality)) {
return MessageBox(this).critical(tr("Error"), tr("Failed to save image."));
}
if (!exifError) {
exifError = !(savePath == fullImagePath ? Metadata::writeBuffer(viewerImage) : Metadata::copy(fullImagePath, savePath, viewerImage));
static bool showExifError = true;
if (exifError && showExifError) {
MessageBox msgBox(this);
QCheckBox cb(tr("Don't show this message again"));
msgBox.setCheckBox(&cb);
msgBox.critical(tr("Error"), tr("Failed to save Exif metadata."));
showExifError = !(cb.isChecked());
}
}
m_edited = false;
reload();
setFeedback(tr("Image saved."));
emit imageSaved(savePath);
}
void ImageViewer::saveImageAs() {
setCursorHiding(false);
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save image as"),
fullImagePath,
tr("Images") +
" (*.jpg *.jpeg *.png *.bmp *.tif *.tiff *.ppm *.pgm *.pbm *.xbm *.xpm *.cur *.ico *.icns *.wbmp *.webp)");
if (!fileName.isEmpty()) {
int rotation = qRound(m_rotation);
if (!batchMode && (m_flip || !(rotation % 90))) {
QTransform matrix;
matrix.scale(m_flip & Qt::Horizontal ? -1 : 1, m_flip & Qt::Vertical ? -1 : 1);
if (!(rotation % 90))
matrix.rotate((m_flip == Qt::Horizontal || m_flip == Qt::Vertical) ? 360-rotation : rotation);
viewerImage = viewerImage.transformed(matrix);
}
if (!viewerImage.save(fileName, 0, Settings::defaultSaveQuality)) {
MessageBox(this).critical(tr("Error"), tr("Failed to save image."));
} else {
Metadata::copy(fullImagePath, fileName, viewerImage);
m_edited = false;
setFeedback(tr("Image saved."));
}
}
if (window()->isFullScreen()) {
setCursorHiding(true);
}
}
void ImageViewer::contextMenuEvent(QContextMenuEvent *) {
// if (Settings::layoutMode != Phototonic::ImageViewWidget)
// return;
if (QMenu *em = myContextMenu->findChild("image_edit_menu"))
em->setEnabled(!animation);
while (QApplication::overrideCursor()) {
QApplication::restoreOverrideCursor();
}
m_contextSpot = mapFromGlobal(QCursor::pos());
myContextMenu->exec(QCursor::pos());
}
void ImageViewer::focusInEvent(QFocusEvent *event) {
QOpenGLWidget::focusInEvent(event);
emit gotFocus();
}
bool ImageViewer::isNewImage() {
return newImage;
}
void ImageViewer::keepTransformation(bool yesno) {
m_keepTransform = yesno;
setFeedback(yesno ? tr("Transformations Locked") : tr("Transformations Unlocked"));
}
void ImageViewer::copyImage() {
QApplication::clipboard()->setImage(viewerImage);
}
void ImageViewer::pasteImage() {
delete animation;
animation = nullptr;
if (!QApplication::clipboard()->image().isNull()) {
origImage = QApplication::clipboard()->image();
refresh();
}
window()->setWindowTitle(tr("Clipboard") + " - Phototonic");
if (Settings::setWindowIcon) {
window()->setWindowIcon(QApplication::windowIcon());
}
}
void ImageViewer::setBackgroundColor() {
QPalette pal = palette();
pal.setColor(backgroundRole(), QColor(Settings::viewerBackgroundColor.red(), Settings::viewerBackgroundColor.green(), Settings::viewerBackgroundColor.blue()));
setPalette(pal);
}
QPoint ImageViewer::contextSpot() {
return m_contextSpot;
}
QSize ImageViewer::sizeHint() const
{
return m_currentImage.size();
}
void ImageViewer::paintEvent(QPaintEvent *ev)
{
float scale = qMax(float(m_currentImageSize.width()) / m_currentImage.width(), float(m_currentImageSize.height()) / m_currentImage.height());
if (scale == 0.0f)
return;
QPainter painter(this);
painter.fillRect(rect(), palette().color(backgroundRole()));
painter.setRenderHint(QPainter::SmoothPixmapTransform);
QRect clip = rect();
clip.adjust(qRound(width()*m_letterbox.x()/100.0),
qRound(height()*m_letterbox.y()/100.0),
-qRound(width()*(100-m_letterbox.right())/100.0),
-qRound(height()*(100-m_letterbox.bottom())/100.0));
painter.setClipRect(clip);
// exif
/// @todo this doesn't work, because the width/height are swapped and the translation is off/inverted
// I don't want to copy the Image into a pre-translation, but for now that's what we'll do
// painter.setWorldTransform(m_exifTransformation);
painter.setTransform(transformation());
if (m_crossfade)
painter.setOpacity(1.0 - m_fadeout);
painter.drawImage(0,0, m_currentImage);
if (m_crossfade) {
if (m_prevImage.size().isNull())
return;
scale = qMax(float(m_currentImageSize.width()) / m_prevImage.width(), float(m_currentImageSize.height()) / m_prevImage.height());
if (scale == 0.0f)
return;
painter.setTransform(transformation(m_prevImage, m_prevImageSize, m_prevImagePos));
painter.setOpacity(m_fadeout);
painter.drawImage(0,0, m_prevImage);
}
if (m_showGrid) {
painter.setTransform(QTransform());
painter.setCompositionMode(QPainter::CompositionMode_Exclusion);
painter.setPen(Qt::white);
const int d = qMax(10, qMax(height()/100, width()/100));
for (int x = d; x < width(); x += d)
painter.drawLine(x, 0, x, height());
for (int y = d; y < height(); y += d)
painter.drawLine(0, y, width(), y);
}
}
phototonic-3.3.0/ImageViewer.h 0000664 0000000 0000000 00000012515 15271130355 0016266 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef IMAGE_VIEWER_H
#define IMAGE_VIEWER_H
class CropRubberBand;
class QMovie;
class QThread;
#include
#include
#include
#include
class ImageViewer : public QOpenGLWidget {
Q_OBJECT
public:
ImageViewer(QWidget *parent);
bool batchMode = false;
QString fullImagePath;
enum ZoomMode {
ZoomOriginal = 0,
ZoomToFit,
ZoomToFill
};
enum Edit {
Crop = 0,
Blackout,
Cartouche,
Annotate
};
enum Rotate {
Direct = 0, CW, CCW
};
void clearImage();
void configureLetterbox();
bool crossfade() const { return m_crossfade; }
QSize currentImageSize() const;
void edit();
bool flip(Qt::Orientations o);
Qt::Orientations flipping() const { return m_flip; }
bool isNewImage();
void keepTransformation(bool yesno);
QRect lastCropGeometry() const { return m_isoCropRect; }
void loadImage(QString imageFileName, const QImage &preview = QImage());
void preload(QString imageFileName);
void refresh();
void resizeImage(QPoint focus = QPoint(-1, -1));
void rotateTo(qreal r, Rotate direction);
qreal rotation() const { return m_rotation; }
void scaleImage(QSize newSize);
void secureEdits();
void setBackgroundColor();
void setContextMenu(QMenu *);
void setCrossfade(bool yesno);
void setCursorHiding(bool hide);
void setEditMode(Edit mode);
void setFeedback(QString feedbackString, int timeLimited = 3000);
void setInfo(QString infoString);
void showFileName(bool yesno) { myFilenameLabel->setVisible(yesno); }
void showGrid(bool show) { m_showGrid = show; update(); }
void slideImage(QPoint delta);
float zoom() const { return m_zoom; }
ZoomMode zoomMode() const { return m_zoomMode; }
void zoomTo(ZoomMode mode, QPoint focus = QPoint(-1,-1), int duration = 125);
void zoomTo(float percent, QPoint focus = QPoint(-1,-1), int duration = 125);
QPoint contextSpot();
signals:
void gotFocus();
void toolsUpdated();
void imageEdited(bool);
void imageSaved(const QString &imageFileName);
void imageLoaded();
public slots:
void applyCropAndRotation();
void lockZoom(bool);
void monitorCursorState();
void saveImage();
void saveImageAs();
void copyImage();
void pasteImage();
void reload();
private slots:
void unsetFeedback();
void updateRubberBandFeedback(QRect geom);
protected:
void contextMenuEvent(QContextMenuEvent *event);
void focusInEvent(QFocusEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event);
void showEvent(QShowEvent *event);
QSize sizeHint() const override;
private:
QMenu *myContextMenu;
QLabel *myFilenameLabel;
QImage origImage;
QImage viewerImage;
QImage m_preloadedImage;
QImage m_currentImage;
QImage m_prevImage;
QString m_preloadedPath;
QString m_preloadPath;
QThread *m_preloadThread;
bool m_loading;
bool m_crossfade;
QTimer *mouseMovementTimer;
QPointer animation;
bool newImage;
bool cursorIsHidden;
bool moveImageLocked;
qreal initialRotation = 0;
int mouseX;
int mouseY;
int layoutX;
int layoutY;
QLabel *feedbackLabel;
QPoint cropOrigin;
QPoint m_contextSpot;
QTransform m_exifTransformation;
QString m_permanentFeedback;
QRect m_letterbox;
CropRubberBand *cropRubberBand;
QRect m_isoCropRect;
ZoomMode m_zoomMode;
float m_zoom;
bool m_lockZoom;
Edit m_editMode;
bool m_edited;
Qt::Orientations m_flip;
void setMouseMoveData(bool lockMove, int lMouseX, int lMouseY);
void centerImage(QSize imgSize);
void colorize();
void colorize(uchar*, int, int, int, const unsigned char(*)[256], const unsigned char(*)[256]); // thread helper
void setImage(const QImage &i);
QTransform transformation(const QImage &img, const QSize &sz, const QPoint &pos) const;
QTransform transformation() const;
const QPoint &imagePosition() const;
const QSize &imageSize() const;
void setImagePosition(const QPoint &p);
void setFlip(Qt::Orientations o);
qreal m_rotation = 0;
QSize m_currentImageSize;
QPoint m_currentImagePos;
QSize m_prevImageSize;
QPoint m_prevImagePos;
float m_fadeout;
bool m_showGrid;
bool m_keepTransform;
};
#endif // IMAGE_VIEWER_H
phototonic-3.3.0/InfoViewer.cpp 0000664 0000000 0000000 00000042022 15271130355 0016466 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "MetadataCache.h"
#include "InfoViewer.h"
#include "Settings.h"
InfoView::InfoView(QWidget *parent) : QWidget(parent) {
infoViewerTable = new QTableView(this);
infoViewerTable->setSelectionMode(QAbstractItemView::SingleSelection/* ExtendedSelection makes no sense wrt the copy feature*/);
infoViewerTable->setSelectionBehavior(QAbstractItemView::SelectRows/* SelectItems dto*/);
infoViewerTable->verticalHeader()->setVisible(false);
infoViewerTable->verticalHeader()->setDefaultSectionSize(infoViewerTable->verticalHeader()->minimumSectionSize());
infoViewerTable->horizontalHeader()->setVisible(false);
infoViewerTable->setEditTriggers(QAbstractItemView::DoubleClicked /* QAbstractItemView::NoEditTriggers */);
infoViewerTable->setTabKeyNavigation(false);
infoViewerTable->setShowGrid(false);
imageInfoModel = new QStandardItemModel(this);
infoViewerTable->setModel(imageInfoModel);
// Menu
QAction *copyAction = new QAction(tr("Copy"), this);
connect(copyAction, SIGNAL(triggered()), this, SLOT(copyEntry()));
m_removeAction = new QAction(tr("Remove"), this);
connect(m_removeAction, SIGNAL(triggered()), this, SLOT(removeEntry()));
infoMenu = new QMenu("");
infoMenu->addAction(copyAction);
infoMenu->addAction(m_removeAction);
infoViewerTable->setContextMenuPolicy(Qt::CustomContextMenu);
connect(infoViewerTable, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showInfoViewMenu(QPoint)));
// Filter items
m_filter = new QComboBox(this);
m_filter->setEditable(true);
m_filter->lineEdit()->setPlaceholderText(tr("Filter Items"));
m_filter->addItems(Settings::exifFilters.keys());
m_filter->setEditText(QString()); // start w/ empty filter
m_manageFiltersButton = new QPushButton("+", this);
connect(m_manageFiltersButton, &QPushButton::clicked, [this]() {
bool ok;
QString filter = Settings::exifFilters.value(m_filter->currentText());
QString dlgTitle, dlgText;
if (filter.isEmpty()) {
dlgTitle = tr("Enter filter name");
dlgText = tr("Enter a name (without leading \"$\") for this filter.\n"
"The special name\"preview\" is used for the filter in the viewer.");
} else {
dlgTitle = tr("Edit filter: %1").arg(filter);
dlgText = tr("Clearing the filter will delete it.");
}
QString n = QInputDialog::getText(this, dlgTitle, dlgText, QLineEdit::Normal, filter, &ok);
ok = ok && !(filter.isEmpty() && n.isEmpty()); // no filter name given
if (!ok)
return;
if (filter.isEmpty()) { // save new variable
Settings::exifFilters.insert("$"+n, m_filter->currentText());
m_filter->addItem("$"+n);
m_filter->setEditText("$"+n);
return;
}
if (n.isEmpty()) { // filter deleted
Settings::exifFilters.remove(m_filter->currentText());
m_filter->removeItem(m_filter->currentIndex());
m_filter->setEditText(QString());
} else { // store new filter
Settings::exifFilters.insert(m_filter->currentText(), n);
if (n != filter)
filterItems(); // filter changed, update
}
});
connect(m_filter, SIGNAL(currentTextChanged(const QString&)), this, SLOT(filterItems()));
m_saveExifButton = new QPushButton(tr("Save EXIF changes"), this);
connect(m_saveExifButton, SIGNAL(clicked()), this, SLOT(saveExifChanges()));
QVBoxLayout *infoViewerLayout = new QVBoxLayout(this);
QHBoxLayout *histLayout = new QHBoxLayout;
histLayout->addStretch();
histLayout->addWidget(m_histogram = new QLabel(this));
m_histogram->setToolTip(tr("Left click: toggle logarithmic scale\nRight click: toggle size\nHide with filter: |nohistogram|"));
histLayout->addStretch();
infoViewerLayout->addLayout(histLayout);
infoViewerLayout->addWidget(infoViewerTable);
infoViewerLayout->addWidget(m_saveExifButton);
QHBoxLayout *filterLayout = new QHBoxLayout;
filterLayout->addWidget(m_filter, 100);
filterLayout->addWidget(m_manageFiltersButton);
infoViewerLayout->addLayout(filterLayout);
setLayout(infoViewerLayout);
m_histogram->installEventFilter(this);
infoViewerTable->installEventFilter(this);
}
bool InfoView::eventFilter(QObject *o, QEvent *e) {
if (o == m_histogram && e->type() == QEvent::MouseButtonPress) {
QMouseEvent *me = static_cast(e);
if (me->button() == Qt::LeftButton) {
emit histogramClicked();
} else if (me->button() == Qt::RightButton) {
m_histogram->setScaledContents(!m_histogram->hasScaledContents());
if (m_histogram->hasScaledContents()) {
m_histogram->setFixedSize(32,20);
} else {
m_histogram->setFixedSize(m_histogram->pixmap().size());
}
}
} else if (o == infoViewerTable && e->type() == QEvent::KeyPress && static_cast(e)->key() == Qt::Key_Delete) {
const QModelIndexList &selection = infoViewerTable->selectionModel()->selectedIndexes();
if (!selection.isEmpty()) {
selectedEntry = selection.first();
removeEntry();
}
}
return QWidget::eventFilter(o, e);
}
void InfoView::showInfoViewMenu(QPoint pt) {
selectedEntry = infoViewerTable->indexAt(pt);
if (selectedEntry.column() == 0)
selectedEntry = selectedEntry.siblingAtColumn(1);
if (selectedEntry.isValid() && infoViewerTable->columnSpan(selectedEntry.row(), 0) == 1) {
QStandardItem *item = imageInfoModel->itemFromIndex(selectedEntry);
m_removeAction->setVisible(item && item->isEditable());
infoMenu->popup(infoViewerTable->viewport()->mapToGlobal(pt));
}
}
void InfoView::clear() {
m_currentFile.clear();
imageInfoModel->clear();
}
void ExifItem::setData(const QVariant &value, int role) {
if (role == Qt::EditRole)
QStandardItem::setData(value, Qt::UserRole + 1);
else
QStandardItem::setData(value, role);
}
QVariant ExifItem::data(int role) const {
if (role == Qt::EditRole)
return QStandardItem::data(Qt::UserRole + 1);
else
return QStandardItem::data(role);
}
void InfoView::addEntry(QString key, QString value, bool editable, QString editValue) {
int atRow = imageInfoModel->rowCount();
QStandardItem *itemKey = new QStandardItem(key);
itemKey->setEditable(false);
imageInfoModel->insertRow(atRow, itemKey);
if (!value.isEmpty()) {
ExifItem *itemVal = new ExifItem(value);
itemVal->setToolTip(value);
itemVal->setEditable(editable);
itemVal->setData(editValue, Qt::EditRole);
imageInfoModel->setItem(atRow, 1, itemVal);
}
}
void InfoView::addTitleEntry(QString title) {
int atRow = imageInfoModel->rowCount();
QStandardItem *itemKey = new QStandardItem(title);
itemKey->setEditable(false);
imageInfoModel->insertRow(atRow, itemKey);
QFont boldFont;
boldFont.setBold(true);
itemKey->setData(boldFont, Qt::FontRole);
infoViewerTable->setSpan(atRow, 0, 1, 2);
}
void InfoView::copyEntry() {
if (selectedEntry.isValid()) {
QApplication::clipboard()->setText(imageInfoModel->itemFromIndex(selectedEntry)->toolTip());
}
}
void InfoView::removeEntry() {
if (selectedEntry.isValid()) {
imageInfoModel->removeRows(selectedEntry.row(), 1);
m_saveExifButton->show();
selectedEntry = QModelIndex();
}
}
void InfoView::showSaveButton(QStandardItem *changedItem) {
if (changedItem) {
imageInfoModel->blockSignals(true);
changedItem->setData(changedItem->data(Qt::EditRole), Qt::DisplayRole);
imageInfoModel->blockSignals(false);
}
m_saveExifButton->show();
}
void InfoView::saveExifChanges() {
Metadata::DataPair EXIF, IPTC, XMP;
Metadata::DataPair *data = nullptr;
for (int i = 0; i < imageInfoModel->rowCount(); ++i) {
if (infoViewerTable->columnSpan(i, 0) > 1) { // title
if (imageInfoModel->item(i)->text() == "Exif")
data = &EXIF;
else if (imageInfoModel->item(i)->text() == "IPTC")
data = &IPTC;
else if (imageInfoModel->item(i)->text() == "XMP")
data = &XMP;
continue; // title
}
if (!imageInfoModel->item(i, 1) || imageInfoModel->item(i, 1)->text().isEmpty())
continue; // empty field
if (!imageInfoModel->item(i, 1)->isEditable())
continue; // static data, brightness, file stats - not metadata
if (!data) {
qDebug() << "WAHHHHHH! (headless metadata!)" << imageInfoModel->item(i)->text();
continue;
}
data->insert(imageInfoModel->item(i)->text(), imageInfoModel->item(i, 1)->text());
}
Metadata::setData(m_currentFile, EXIF, IPTC, XMP);
m_saveExifButton->hide();
reloadExifData();
emit exifChanged(m_currentFile);
}
void InfoView::reloadExifData() {
const QString currentFile = m_currentFile;
m_currentFile = QString();
const QPixmap histogram = m_histogram->pixmap();
read(currentFile, QImage());
m_histogram->setPixmap(histogram);
}
void InfoView::filterItems() {
QString filter = Settings::exifFilters.value(m_filter->currentText());
if (filter.isEmpty()) {
m_manageFiltersButton->setText("+");
filter = m_filter->currentText();
} else {
m_manageFiltersButton->setText("=");
}
const bool nohistogram = filter.contains("|nohistogram|");
if (nohistogram)
filter.remove("|nohistogram|");
m_histogram->setVisible(!nohistogram);
const bool showFileStats = filter.contains("|filestats|");
if (showFileStats)
filter.remove("|filestats|");
QRegularExpression re(filter, QRegularExpression::CaseInsensitiveOption);
if (!re.isValid()) {
m_manageFiltersButton->setEnabled(false);
QPalette pal = m_filter->palette();
pal.setColor(QPalette::Text, 0xd01717); // force my idea of Qt::red on everyone
m_filter->setPalette(pal);
return;
}
const bool hot = !filter.isEmpty();
m_manageFiltersButton->setEnabled(hot);
m_filter->setPalette(QPalette());
int lastHeader = -1;
bool allHidden = true;
for (int i = 0; i < imageInfoModel->rowCount(); ++i) {
if (infoViewerTable->columnSpan(i, 0) > 1) { // title
infoViewerTable->setRowHidden(i, false);
if (allHidden && lastHeader > -1)
infoViewerTable->setRowHidden(lastHeader, true);
lastHeader = i;
allHidden = true;
infoViewerTable->setRowHidden(i, false);
continue;
}
const bool hidden = hot && (!showFileStats || lastHeader > 0) && !imageInfoModel->item(i)->text().contains(re);
infoViewerTable->setRowHidden(i, hidden);
allHidden = allHidden && hidden;
}
if (allHidden && lastHeader > -1)
infoViewerTable->setRowHidden(lastHeader, true);
}
void InfoView::hint(QString key, QString value) {
m_hints[key] = value;
}
QString InfoView::html() const {
QRegularExpression re;
bool showFileStats = false;
QString filter = Settings::exifFilters.value("$preview");
if (!filter.isEmpty()) {
if (filter.contains("|filestats|")) {
showFileStats = true;
filter.remove("|filestats|");
}
re = QRegularExpression(filter, QRegularExpression::CaseInsensitiveOption);
if (!re.isValid()) {
qWarning() << "invalid custom preview filter" << filter;
filter = QString();
}
}
if (filter.isEmpty()) {
showFileStats = true;
filter ="^("
"lensmodel|make|model"
"|exposuretime|exposureprogram|flash|fnumber|focallength|isospeedratings"
"|artist|copyright|datetime|keywords|software"
")$";
re = QRegularExpression(filter, QRegularExpression::CaseInsensitiveOption);
}
QString text = "";
QString lastHeader, lastTag;
for (int i = 0; i < imageInfoModel->rowCount(); ++i) {
if (infoViewerTable->columnSpan(i, 0) > 1) {
showFileStats = showFileStats && !i; // file stats header is on 0
lastHeader = imageInfoModel->item(i)->text();
continue;
}
QString tag = imageInfoModel->item(i)->text();
if ((showFileStats || tag.contains(re)) && imageInfoModel->item(i, 1)) {
if (!lastHeader.isNull()) {
text += "| " + lastHeader + " |
";
lastHeader = QString();
}
static const QRegularExpression newline("[\r\n]+");
QString value = imageInfoModel->item(i, 1)->text();
value.replace(newline, "
");
if (lastTag == tag)
tag = QString();
else
lastTag = tag;
text += "| " + tag + " | " + value + " |
";
}
}
text += "
";
return text;
}
void InfoView::read(QString imageFullPath, const QImage &histogram) {
m_histogram->setPixmap(QPixmap::fromImage(histogram));
if (m_currentFile == imageFullPath)
return;
m_saveExifButton->hide();
disconnect(imageInfoModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(showSaveButton(QStandardItem*)));
clear();
QFileInfo imageInfo = QFileInfo(imageFullPath);
if (!imageInfo.exists())
return;
m_currentFile = imageFullPath;
QString key;
QString val;
addTitleEntry(tr("Image"));
addEntry(tr("File name"), imageInfo.fileName());
addEntry(tr("Location"), imageInfo.path());
addEntry(key = tr("Size"), QString::number(imageInfo.size() / 1024.0, 'f', 2) + "K");
addEntry(tr("Modified"), imageInfo.lastModified().toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat)));
QImageReader imageInfoReader(imageFullPath);
if (imageInfoReader.size().isValid()) {
addEntry(tr("Format"), imageInfoReader.format().toUpper());
const QSize sz = imageInfoReader.size();
addEntry(tr("Resolution"), QString::number(sz.width()) + "x" + QString::number(sz.height()));
addEntry(tr("Megapixel"), QString::number((sz.width() * sz.height()) / 1000000.0, 'f', 2));
for (auto i = m_hints.cbegin(), end = m_hints.cend(); i != end; ++i)
addEntry(i.key(), i.value());
const QStringList textKeys = imageInfoReader.textKeys();
if (!textKeys.isEmpty()) {
addTitleEntry("Text");
for (const QString &textKey : imageInfoReader.textKeys()) {
const QString text = imageInfoReader.text(textKey);
addEntry(textKey, text/* , true, text */);
}
}
} else {
imageInfoReader.read();
key = tr("Error");
val = imageInfoReader.errorString();
addEntry(key, val);
}
Metadata::DataTriple EXIF, IPTC, XMP;
Metadata::data(imageFullPath, &EXIF, &IPTC, &XMP);
if (!EXIF.isEmpty()) {
addTitleEntry("Exif");
for (auto i = EXIF.cbegin(), end = EXIF.cend(); i != end; ++i)
addEntry(i.key(), i.value().first, true, i.value().second);
}
if (!IPTC.isEmpty()) {
addTitleEntry("IPTC");
for (auto i = IPTC.cbegin(), end = IPTC.cend(); i != end; ++i)
addEntry(i.key(), i.value().first, true, i.value().second);
}
if (!XMP.isEmpty()) {
addTitleEntry("XMP");
for (auto i = XMP.cbegin(), end = XMP.cend(); i != end; ++i)
addEntry(i.key(), i.value().first, true, i.value().second);
}
infoViewerTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
infoViewerTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
filterItems();
connect(imageInfoModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(showSaveButton(QStandardItem*)));
}
phototonic-3.3.0/InfoViewer.h 0000664 0000000 0000000 00000004530 15271130355 0016135 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef INFO_VIEWER_H
#define INFO_VIEWER_H
class QComboBox;
class QLabel;
class QMenu;
class QPushButton;
class QStandardItemModel;
class QTableView;
#include
#include
#include
#include
class ExifItem : public QStandardItem {
public:
using QStandardItem::QStandardItem;
void setData(const QVariant &value, int role = Qt::UserRole + 1) override;
QVariant data(int role = Qt::UserRole + 1) const override;
};
class InfoView : public QWidget {
Q_OBJECT
public:
InfoView(QWidget *parent);
void clear();
void hint(QString key, QString value);
QString html() const;
void read(QString imageFullPath, const QImage &histogram = QImage());
void reloadExifData();
signals:
void histogramClicked();
void exifChanged(const QString &fileName);
protected:
bool eventFilter(QObject *o, QEvent *e) override;
private slots:
void copyEntry();
void filterItems();
void removeEntry();
void saveExifChanges();
void showInfoViewMenu(QPoint pt);
void showSaveButton(QStandardItem *changedItem);
private:
void addEntry(QString key, QString value, bool editable = false, QString editValue = QString());
void addTitleEntry(QString title);
QTableView *infoViewerTable;
QStandardItemModel *imageInfoModel;
QModelIndex selectedEntry;
QMenu *infoMenu;
QComboBox *m_filter;
QPushButton *m_manageFiltersButton;
QString m_currentFile;
QMap m_hints;
QLabel *m_histogram;
QAction *m_removeAction;
QPushButton *m_saveExifButton;
};
#endif // INFO_VIEWER_H
phototonic-3.3.0/MessageBox.cpp 0000664 0000000 0000000 00000020174 15271130355 0016452 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include "MessageBox.h"
#include "Phototonic.h"
#if __cplusplus >= 202002L
#define _LCD_ =,this
#else
#define _LCD_ =
#endif
MessageBox::MessageBox(QWidget *parent, StandardButtons buttons, StandardButton defaultButton) : QMessageBox(parent) {
setWindowIcon(QIcon(":/images/phototonic.png"));
if (buttons != NoButton) {
setStandardButtons(buttons);
if (defaultButton != NoButton)
setDefaultButton(defaultButton);
}
}
int MessageBox::ask(const QString &title, const QString &message) {
setWindowTitle(title);
setText(message);
setIcon(MessageBox::Question);
return exec();
}
void MessageBox::critical(const QString &title, const QString &message) {
setWindowTitle(title);
setText(message);
setIcon(MessageBox::Critical);
exec();
}
int MessageBox::warning(const QString &title, const QString &message) {
setWindowTitle(title);
setText(message);
setIcon(MessageBox::Warning);
return exec();
}
void MessageBox::about() {
QStringList contributers;
contributers // << "Code: Ofer Kashayov" // oferkv@gmail.com
<< "Alphatests: Standreas (stefonarch)" // github.com/stefonarch
<< "Code: Christopher Roy Bratusek" // nano@jpberlin.de
<< "Code: Krzysztof Pyrkosz" // pyrkosz@o2.pl
<< "Code: Roman Chistokhodov" // freeslave93@gmail.com
<< "Code: Tung Le (https://github.com/everbot)" //
<< "Code: Peter Mattern (https://github.com/pmattern)" //
<< "Code: Thomas Lübking - some patches in 2015 ;)" // thomas.luebking@gmail.com
<< "Bosnian: Dino Duratović" // dinomol@mail.com
<< "Chinese: BigELK176 ≡" //
<< "Chinese: wenchao-cui" //
<< "Croatian: Dino Duratović" // dinomol@mail.com
<< "Croatian: milotype" //
<< "Czech: Pavel Fric" // pavelfric@seznam.cz
<< "Czech: p-bo" //
<< "Dutch: Heimen Stoffels" //
<< "Estonian: Priit Jõerüüt" //
<< "Finnish: sudoasd" //
<< "French: Adrien Daugabel" // adrien.d@mageialinux-online.org
<< "French: David Geiger" // david.david@mageialinux-online.org
<< "French: Nicolas PARLANT" //
<< "French: Oliver Chiasson" //
<< "French: Rémi Verschelde" // akien@mageia.org
<< "Georgian: NorwayFun" //
<< "German: Damir Perisa" //
<< "German: Demian" //
<< "German: Ettore Atalan" //
<< "German: Jonathan Hooverman" // jonathan.hooverman@gmail.com
<< "German: Some wordstumbling fool" // thomas.luebking@gmail.com
<< "Hebrew: Yaron Shahrabani" //
<< "Italian: Standreas (stefonarch)" // github.com/stefonarch
<< "Kabyle: ButterflyOfFire" //
<< "Lithuanian: Moo" //
<< "Polish: Jan Rolski" //
<< "Polish: Krzysztof Pyrkosz" // pyrkosz@o2.pl
<< "Polish: Robert Wojewódzki" // robwoj44@poczta.onet.pl
<< "Portuguese: Hugo Carvalho" //
<< "Portuguese: Marcos M. Nascimento" // wstlmn@uol.com.br
<< "Portuguese: virtual-hand" //
<< "Russian: Azasis" //
<< "Russian: Dmitry" //
<< "Russian: Ilya Alexandrovich" // yast4ik@gmail.com
<< "Russian: Valera" //
<< "Russian: Andrei Stepanov" //
<< "Serbian: Dino Duratović" // dinomol@mail.com
<< "Serbian: Марко Ко�тић" //
<< "Spanish: Roberalz" //
<< "Spanish: Megido" //
<< "Spanish: lq259" //
// << "Swedish: Luna Jernberg" //
<< "Swedish: bittin" //
<< "Swedish: Daniel Nylander" //
<< "Ukrainian: Ihor Hordiichuk" //
<< "Ukrainian: Earthquakehunter" //
<< "Ukrainian: opensourcemount" //
<< "Standreas and the entire LXQt weblate team"
;
QString aboutString = "Phototonic 3.3
" // + QString(VERSION)
"" + tr("Image Viewer and Organizer") + "
"
"" + tr("Home page and bug reports") + ""
"- Copyright
- "
"©2013-2018 Ofer Kashayov
"
"©2024-2026 Thomas Lübking
"
+ "
Using Qt v" + QT_VERSION_STR
+ "
Phototonic is licensed under the GNU General Public License v3
"
+ tr("Special thanks to our contributers.");
setWindowTitle(tr("About"));
setIconPixmap(QIcon(":/images/phototonic.png").pixmap(128, 128));
setText(aboutString);
setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::LinksAccessibleByKeyboard);
setInformativeText(contributers.at(0));
QWidget *magicLabel = findChild("qt_msgbox_informativelabel");
QPropertyAnimation *magicAnimation = nullptr;
if (magicLabel) {
QGraphicsOpacityEffect *magic = new QGraphicsOpacityEffect(magicLabel);
magicLabel->setGraphicsEffect(magic);
magic->setOpacity(1);
magicAnimation = new QPropertyAnimation(magic, "opacity", magic);
magicAnimation->setDuration(125);
}
int idx = 0;
QTimer *t = new QTimer(this);
t->setInterval(3000);
connect (t, &QTimer::timeout, [_LCD_,&idx]() {
idx = (idx + 1) % contributers.size();
if (magicAnimation) {
magicAnimation->setStartValue(1);
magicAnimation->setEndValue(0);
magicAnimation->setEasingCurve(QEasingCurve::OutQuad);
magicAnimation->start();
}
QTimer::singleShot(125, this, [_LCD_]() {
setInformativeText(contributers.at(idx));
if (magicAnimation) {
magicAnimation->setStartValue(0);
magicAnimation->setEndValue(1);
magicAnimation->setEasingCurve(QEasingCurve::InQuad);
magicAnimation->start();
}
});
});
t->start();
exec();
}
phototonic-3.3.0/MessageBox.h 0000664 0000000 0000000 00000002331 15271130355 0016112 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef MESSAGE_BOX_H
#define MESSAGE_BOX_H
#include
class MessageBox : public QMessageBox {
Q_OBJECT
public:
MessageBox(QWidget *parent, StandardButtons buttons = NoButton, StandardButton defaultButton = NoButton);
void about();
int ask(const QString &title, const QString &message);
void critical(const QString &title, const QString &message);
int warning(const QString &title, const QString &message);
};
#endif // MESSAGE_BOX_H
phototonic-3.3.0/MetadataCache.cpp 0000664 0000000 0000000 00000051203 15271130355 0017056 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2015 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include "Settings.h"
#include "MetadataCache.h"
namespace { // anonymous, not visible outside of this file
Q_DECLARE_LOGGING_CATEGORY(PHOTOTONIC_EXIV2_LOG)
Q_LOGGING_CATEGORY(PHOTOTONIC_EXIV2_LOG, "phototonic.exif", QtCriticalMsg)
struct Exiv2LogHandler {
static void handleMessage(int level, const char *message) {
switch(level) {
case Exiv2::LogMsg::debug:
qCDebug(PHOTOTONIC_EXIV2_LOG) << message;
break;
case Exiv2::LogMsg::info:
qCInfo(PHOTOTONIC_EXIV2_LOG) << message;
break;
case Exiv2::LogMsg::warn:
case Exiv2::LogMsg::error:
case Exiv2::LogMsg::mute:
qCWarning(PHOTOTONIC_EXIV2_LOG) << message;
break;
default:
qCWarning(PHOTOTONIC_EXIV2_LOG) << "unhandled log level" << level << message;
break;
}
}
Exiv2LogHandler() {
Exiv2::LogMsg::setHandler(&Exiv2LogHandler::handleMessage);
}
};
} // anonymous namespace
static Exiv2LogHandler gs_errorHandler;
namespace Metadata {
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#if EXIV2_TEST_VERSION(0,28,0)
#define Exiv2ImagePtr Exiv2::Image::UniquePtr
#define Exiv2ValuePtr Exiv2::Value::UniquePtr
#else
#define Exiv2ImagePtr Exiv2::Image::AutoPtr
#define Exiv2ValuePtr Exiv2::Value::AutoPtr
#endif
#if __clang__
#pragma clang diagnostic pop
#else
#pragma GCC diagnostic pop
#endif
class ImageMetadata {
public:
QSet tags;
long orientation;
qint64 date;
};
static QMap gs_cache;
// updateImageTags
bool updateTags(const QString &imageFileName, QSet tags) {
QMap::iterator it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
return false;
it->tags = tags;
return true;
}
// removeTagFromImage
bool removeTag(const QString &imageFileName, const QString &tagName) {
QMap::iterator it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
return false;
return it->tags.remove(tagName);
}
// removeImage
void forget(const QString &imageFileName) {
gs_cache.remove(imageFileName);
}
void rename(const QString &oldImageFileName, const QString &newImageFileName) {
gs_cache.insert(newImageFileName, gs_cache.take(oldImageFileName));
}
// getImageTags
const QSet &tags(const QString &imageFileName) {
static QSet dummy;
QMap::iterator it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
return dummy;
return it->tags;
}
#define WARN_LOAD "Error loading image for reading metadata"
#define WARN_WRITE "Error writing metadata to image"
QImage thumbnail(const QString &imageFullPath) {
Exiv2ImagePtr exifImage;
try {
exifImage = Exiv2::ImageFactory::open(imageFullPath.toStdString());
exifImage->readMetadata();
} catch (Exiv2::Error &error) {
qWarning() << WARN_LOAD << error.what();
return QImage();
}
Exiv2::ExifThumbC thumbc(exifImage->exifData());
Exiv2::DataBuf dbuf = thumbc.copy();
QBuffer qbuf;
qbuf.setData(dbuf.c_str(), dbuf.size());
return QImageReader(&qbuf).read();
}
static void setThumbnail(Exiv2ImagePtr &exifImage, QImage thumbnail) {
if (thumbnail.width() > 256 || thumbnail.height() > 256)
thumbnail = thumbnail.scaled(256, 256, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QBuffer qbuf;
QImageWriter writer(&qbuf, "jpeg");
writer.setOptimizedWrite(true);
writer.setProgressiveScanWrite(true);
writer.setQuality(50);
writer.write(thumbnail);
Exiv2::ExifThumb image(exifImage->exifData());
image.setJpegThumbnail(reinterpret_cast(qbuf.data().constData()), qbuf.size());
}
bool setThumbnail(const QString &imageFullPath, QImage thumbnail) {
if (thumbnail.width() < 64 && thumbnail.height() < 64) {
qWarning() << "Not writing tiny thumbnail" << thumbnail.size() << imageFullPath;
return false;
}
Exiv2ImagePtr exifImage;
try {
exifImage = Exiv2::ImageFactory::open(imageFullPath.toStdString());
exifImage->readMetadata();
} catch (Exiv2::Error &error) {
qWarning() << WARN_LOAD << error.what();
return false;
}
setThumbnail(exifImage, thumbnail);
exifImage->writeMetadata();
return true;
}
static Exiv2ImagePtr gs_exifBuffer;
bool buffer(const QString &imageFileName) {
if (gs_exifBuffer) {
qDebug() << "MEEK, buffer already in use!!!";
return false;
}
try {
gs_exifBuffer = Exiv2::ImageFactory::open(imageFileName.toStdString());
gs_exifBuffer->readMetadata();
} catch (Exiv2::Error &error) {
qWarning() << WARN_LOAD << error.what();
return false;
}
return true;
}
bool writeBuffer(QImage thumbnail) {
if (!gs_exifBuffer) {
qDebug() << "MEEK, no buffer available!!!";
return false;
}
if (!thumbnail.isNull())
setThumbnail(gs_exifBuffer, thumbnail);
bool ok = true;
try {
gs_exifBuffer->writeMetadata();
} catch (Exiv2::Error &error) {
qWarning() << WARN_WRITE << error.what();
ok = false;
}
gs_exifBuffer.reset(nullptr);
return ok;
}
bool copy(const QString &from, const QString &to, QImage thumbnail) {
Exiv2ImagePtr exifFrom, exifTo;
try {
exifFrom = Exiv2::ImageFactory::open(from.toStdString());
exifFrom->readMetadata();
exifTo = Exiv2::ImageFactory::open(to.toStdString());
exifTo->readMetadata();
} catch (Exiv2::Error &error) {
qWarning() << WARN_LOAD << error.what();
return false;
}
exifTo->setMetadata(*exifFrom);
if (!thumbnail.isNull())
setThumbnail(exifTo, thumbnail);
try {
exifTo->writeMetadata();
} catch (Exiv2::Error &error) {
qWarning() << WARN_WRITE << error.what();
return false;
}
return true;
}
// getImageOrientation
long orientation(const QString &imageFileName) {
QMap::iterator it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
cache(imageFileName);
it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
return 0;
return it->orientation;
}
qint64 dateTimeOriginal(const QString &imageFileName) {
QMap::iterator it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
cache(imageFileName);
it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
return 0;
return it->date;
}
// setImageTags
void setTags(const QString &imageFileName, QSet tags) {
gs_cache[imageFileName].tags = tags;
}
// addTagToImage
bool addTag(const QString &imageFileName, const QString &tagName) {
QMap::iterator it = gs_cache.find(imageFileName);
if (it == gs_cache.end())
return false; // no such image
if (it->tags.contains(tagName))
return false; // no overwrite
it->tags.insert(tagName);
return true;
}
// clear
void dropCache() {
gs_cache.clear();
}
QTransform transformation(const QString &imageFullPath) {
QTransform trans;
switch (orientation(imageFullPath)) {
case 1:
break;
case 2:
trans.scale(-1, 1);
// image = image.transformed(trans, Qt::SmoothTransformation);
/// image = image.mirrored(true, false);
break;
case 3:
trans.rotate(180);
// image = image.transformed(trans, Qt::SmoothTransformation);
break;
case 4:
trans.scale(1, -1);
// image.mirror(false, true);
break;
case 5:
trans.scale(-1, 1);
trans.rotate(90);
// image = image.transformed(trans, Qt::SmoothTransformation);
/// image.mirror(true, false);
break;
case 6:
trans.rotate(90);
// image = image.transformed(trans, Qt::SmoothTransformation);
break;
case 7:
trans.scale(1, -1);
trans.rotate(90);
// image = image.transformed(trans, Qt::SmoothTransformation);
/// image.mirror(false, true);
break;
case 8:
trans.rotate(270);
// image = image.transformed(trans, Qt::SmoothTransformation);
/// image.mirror(true, false);
break;
default:
break;
}
return trans;
}
// loadImageMetadata
void cache(const QString &imageFullPath) {
if (gs_cache.contains(imageFullPath))
return;
Exiv2ImagePtr exifImage;
ImageMetadata imageMetadata;
imageMetadata.orientation = 0;
imageMetadata.date = 0;
try {
exifImage = Exiv2::ImageFactory::open(imageFullPath.toStdString());
exifImage->readMetadata();
} catch (Exiv2::Error &error) {
qWarning() << "Error loading image for reading metadata" << error.what();
gs_cache.insert(imageFullPath, imageMetadata);
return;
}
if (!exifImage->good()) {
gs_cache.insert(imageFullPath, imageMetadata);
return;
}
if (exifImage->supportsMetadata(Exiv2::mdExif)) try {
Exiv2::ExifData::const_iterator it = Exiv2::orientation(exifImage->exifData());
if (it != exifImage->exifData().end()) {
#if EXIV2_TEST_VERSION(0,28,0)
imageMetadata.orientation = it->toUint32();
#else
imageMetadata.orientation = it->toLong();
#endif
}
Exiv2::ExifData &exifData = exifImage->exifData();
Exiv2::ExifData::const_iterator end = exifData.end();
for (Exiv2::ExifData::const_iterator md = exifData.begin(); md != end; ++md) {
if (!strncmp(md->tagName().c_str(), "DateTime", 8)) {
imageMetadata.date = QDateTime::fromString(QLatin1String(md->print().c_str()),
QLatin1String("yyyy:MM:dd hh:mm:ss")).toSecsSinceEpoch(); // "2009:06:28 17:06:56"
break;
}
}
} catch (Exiv2::Error &error) {
qWarning() << "Failed to read Exif metadata" << error.what();
}
if (exifImage->supportsMetadata(Exiv2::mdIptc)) try {
Exiv2::IptcData &iptcData = exifImage->iptcData();
if (!iptcData.empty()) {
QString key;
Exiv2::IptcData::iterator end = iptcData.end();
// Finds the first ID, but we need to loop over the rest in case there are more
Exiv2::IptcData::iterator iptcIt = iptcData.findId(Exiv2::IptcDataSets::Keywords);
for (; iptcIt != end; ++iptcIt) {
if (iptcIt->tag() != Exiv2::IptcDataSets::Keywords) {
continue;
}
QString tagName = QString::fromUtf8(iptcIt->toString().c_str());
imageMetadata.tags.insert(tagName);
// Settings::knownTags.insert(tagName);
}
}
} catch (Exiv2::Error &error) {
qWarning() << "Failed to read Iptc metadata";
}
gs_cache.insert(imageFullPath, imageMetadata);
}
void data(const QString &imageFullPath, Metadata::DataTriple *EXIF, Metadata::DataTriple *IPTC, Metadata::DataTriple *XMP) {
Exiv2ImagePtr exifImage;
try {
exifImage = Exiv2::ImageFactory::open(imageFullPath.toStdString());
exifImage->readMetadata();
}
catch (const Exiv2::Error &error) {
qWarning() << "EXIV2:" << error.what();
return;
}
//#define EXIV2_ENTRY QString::fromUtf8(md->tagName().c_str()), QString::fromUtf8(md->print().c_str())
#define INSERT(_MAP_) const QString p = QString::fromUtf8(md->print().c_str()), r = QString::fromUtf8(md->toString().c_str()); \
_MAP_->insert(QString::fromUtf8(md->tagName().c_str()), QPair(p, p == r ? p : r))
if (EXIF) {
Exiv2::ExifData &exifData = exifImage->exifData();
if (!exifData.empty()) {
Exiv2::ExifData::const_iterator end = exifData.end();
for (Exiv2::ExifData::const_iterator md = exifData.begin(); md != end; ++md) {
INSERT(EXIF);
}
}
}
if (IPTC) {
Exiv2::IptcData &iptcData = exifImage->iptcData();
if (!iptcData.empty()) {
Exiv2::IptcData::iterator end = iptcData.end();
for (Exiv2::IptcData::iterator md = iptcData.begin(); md != end; ++md) {
INSERT(IPTC);
}
}
}
if (XMP) {
Exiv2::XmpData &xmpData = exifImage->xmpData();
if (!xmpData.empty()) {
Exiv2::XmpData::iterator end = xmpData.end();
for (Exiv2::XmpData::iterator md = xmpData.begin(); md != end; ++md) {
INSERT(XMP);
}
}
}
}
bool gpsData(const QString &imageFullPath, double &lat, double &lon, double &alt) {
lat = lon = alt = 0.0;
Exiv2ImagePtr exifImage;
try {
exifImage = Exiv2::ImageFactory::open(imageFullPath.toStdString());
exifImage->readMetadata();
}
catch (const Exiv2::Error &error) {
qWarning() << "EXIV2:" << error.what();
return false;
}
Exiv2::ExifData &exifData = exifImage->exifData();
if (exifData.empty())
return false;
auto rat2dec = [=](const QString s) {
QStringList t = s.split("/", Qt::SkipEmptyParts);
if (t.size() != 2)
return 0.0; // wtf
const double c = t.at(0).toDouble();
const double d = t.at(1).toDouble();
if (d != 0.0)
return c/d;
return 0.0; // nan
};
auto ratarc2dec = [=](const QString s) {
QStringList t = s.split(" ", Qt::SkipEmptyParts);
double val = 0.0;
if (t.size() > 0)
val = rat2dec(t.at(0));
if (t.size() > 1)
val += rat2dec(t.at(1))/60.0;
if (t.size() > 2)
val += rat2dec(t.at(2))/3600.0;
return val;
};
bool south(false), west(false), nautilus(false);
int flags = (1|2|4|8|16|32);
Exiv2::ExifData::const_iterator end = exifData.end();
for (Exiv2::ExifData::const_iterator md = exifData.begin(); md != end; ++md) {
const QString key = QString::fromUtf8(md->tagName().c_str());
if (key == "GPSLatitude") {
flags &= ~1;
lat = ratarc2dec(QString::fromUtf8(md->toString().c_str()));
} else if (key == "GPSLatitudeRef") {
flags &= ~2;
south = QString::fromUtf8(md->toString().c_str()).toLower() == "s";
} else if (key == "GPSLongitude") {
flags &= ~4;
lon = ratarc2dec(QString::fromUtf8(md->toString().c_str()));
} else if (key == "GPSLongitudeRef") {
flags &= ~8;
west = QString::fromUtf8(md->toString().c_str()).toLower() == "w";
} else if (key == "GPSAltitude") {
flags &= ~16;
alt = QString::fromUtf8(md->toString().c_str()).toDouble();
} else if (key == "GPSAltitudeRef") {
flags &= ~32;
nautilus = QString::fromUtf8(md->toString().c_str()) == "1";
}
if (!flags)
break;
}
if (south)
lat = -lat;
if (west)
lon = -lon;
if (nautilus)
alt = -alt;
return flags != (1|2|4|8|16|32);
}
template static void writeBack(Ev2D &data, Metadata::DataPair newData) {
if (data.empty())
return;
if (newData.isEmpty()) {
data.clear();
return;
}
DataPair phase2;
typename Ev2D::iterator md = data.begin();
while (md != data.end()) {
const QString tagName = QString::fromUtf8(md->tagName().c_str());
const QString value = QString::fromUtf8(md->print().c_str());
DataPair::const_iterator cit = newData.constFind(tagName, value);
if (cit != newData.constEnd()) {
newData.erase(cit); // the tag exists in its current form, keep
++md;
} else if (newData.constFind(tagName) == newData.constEnd()) {
md = data.erase(md); // there's no such tag left, delete
} else {
phase2.insert(tagName, value); // edit in second pass
++md;
}
}
if (phase2.isEmpty())
return;
md = data.begin();
while (md != data.end()) {
const QString tagName = QString::fromUtf8(md->tagName().c_str());
const QString value = QString::fromUtf8(md->print().c_str());
DataPair::const_iterator cit = phase2.constFind(tagName, value);
if (cit == phase2.constEnd()) {
++md; continue; // not a concern anyway
}
phase2.erase(cit); // we're gonna handle this pair now:
cit = newData.constFind(tagName); // do we still have such tag (w/ different value)
if (cit == newData.constEnd()) {
md = data.erase(md); // ultimately stale
} else {
if (value == *cit) // this is not supposed to happen
qWarning() << "errr… WHAT?!";
if (md->setValue(cit->toStdString()))
qWarning() << "could not set" << cit.key() << "from" << md->toString() << " to " << *cit;
newData.erase(cit); // we've stored this pair now - or ultimately failed because of invalid form…
++md;
}
if (phase2.isEmpty())
return;
}
}
bool setData(const QString &imageFullPath, Metadata::DataPair EXIF, Metadata::DataPair IPTC, Metadata::DataPair XMP) {
Exiv2ImagePtr exifImage;
try {
exifImage = Exiv2::ImageFactory::open(imageFullPath.toStdString());
exifImage->readMetadata();
writeBack(exifImage->exifData(), EXIF);
writeBack(exifImage->iptcData(), IPTC);
writeBack(exifImage->xmpData(), XMP);
exifImage->writeMetadata();
Metadata::forget(imageFullPath);
cache(imageFullPath);
}
catch (Exiv2::Error &error) {
qWarning() << "Failed to write metadata" << error.what();
return false;
}
return true;
}
bool wipeFrom(const QString &imageFileName) {
Exiv2ImagePtr image;
try {
image = Exiv2::ImageFactory::open(imageFileName.toStdString());
image->clearMetadata();
image->writeMetadata();
Metadata::forget(imageFileName);
}
catch (Exiv2::Error &error) {
return false;
}
return true;
}
bool write(const QString &imageFileName) {
const QSet &newTags = tags(imageFileName);
Exiv2ImagePtr exifImage;
try {
exifImage = Exiv2::ImageFactory::open(imageFileName.toStdString());
exifImage->readMetadata();
Exiv2::IptcData newIptcData;
/* copy existing data */
Exiv2::IptcData &iptcData = exifImage->iptcData();
if (!iptcData.empty()) {
QString key;
Exiv2::IptcData::iterator end = iptcData.end();
for (Exiv2::IptcData::iterator iptcIt = iptcData.begin(); iptcIt != end; ++iptcIt) {
if (iptcIt->tagName() != "Keywords") {
newIptcData.add(*iptcIt);
}
}
}
/* add new tags */
QSetIterator newTagsIt(newTags);
while (newTagsIt.hasNext()) {
QString tag = newTagsIt.next();
Exiv2ValuePtr value = Exiv2::Value::create(Exiv2::string);
value->read(tag.toStdString());
Exiv2::IptcKey key("Iptc.Application2.Keywords");
newIptcData.add(key, value.get());
}
exifImage->setIptcData(newIptcData);
exifImage->writeMetadata();
}
catch (Exiv2::Error &error) {
return false;
}
return true;
}
} // namespace Metadata phototonic-3.3.0/MetadataCache.h 0000664 0000000 0000000 00000004657 15271130355 0016536 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2015 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef META_DATA_CACHE_H
#define META_DATA_CACHE_H
#include
#include
#include
namespace Metadata {
typedef QMultiMap> DataTriple;
typedef QMultiMap DataPair;
bool addTag(const QString &imageFileName, const QString &tagName);
bool buffer(const QString &imageFileName);
void cache(const QString &imageFullPath);
bool copy(const QString &from, const QString &to, QImage thumbnail = QImage());
void data(const QString &imageFullPath, DataTriple *EXIF = nullptr, DataTriple *IPTC = nullptr, DataTriple *XMP = nullptr);
bool setData(const QString &imageFullPath, DataPair EXIF, DataPair IPTC, DataPair XMP);
void dropCache();
bool gpsData(const QString &imageFullPath, double &lat, double &lon, double &alt);
QTransform transformation(const QString &imageFullPath);
void forget(const QString &imageFileName);
void rename(const QString &oldImageFileName, const QString &newImageFileName);
long orientation(const QString &imageFileName);
qint64 dateTimeOriginal(const QString &imageFileName);
bool removeTag(const QString &imageFileName, const QString &tagName);
void setTags(const QString &imageFileName, QSet tags);
bool setThumbnail(const QString &imageFullPath, QImage thumbnail);
const QSet &tags(const QString &imageFileName);
QImage thumbnail(const QString &imageFullPath);
bool updateTags(const QString &imageFileName, QSet tags);
bool wipeFrom(const QString &imageFileName);
bool write(const QString &imageFileName);
bool writeBuffer(QImage thumbnail = QImage());
};
#endif // META_DATA_CACHE_H
phototonic-3.3.0/Phototonic.cpp 0000664 0000000 0000000 00000473360 15271130355 0016554 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2015 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Bookmarks.h"
#include "CopyMoveDialog.h"
#include "CopyMoveToDialog.h"
#include "ColorsDialog.h"
#include "DirCompleter.h"
#include "ExternalAppsDialog.h"
#include "FileSystemTree.h"
#include "GuideWidget.h"
#include "IconProvider.h"
#include "ImageViewer.h"
#include "InfoViewer.h"
#include "MessageBox.h"
#include "MetadataCache.h"
#include "Phototonic.h"
#include "RenameDialog.h"
#include "ResizeDialog.h"
#include "Settings.h"
#include "SettingsDialog.h"
#include "Tags.h"
#include "ThumbsViewer.h"
#if __cplusplus >= 202002L
#define _LCD_ =,this
#else
#define _LCD_ =
#endif
static QString localFile(const QString &fileOrUrl) {
QUrl url(fileOrUrl);
if (url.scheme().isEmpty())
return fileOrUrl;
return url.toLocalFile();
}
Phototonic::Phototonic(QStringList argumentsList, int filesStartAt, QString filter, QWidget *parent) : QMainWindow(parent) {
imageViewer = nullptr;
m_presentationMode = false;
Settings::appSettings = new QSettings("phototonic", "phototonic");
fileSystemModel = new QFileSystemModel(this);
fileSystemModel->setFilter(QDir::AllDirs | QDir::Dirs | QDir::NoDotAndDotDot);
fileSystemModel->setOptions(QFileSystemModel::DontWatchForChanges);
fileSystemModel->setIconProvider(new IconProvider);
setDockOptions(QMainWindow::AllowNestedDocks);
readSettings();
createThumbsViewer();
if (!filter.isEmpty()) {
if (argumentsList.size()) {
QFileInfo firstArgument(localFile(argumentsList.at(filesStartAt)));
if (firstArgument.isDir()) {
// Confusingly we need the absoluteFile and not absolutePath if it's a directory
Settings::currentDirectory = firstArgument.absoluteFilePath();
}
}
if (Settings::currentDirectory.isEmpty())
Settings::currentDirectory = QDir::currentPath();
thumbsViewer->disconnect();
thumbsViewer->selectionModel()->disconnect();
thumbsViewer->reload();
if (thumbsViewer->setFilter(filter)) {
thumbsViewer->filterRows();
for (int i = 0; i < thumbsViewer->model()->rowCount(); ++i) {
if (!thumbsViewer->isRowHidden(i))
printf("%s\n", qPrintable(thumbsViewer->fullPathOf(i)));
}
} else {
qWarning() << "Inalid filter:" << filter;
}
close();
QMetaObject::invokeMethod(qApp, "exit", Qt::QueuedConnection);
return;
}
createActions();
myMainMenu = new QMenu(this);
statusBar()->setVisible(false);
createFileSystemDock();
createBookmarksDock();
createImagePreviewDock();
createThumbviewDock();
createImageTagsDock();
setupDocks();
myMainToolBar = nullptr; // accessed but undesired by …
createMenus(); // createPopupMenu …
createToolBars(); // and created only here
createImageViewer();
m_imageToolBar->setParent(imageViewer);
m_imageToolBar->setVisible(Settings::showViewerToolbar);
positionImageToolbar();
updateExternalApps();
loadShortcuts();
m_statusLabel = new QLabel(this);
m_statusLabel->hide();
m_statusLabel->setMargin(3);
m_statusLabel->setAutoFillBackground(true);
m_statusLabel->setFrameStyle(QFrame::Plain|QFrame::NoFrame);
QPalette pal = m_statusLabel->palette();
pal.setColor(m_statusLabel->backgroundRole(), QColor(0,0,0,192));
pal.setColor(m_statusLabel->foregroundRole(), QColor(255,255,255,192));
connect (thumbsViewer, &ThumbsViewer::currentIndexChanged, this, [this](const QModelIndex ¤t) {
if (!current.isValid())
return;
if (m_infoViewer->isVisible()) {
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
if (QStandardItem *citem = thumbModel->item(current.row()))
m_infoViewer->hint(tr("Average brightness"), QString::number(citem->data(ThumbsViewer::BrightnessRole).toInt()/255.0f, 'f', 2));
const QString filePath = thumbsViewer->fullPathOf(current.row());
m_infoViewer->read(filePath, thumbsViewer->renderHistogram(filePath, m_logHistogram));
}
if (imageViewer->isVisible()) {
const QString &imagePath = thumbsViewer->fullPathOf(current.row());
if (m_imageInfoAction->isChecked()) {
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
if (!m_infoViewer->isVisible()) {
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
if (QStandardItem *citem = thumbModel->item(current.row()))
m_infoViewer->hint(tr("Average brightness"), QString::number(citem->data(ThumbsViewer::BrightnessRole).toInt()/255.0f, 'f', 2));
m_infoViewer->read(imagePath);
}
imageViewer->setFeedback(m_infoViewer->html(), false);
}
if (!thumbsViewer->isVisible())
setImageViewerWindowTitle();
imageViewer->loadImage(imagePath, m_slideShowActive ? QImage() : thumbsViewer->icon(current.row()).pixmap(THUMB_SIZE_MAX).toImage());
}
}, Qt::QueuedConnection);
connect(qApp, SIGNAL(focusChanged(QWidget * , QWidget * )), this, SLOT(updateActions()));
QApplication::setWindowIcon(QIcon(":/images/phototonic.png"));
m_centralLayout = new QStackedLayout;
QWidget *stackedLayoutWidget = new QWidget;
m_centralLayout->addWidget(thumbsViewer);
m_centralLayout->addWidget(imageViewer);
stackedLayoutWidget->setLayout(m_centralLayout);
setCentralWidget(stackedLayoutWidget);
restoreGeometry(Settings::value(Settings::optionGeometry, QByteArray()).toByteArray());
restoreState(Settings::value(Settings::optionWindowState, QByteArray()).toByteArray());
processStartupArguments(argumentsList, filesStartAt);
if (Settings::currentDirectory.isEmpty())
Settings::currentDirectory = QDir::currentPath();
m_thumbSizeDelta = 0;
colorsDialog = nullptr;
initComplete = true;
m_deleteInProgress = false;
currentHistoryIdx = -1;
needHistoryRecord = true;
m_reloadPending = false;
m_slideShowActive = false;
refreshThumbs(true);
if (m_centralLayout->currentWidget() == thumbsViewer) {
thumbsViewer->setFocus(Qt::OtherFocusReason);
}
action(QString()); // clear hash
}
void Phototonic::processStartupArguments(QStringList argumentsList, int filesStartAt) {
if (Settings::startupDir == Settings::SpecifiedDir) {
Settings::currentDirectory = Settings::specifiedStartDir;
} else if (Settings::startupDir == Settings::RememberLastDir) {
Settings::currentDirectory = Settings::value(Settings::optionLastDir, QString()).toString();
}
QFile *input = nullptr;
if (filesStartAt < argumentsList.size() && argumentsList.at(filesStartAt) == "-") { // stdin ?
#ifdef Q_OS_WIN
if (!_isatty(_fileno(stdin))) {
#else
if (!isatty(fileno(stdin))) {
#endif
input = new QFile;
QByteArray ba;
if (input->open(stdin, QFile::ReadOnly))
ba = input->readLine();
if (ba.isEmpty()) { // catches /dev/null or <&-
input->close();
delete input;
input = nullptr;
} else { // load first file into list
QString line = QString::fromLocal8Bit(ba.trimmed());
if (!line.isEmpty())
loadStartupFileList(QStringList() << line, 0);
}
}
if (!input)
argumentsList.remove(filesStartAt);
}
if (input) {
QSocketNotifier *snr = new QSocketNotifier(input->handle(), QSocketNotifier::Read, input);
static QStringList newFiles;
static QTimer *bouncer;
if (!bouncer) {
bouncer = new QTimer(this);
bouncer->setInterval(30);
bouncer->setSingleShot(true);
connect(bouncer, &QTimer::timeout, [_LCD_]() {
loadStartupFileList(newFiles, 0);
newFiles.clear();
thumbsViewer->reload(true);
});
if (!Settings::filesList.isEmpty())
bouncer->start(); // for the first file
}
connect (snr, &QSocketNotifier::activated, [_LCD_](){
QByteArray ba = input->readLine();
if (ba.isEmpty()) { // effectively EOF
snr->setEnabled(false);
input->close();
delete input;
// snr->deleteLater(); // segfault
return;
}
QString line = QString::fromLocal8Bit(ba.trimmed());
if (!line.isEmpty()) {
newFiles << line;
if (newFiles.size() < 25) // if we got some batch, let the timer run out to load it
bouncer->start();
}
});
} else if (filesStartAt < argumentsList.size()) {
QFileInfo firstArgument(localFile(argumentsList.at(filesStartAt)));
if (firstArgument.isDir()) {
// Confusingly we need the absoluteFile and not absolutePath if it's a directory
Settings::currentDirectory = firstArgument.absoluteFilePath();
} else if (argumentsList.size() > filesStartAt + 1) {
loadStartupFileList(argumentsList, filesStartAt);
return;
} else {
Settings::currentDirectory = firstArgument.absolutePath();
const QString cliFileName = Settings::currentDirectory + QDir::separator() + firstArgument.fileName();
if (QFile::exists(cliFileName)) {
showViewer();
imageViewer->loadImage(cliFileName);
thumbsViewer->setCurrentIndex(cliFileName);
setWindowTitle(cliFileName + " - Phototonic");
} else {
MessageBox(this).critical(tr("Error"), tr("Failed to open file %1, file not found.").arg(cliFileName));
}
}
}
selectCurrentViewDir();
}
// for singleton update
void Phototonic::setCurrentFileOrDirectory(const QString &path) {
activateWindow();
QFileInfo info(localFile(path));
if (info.isDir()) {
if (Settings::currentDirectory != info.absoluteFilePath())
goTo(info.absoluteFilePath());
} else if (info.exists()) {
showViewer();
imageViewer->loadImage(info.absoluteFilePath());
setWindowTitle(info.absoluteFilePath() + " - Phototonic");
if (Settings::currentDirectory != info.absolutePath())
goTo(info.absolutePath());
thumbsViewer->setCurrentIndex(info.absoluteFilePath());
thumbsViewer->scrollTo(thumbsViewer->currentIndex());
}
}
void Phototonic::loadStartupFileList(QStringList argumentsList, int filesStartAt) {
const int oldSize = Settings::filesList.size();
for (int i = filesStartAt; i < argumentsList.size(); i++) {
QFileInfo file(localFile(argumentsList[i]));
if (!file.exists() || file.isDir())
continue;
QString path = file.canonicalFilePath();
if (path.isEmpty())
path = file.absoluteFilePath();
if (!Settings::filesList.contains(path)) {
Settings::filesList << path;
}
}
if (oldSize == Settings::filesList.size())
return; // stale
if (!oldSize) { // only on first update, don't undo user interactions
QToolButton *btn = static_cast(myMainToolBar->widgetForAction(m_goHomeAction));
QMenu *btnmenu = new QMenu(btn);
QAction *act = btnmenu->addAction(tr("Home"));
connect(act, &QAction::triggered, [this]() { goTo(QDir::homePath()); });
//: The file list is the optional list of files in the execution parameters, some virtual directory
act = btnmenu->addAction(tr("File List"));
connect(act, &QAction::triggered, [this]() { goTo("Phototonic::FileList"); });
btn->setMenu(btnmenu);
setFileListMode(true);
}
}
void Phototonic::setFileListMode(bool on) {
Settings::isFileListLoaded = on;
if (on) {
m_includeSubDirsAction->setChecked(false);
fileSystemTree->clearSelection();
}
m_includeSubDirsAction->setEnabled(!on);
}
void Phototonic::createThumbsViewer() {
thumbsViewer = new ThumbsViewer(this);
thumbsViewer->installEventFilter(this);
thumbsViewer->viewport()->installEventFilter(this);
thumbsViewer->thumbsSortFlags = (QDir::SortFlags) Settings::value(Settings::optionThumbsSortFlags, 0).toInt();
connect(thumbsViewer->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(updateActions()));
connect (thumbsViewer, &ThumbsViewer::status, this, &Phototonic::setStatus);
connect (thumbsViewer, &ThumbsViewer::progress, [this](unsigned int v, unsigned int t) {
m_progressBar->setMaximum(t);
m_progressBar->setValue(v);
});
connect (thumbsViewer, &ThumbsViewer::doubleClicked, this, &Phototonic::loadSelectedThumbImage);
imageInfoDock = new QDockWidget(tr("Image Info"), this);
imageInfoDock->setObjectName("Image Info");
m_infoViewer = new InfoView(this);
imageInfoDock->setWidget(m_infoViewer);
m_logHistogram = false;
connect(imageInfoDock, &QDockWidget::visibilityChanged, [this](bool visible) {
if (!m_presentationMode) {
Settings::imageInfoDockVisible = visible;
}
if (visible) {
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
int currentRow = thumbsViewer->currentIndex().row();
if (currentRow > -1) {
m_infoViewer->hint(tr("Average brightness"),
QString::number(thumbModel->item(currentRow)->data(ThumbsViewer::BrightnessRole).toInt()/255.0f, 'f', 2));
const QString filePath = thumbsViewer->fullPathOf(currentRow);
m_infoViewer->read(filePath, thumbsViewer->renderHistogram(filePath, m_logHistogram));
}
}
} );
connect(m_infoViewer, &InfoView::histogramClicked, [this](){
m_logHistogram = !m_logHistogram;
int currentRow = thumbsViewer->currentIndex().row();
if (currentRow > -1) {
const QString filePath = thumbsViewer->fullPathOf(currentRow);
m_infoViewer->read(filePath, thumbsViewer->renderHistogram(filePath, m_logHistogram));
}
});
connect(m_infoViewer, &InfoView::exifChanged, [this](const QString &fileName) {
thumbsViewer->updateThumbnail(fileName);
m_imageTags->setSelectedFiles(thumbsViewer->selectedFiles());
});
}
void Phototonic::createImageViewer() {
imageViewer = new ImageViewer(this);
imageViewer->setFocusPolicy(Qt::StrongFocus);
imageViewer->installEventFilter(this);
connect(m_saveAction, SIGNAL(triggered()), imageViewer, SLOT(saveImage()));
connect(m_saveAsAction, SIGNAL(triggered()), imageViewer, SLOT(saveImageAs()));
connect(action("copyImage"), SIGNAL(triggered()), imageViewer, SLOT(copyImage()));
connect(action("pasteImage"), SIGNAL(triggered()), imageViewer, SLOT(pasteImage()));
QAction *rotateMouse = action("rotateMouse");
connect(imageViewer, &ImageViewer::toolsUpdated, [_LCD_](){ rotateMouse->setChecked(Settings::mouseRotateEnabled); });
connect(imageViewer, &ImageViewer::gotFocus, [this](){
if (thumbsViewer->selectionModel()->selectedIndexes().size() < 1)
thumbsViewer->setCurrentIndex(imageViewer->fullImagePath);
});
connect(imageViewer, &ImageViewer::imageSaved, thumbsViewer, &ThumbsViewer::updateThumbnail);
m_editSteps = 0;
connect(imageViewer, &ImageViewer::imageEdited, [this](bool yes) {
m_editSteps = yes ? m_editSteps+1 : 0;
m_saveAction->setEnabled(m_editSteps);
m_saveAsAction->setEnabled(m_editSteps);
});
QMenu *contextMenu = new QMenu(imageViewer);
// Widget actions
imageViewer->addAction(action("toggleSlideShow"));
imageViewer->addAction(action("nextImage"));
imageViewer->addAction(action("prevImage"));
imageViewer->addAction(action("firstImage"));
imageViewer->addAction(action("lastImage"));
imageViewer->addAction(action("randomImage"));
imageViewer->addAction(action("zoomIn"));
imageViewer->addAction(action("zoomOut"));
imageViewer->addAction(action("origZoom"));
imageViewer->addAction(action("resetZoom"));
imageViewer->addAction(action("rotateLeft"));
imageViewer->addAction(action("rotateRight"));
imageViewer->addAction(action("freeRotateLeft"));
imageViewer->addAction(action("freeRotateRight"));
imageViewer->addAction(action("flipH"));
imageViewer->addAction(action("flipV"));
imageViewer->addAction(action("letterbox"));
imageViewer->addAction(action("resize"));
imageViewer->addAction(action("save"));
imageViewer->addAction(action("saveAs"));
imageViewer->addAction(action("copyImage"));
imageViewer->addAction(action("pasteImage"));
imageViewer->addAction(action("moveToTrash"));
imageViewer->addAction(action("delete"));
imageViewer->addAction(action("rename"));
imageViewer->addAction(action("closeImage"));
imageViewer->addAction(action("fullScreen"));
imageViewer->addAction(action("settings"));
imageViewer->addAction(action("keepTransform"));
imageViewer->addAction(action("keepZoom"));
imageViewer->addAction(action("refresh"));
imageViewer->addAction(action("colors"));
imageViewer->addAction(action("moveLeft"));
imageViewer->addAction(action("moveRight"));
imageViewer->addAction(action("moveUp"));
imageViewer->addAction(action("moveDown"));
imageViewer->addAction(action("showClipboard"));
imageViewer->addAction(action("copyTo"));
imageViewer->addAction(action("moveTo"));
imageViewer->addAction(action("open"));
imageViewer->addAction(action("exit"));
imageViewer->addAction(action("showViewerToolbar"));
imageViewer->addAction(action("chooseApp"));
imageViewer->addAction(action("imageinfo"));
imageViewer->addAction(action("showgrid"));
// Actions
contextMenu->addAction(action("setwallpaper"));
contextMenu->addAction(action("openWithMenu"));
contextMenu->addAction(action("imageinfo"));
contextMenu->addSeparator();
contextMenu->addAction(action("showgrid"));
contextMenu->addAction(action("showViewerToolbar"));
QMenu *menu = contextMenu->addMenu(tr("Navigate"));
menu->addAction(action("nextImage"));
menu->addAction(action("prevImage"));
menu->addAction(action("firstImage"));
menu->addAction(action("lastImage"));
menu->addAction(action("randomImage"));
menu->addAction(action("toggleSlideShow"));
menu = contextMenu->addMenu(tr("Transform"));
QMenu *submenu = menu->addMenu(QIcon::fromTheme("zoom-fit-best", QIcon(":/images/zoom-fit-best.png")), tr("Zoom"));
submenu->addAction(action("zoomIn"));
submenu->addAction(action("zoomOut"));
submenu->addAction(action("origZoom"));
submenu->addAction(action("resetZoom"));
submenu->addAction(action("keepZoom"));
submenu = menu->addMenu(tr("Flip and Flop and Rotate"));
submenu->addAction(action("flipH"));
submenu->addAction(action("flipV"));
submenu->addSeparator();
submenu->addAction(action("rotateLeft"));
submenu->addAction(action("rotateRight"));
submenu->addAction(action("freeRotateLeft"));
submenu->addAction(action("freeRotateRight"));
submenu->addSeparator();
submenu->addAction(action("keepTransform"));
menu = contextMenu->addMenu(tr("Edit"));
menu->setObjectName("image_edit_menu");
menu->addAction(action("resize"));
menu->addAction(action("colors"));
menu->addAction(action("crop"));
menu->addSeparator();
menu->addAction(action("blackout"));
menu->addAction(action("cartouche"));
menu->addAction(action("annotate"));
menu = contextMenu->addMenu(tr("File"));
menu->addAction(action("copyTo"));
menu->addAction(action("moveTo"));
menu->addAction(action("save"));
menu->addAction(action("saveAs"));
menu->addAction(action("rename"));
menu->addSeparator();
menu->addAction(action("removeMetadata"));
menu->addAction(action("moveToTrash"));
menu->addAction(action("delete"));
menu = contextMenu->addMenu(tr("View"));
menu->addAction(action("fullScreen"));
menu->addSeparator();
menu->addAction(action("letterbox"));
//: The guides a lines across the image for orientation
submenu = menu->addMenu(tr("Guides"));
QAction *act = new QAction(tr("Add vertical guide"), submenu);
connect(act, &QAction::triggered, [this]() { new GuideWidget(imageViewer, Qt::Vertical, imageViewer->contextSpot().x()); });
submenu->addAction(act);
act = new QAction(tr("Add horizontal guide"), submenu);
connect(act, &QAction::triggered, [this]() { new GuideWidget(imageViewer, Qt::Horizontal, imageViewer->contextSpot().y()); });
submenu->addAction(act);
menu->addSeparator();
menu->addAction(action("showClipboard"));
menu->addSeparator();
menu->addAction(action("refresh"));
contextMenu->addSeparator();
contextMenu->addAction(action("copyImage"));
contextMenu->addAction(action("pasteImage"));
contextMenu->addSeparator();
contextMenu->addAction(action("closeImage"));
imageViewer->setContextMenuPolicy(Qt::DefaultContextMenu);
imageViewer->setContextMenu(contextMenu);
Settings::isFullScreen = Settings::value(Settings::optionFullScreenMode, false).toBool();
m_fullScreenAction->setChecked(Settings::isFullScreen);
}
void Phototonic::createActions() {
#define MAKE_ACTION_NOSC(_TEXT_, _NAME_) \
action = new QAction(_TEXT_, this); action->setObjectName(_NAME_)
#define MAKE_ACTION(_TEXT_, _NAME_, _SHORTCUT_) \
MAKE_ACTION_NOSC(_TEXT_, _NAME_); action->setProperty("sc_default", _SHORTCUT_)
#define SET_ICON(_ICON_) action->setProperty("icon_name", #_ICON_)
QAction *action;
MAKE_ACTION(tr("Top"), "thumbsGoTop", "Ctrl+Home");
SET_ICON(go-top);
connect(action, &QAction::triggered, thumbsViewer, &ThumbsViewer::scrollToTop);
MAKE_ACTION(tr("Bottom"), "thumbsGoBottom", "Ctrl+End");
SET_ICON(go-bottom);
connect(action, &QAction::triggered, thumbsViewer, &ThumbsViewer::scrollToBottom);
m_closeImageAction = MAKE_ACTION(tr("Close Viewer"), "closeImage", "Esc");
connect(action, SIGNAL(triggered()), this, SLOT(hideViewer()));
m_fullScreenAction = MAKE_ACTION(tr("Full Screen"), "fullScreen", "Alt+Return");
action->setCheckable(true);
connect(action, SIGNAL(triggered()), this, SLOT(toggleFullScreen()));
MAKE_ACTION(tr("Preferences"), "settings", "Ctrl+P");
SET_ICON(preferences-system);
connect(action, SIGNAL(triggered()), this, SLOT(showSettings()));
MAKE_ACTION(tr("Exit"), "exit", "Ctrl+Q");
connect(action, SIGNAL(triggered()), this, SLOT(close()));
MAKE_ACTION_NOSC(tr("Enlarge Thumbnails"), "thumbsZoomIn");
connect(action, &QAction::triggered, [this]() {m_thumbSizeDelta = 1; resizeThumbs();});
SET_ICON(zoom-in);
if (thumbsViewer->thumbSize == THUMB_SIZE_MAX) {
action->setEnabled(false);
}
MAKE_ACTION_NOSC(tr("Shrink Thumbnails"), "thumbsZoomOut");
connect(action, &QAction::triggered, [this]() {m_thumbSizeDelta = -1; resizeThumbs();});
SET_ICON(zoom-out);
if (thumbsViewer->thumbSize == THUMB_SIZE_MIN) {
action->setEnabled(false);
}
m_cutAction = MAKE_ACTION(tr("Cut"), "cut", "Ctrl+X");
SET_ICON(edit-cut);
connect(action, &QAction::triggered, [this]() { copyOrCutThumbs(false); });
action->setEnabled(false);
m_copyAction = MAKE_ACTION(tr("Copy"), "copy", "Ctrl+C");
SET_ICON(edit-copy);
connect(action, &QAction::triggered, [this]() { copyOrCutThumbs(true); });
action->setEnabled(false);
MAKE_ACTION_NOSC(tr("Show classic thumbnails"), "setClassicThumbs");
action->setCheckable(true);
action->setChecked(Settings::thumbsLayout == ThumbsViewer::Classic);
connect(action, &QAction::triggered, [this](){ Settings::thumbsLayout = ThumbsViewer::Classic; thumbsViewer->refreshThumbs(); });
MAKE_ACTION_NOSC(tr("Show square thumbnails"), "setSquareThumbs");
action->setCheckable(true);
action->setChecked(Settings::thumbsLayout == ThumbsViewer::Squares);
connect(action, &QAction::triggered, [this](){ Settings::thumbsLayout = ThumbsViewer::Squares; thumbsViewer->refreshThumbs(); });
MAKE_ACTION_NOSC(tr("Show compact thumbnails"), "setCompactThumbs");
action->setCheckable(true);
action->setChecked(Settings::thumbsLayout == ThumbsViewer::Compact);
connect(action, &QAction::triggered, [this](){ Settings::thumbsLayout = ThumbsViewer::Compact; thumbsViewer->refreshThumbs(); });
m_copyToAction = MAKE_ACTION(tr("Copy to..."), "copyTo", "Ctrl+Y");
connect(action, &QAction::triggered, [this]() { copyOrMoveImages(true); });
m_moveToAction = MAKE_ACTION(tr("Move to..."), "moveTo", "Ctrl+M");
connect(action, &QAction::triggered, [this]() { copyOrMoveImages(false); });
m_trashAction = MAKE_ACTION(tr("Move to Trash"), "moveToTrash", "Del");
action->setIcon(style()->standardIcon(QStyle::SP_TrashIcon));
connect(action, SIGNAL(triggered()), this, SLOT(deleteOperation()));
m_deleteAction = MAKE_ACTION(tr("Delete"), "delete", "Shift+Del");
SET_ICON(edit-delete);
connect(action, SIGNAL(triggered()), this, SLOT(deletePermanentlyOperation()));
m_saveAction = MAKE_ACTION(tr("Save"), "save", "Ctrl+S");
SET_ICON(document-save);
action->setEnabled(false);
m_saveAsAction = MAKE_ACTION_NOSC(tr("Save As"), "saveAs");
SET_ICON(document-save-as);
action->setEnabled(false);
MAKE_ACTION(tr("Copy Image"), "copyImage", "Ctrl+Shift+C");
MAKE_ACTION(tr("Paste Image"), "pasteImage", "Ctrl+Shift+V");
MAKE_ACTION(tr("Rename"), "rename", "F2");
connect(action, SIGNAL(triggered()), this, SLOT(rename()));
MAKE_ACTION_NOSC(tr("Remove Metadata"), "removeMetadata");
connect(action, SIGNAL(triggered()), this, SLOT(removeMetadata()));
MAKE_ACTION_NOSC(tr("Regenerate Thumbnail"), "regenerateThumbnail");
connect(action, SIGNAL(triggered()), this, SLOT(regenerateThumbnails()));
MAKE_ACTION_NOSC(tr("Select All"), "selectAll");
connect(action, SIGNAL(triggered()), this, SLOT(selectAllThumbs()));
MAKE_ACTION_NOSC(tr("About"), "about");
connect(action, &QAction::triggered, [this](){MessageBox(this).about();});
// Sort actions
#define CHECKABLE_SORT action->setCheckable(true); connect(action, SIGNAL(triggered()), this, SLOT(sortThumbnails()));
QAction *sortByName, *sortByTime, *sortBySize, *sortByType, *sortByDuplicate;
sortByName = MAKE_ACTION_NOSC(tr("Sort by Name"), "sortByName");
CHECKABLE_SORT
sortByDuplicate = MAKE_ACTION_NOSC(tr("Sort by Duplicate Group"), "sortByDuplicate");
CHECKABLE_SORT
sortByTime = MAKE_ACTION_NOSC(tr("Sort by Time"), "sortByTime");
CHECKABLE_SORT
MAKE_ACTION_NOSC(tr("Sort by Time") + " (Exif)", "sortByExifTime");
CHECKABLE_SORT
sortBySize = MAKE_ACTION_NOSC(tr("Sort by Size"), "sortBySize");
CHECKABLE_SORT
sortByType = MAKE_ACTION_NOSC(tr("Sort by Type"), "sortByType");
CHECKABLE_SORT
MAKE_ACTION_NOSC(tr("Sort by Similarity"), "sortBySimilarity");
CHECKABLE_SORT
MAKE_ACTION_NOSC(tr("Sort by Brightness"), "sortByBrightness");
CHECKABLE_SORT
MAKE_ACTION_NOSC(tr("Sort by Color"), "sortByColor");
CHECKABLE_SORT
if (thumbsViewer->thumbsSortFlags & QDir::Time)
sortByTime->setChecked(true);
else if (thumbsViewer->thumbsSortFlags & QDir::Size)
sortBySize->setChecked(true);
else if (thumbsViewer->thumbsSortFlags & QDir::Type)
sortByType->setChecked(true);
else
sortByName->setChecked(true);
sortByDuplicate->setVisible(false);
MAKE_ACTION_NOSC(tr("Reverse Sort Order"), "sortReverse");
CHECKABLE_SORT
action->setChecked(thumbsViewer->thumbsSortFlags & QDir::Reversed);
MAKE_ACTION(tr("Show Hidden Files"), "showHidden", "Ctrl+H");
action->setCheckable(true);
action->setChecked(Settings::showHiddenFiles);
connect(action, SIGNAL(triggered()), this, SLOT(showHiddenFiles()));
MAKE_ACTION_NOSC(tr("Small Toolbar Icons"), "smallToolbarIcons");
action->setCheckable(true);
action->setChecked(Settings::smallToolbarIcons);
connect(action, SIGNAL(triggered()), this, SLOT(setToolbarIconSize()));
MAKE_ACTION_NOSC(tr("Hide Dock Title Bars"), "lockDocks");
action->setCheckable(true);
action->setChecked(Settings::hideDockTitlebars);
connect(action, SIGNAL(triggered()), this, SLOT(lockDocks()));
MAKE_ACTION_NOSC(tr("Show Toolbar"), "showViewerToolbar");
action->setCheckable(true);
action->setChecked(Settings::showViewerToolbar);
connect(action, &QAction::triggered, [this,action]() {
Settings::showViewerToolbar = action->isChecked();
m_imageToolBar->setVisible(Settings::showViewerToolbar);
positionImageToolbar();
});
m_refreshAction = MAKE_ACTION(tr("Reload"), "refresh", "F5");
SET_ICON(view-refresh);
connect(action, SIGNAL(triggered()), this, SLOT(reload()));
m_includeSubDirsAction = MAKE_ACTION_NOSC(tr("Include Sub-directories"), "includeSubDirs");
action->setIcon(QIcon(":/images/tree.png"));
action->setCheckable(true);
connect(action, SIGNAL(triggered()), this, SLOT(setIncludeSubDirs()));
MAKE_ACTION(tr("Paste Here"), "paste", "Ctrl+V");
SET_ICON(edit-paste);
connect(action, SIGNAL(triggered()), this, SLOT(pasteThumbs()));
action->setEnabled(false);
MAKE_ACTION_NOSC(tr("New Directory"), "createDir");
connect(action, SIGNAL(triggered()), this, SLOT(createSubDirectory()));
SET_ICON(folder-new);
MAKE_ACTION_NOSC(tr("Set Save Directory"), "setSaveDir");
connect(action, SIGNAL(triggered()), this, SLOT(setSaveDirectory()));
SET_ICON(folder-visiting);
m_goBackAction = MAKE_ACTION(tr("Back"), "goBack", "Alt+Left");
m_goBackAction->setIcon(QIcon::fromTheme("go-previous", QIcon(":/images/go-previous.png")));
connect(m_goBackAction, &QAction::triggered, this, [this]() {
if (currentHistoryIdx < 1)
return;
needHistoryRecord = false;
goTo(pathHistoryList.at(--currentHistoryIdx));
m_goFrwdAction->setEnabled(true);
if (currentHistoryIdx == 0)
m_goBackAction->setEnabled(false);
});
m_goBackAction->setEnabled(false);
m_goFrwdAction = MAKE_ACTION(tr("Forward"), "goFrwd", "Alt+Right");
m_goFrwdAction->setIcon(QIcon::fromTheme("go-next", QIcon(":/images/go-next.png")));
connect(m_goFrwdAction, &QAction::triggered, this, [this]() {
if (currentHistoryIdx > pathHistoryList.size() - 2)
return;
needHistoryRecord = false;
goTo(pathHistoryList.at(++currentHistoryIdx));
if (currentHistoryIdx == (pathHistoryList.size() - 1))
m_goFrwdAction->setEnabled(false);
});
m_goFrwdAction->setEnabled(false);
m_goUpAction = MAKE_ACTION(tr("Go Up"), "up", "Alt+Up");
SET_ICON(go-up);
connect(action, &QAction::triggered, [this](){ goTo(QFileInfo(Settings::currentDirectory).dir().absolutePath()); });
m_goHomeAction = MAKE_ACTION_NOSC(tr("Home"), "goHome");
connect(action, &QAction::triggered, [this](){
if (Settings::isFileListLoaded || Settings::filesList.isEmpty() || Settings::currentDirectory != QDir::homePath())
goTo(QDir::homePath());
else
goTo("Phototonic::FileList");
});
SET_ICON(go-home);
MAKE_ACTION(tr("Slide Show"), "toggleSlideShow", "Ctrl+W");
connect(action, &QAction::triggered, this, [this]() { setSlideShow(!m_slideShowActive); });
SET_ICON(media-playback-start);
m_nextImageAction = MAKE_ACTION(tr("Next Image"), "nextImage", "PgDown");
SET_ICON(go-next);
connect(action, &QAction::triggered, [this](){ loadImage(Phototonic::Next); });
m_prevImageAction = MAKE_ACTION(tr("Previous Image"), "prevImage", "PgUp");
SET_ICON(go-previous);
connect(action, &QAction::triggered, [this](){ loadImage(Phototonic::Previous); });
MAKE_ACTION(tr("First Image"), "firstImage", "Home");
SET_ICON(go-first);
connect(action, &QAction::triggered, [this](){ loadImage(Phototonic::First); });
MAKE_ACTION(tr("Last Image"), "lastImage", "End");
SET_ICON(go-last);
connect(action, &QAction::triggered, [this](){ loadImage(Phototonic::Last); });
MAKE_ACTION(tr("Random Image"), "randomImage", "Ctrl+D");
connect(action, &QAction::triggered, [this](){ loadImage(Phototonic::Random); });
m_viewImageAction = MAKE_ACTION(tr("View Image"), "open", "Return");
SET_ICON(document-open);
connect(action, SIGNAL(triggered()), this, SLOT(viewImage()));
MAKE_ACTION_NOSC(tr("Load Clipboard"), "showClipboard");
SET_ICON(insert-image);
connect(action, SIGNAL(triggered()), this, SLOT(newImage()));
m_wallpaperAction = MAKE_ACTION_NOSC(tr("Set Wallpaper"), "setwallpaper");
connect(action, &QAction::triggered, this, &Phototonic::runExternalApp);
openWithSubMenu = new QMenu(tr("Open With..."));
m_openWithMenuAction = MAKE_ACTION_NOSC(tr("Open With..."), "openWithMenu");
action->setMenu(openWithSubMenu);
MAKE_ACTION_NOSC(tr("External Applications"), "chooseApp");
action->setIcon(QIcon::fromTheme("preferences-other", QIcon(":/images/preferences-system.png")));
connect(action, SIGNAL(triggered()), this, SLOT(chooseExternalApp()));
MAKE_ACTION_NOSC(tr("Add Bookmark"), "addBookmark");
action->setIcon(QIcon(":/images/new_bookmark.png"));
connect(action, &QAction::triggered, [this](){ addBookmark(getSelectedPath()); });
MAKE_ACTION_NOSC(tr("Delete Bookmark"), "removeBookmark");
SET_ICON(edit-delete);
MAKE_ACTION(tr("Zoom Out"), "zoomOut", "-");
connect(action, &QAction::triggered, [this](){ zoom(-1.0f); });
SET_ICON(zoom-out);
MAKE_ACTION(tr("Zoom In"), "zoomIn", "+");
connect(action, &QAction::triggered, [this](){ zoom(1.0f); });
SET_ICON(zoom-in);
MAKE_ACTION(tr("Reset Zoom"), "resetZoom", "*");
SET_ICON(zoom-fit-best);
connect(action, &QAction::triggered, this, [this](){
imageViewer->zoomTo(imageViewer->zoomMode() == ImageViewer::ZoomToFit ?
ImageViewer::ZoomToFill :
ImageViewer::ZoomToFit);
});
MAKE_ACTION(tr("Original Size"), "origZoom", "/");
SET_ICON(zoom-original);
connect(action, &QAction::triggered, this, [this](){ imageViewer->zoomTo(ImageViewer::ZoomOriginal); });
MAKE_ACTION_NOSC(tr("Keep Zoom"), "keepZoom");
action->setCheckable(true);
connect(action, &QAction::toggled, this, [this](bool keep) {imageViewer->lockZoom(keep);});
MAKE_ACTION(tr("Rotate 90° CCW"), "rotateLeft", "Ctrl+Left");
SET_ICON(object-rotate-left);
connect(action, &QAction::triggered, this, [this]() { rotate(-90); });
MAKE_ACTION(tr("Rotate 90° CW"), "rotateRight", "Ctrl+Right");
SET_ICON(object-rotate-right);
connect(action, &QAction::triggered, this, [this]() { rotate(+90); });
MAKE_ACTION_NOSC(tr("Rotate with mouse"), "rotateMouse");
SET_ICON(rotation-allowed);
action->setCheckable(true);
connect(action, &QAction::triggered, [this,action](){
Settings::mouseRotateEnabled = action->isChecked();
imageViewer->setFeedback(tr("Or try holding Shift"));
});
MAKE_ACTION(tr("Flip Horizontally"), "flipH", "Ctrl+Down");
SET_ICON(object-flip-horizontal);
connect(action, SIGNAL(triggered()), this, SLOT(flipHorizontal()));
MAKE_ACTION(tr("Flip Vertically"), "flipV", "Ctrl+Up");
SET_ICON(object-flip-vertical);
connect(action, SIGNAL(triggered()), this, SLOT(flipVertical()));
MAKE_ACTION(tr("Letterbox"), "letterbox", "Ctrl+G");
action->setIcon(QIcon(":/images/crop.png"));
connect(action, SIGNAL(triggered()), this, SLOT(cropImage()));
MAKE_ACTION(tr("Scale Image"), "resize", "Ctrl+I");
SET_ICON(transform-scale);
connect(action, SIGNAL(triggered()), this, SLOT(scaleImage()));
MAKE_ACTION(tr("Rotate 1° CCW"), "freeRotateLeft", "Ctrl+Shift+Left");
connect(action, &QAction::triggered, this, [this]() { freeRotate(-1); });
MAKE_ACTION(tr("Rotate 1° CW"), "freeRotateRight", "Ctrl+Shift+Right");
connect(action, &QAction::triggered, this, [this]() { freeRotate(+1); });
MAKE_ACTION(tr("Colors"), "colors", "Ctrl+O");
connect(action, SIGNAL(triggered()), this, SLOT(showColorsDialog()));
action->setIcon(QIcon(":/images/colors.png"));
MAKE_ACTION_NOSC(tr("Crop"), "crop");
action->setIcon(QIcon(":/images/crop.png"));
connect(action, &QAction::triggered, [this](){ imageViewer->setEditMode(ImageViewer::Crop); });
MAKE_ACTION_NOSC(tr("Blackout"), "blackout");
action->setIcon(QIcon(":/images/blackout.png"));
connect(action, &QAction::triggered, [this](){ imageViewer->setEditMode(ImageViewer::Blackout); });
MAKE_ACTION_NOSC(tr("Cartouche"), "cartouche");
action->setIcon(QIcon(":/images/cartouche.png"));
connect(action, &QAction::triggered, [this](){ imageViewer->setEditMode(ImageViewer::Cartouche); });
MAKE_ACTION_NOSC(tr("Annotate"), "annotate");
action->setIcon(QIcon(":/images/annotate.png"));
connect(action, &QAction::triggered, [this](){ imageViewer->setEditMode(ImageViewer::Annotate); });
m_findDupesAction = MAKE_ACTION_NOSC(tr("Find Duplicate Images"), "findDupes");
action->setIcon(QIcon(":/images/duplicates.png"));
action->setCheckable(true);
connect(action, &QAction::triggered, [_LCD_]() {
if (action->isChecked()) {
sortByDuplicate->setVisible(true);
sortByDuplicate->setChecked(true);
// scenario: user enters a filter and clicks the duplicate button
QString error;
if (!thumbsViewer->setFilter(filterLineEdit->text(), &error))
QToolTip::showText(filterLineEdit->mapToGlobal(QPoint(0, filterLineEdit->height()*6/5)),
error, filterLineEdit);
} else {
sortByDuplicate->setVisible(false);
sortByName->setChecked(true);
}
refreshThumbs(true);
});
MAKE_ACTION(tr("Keep Transformations"), "keepTransform", "Ctrl+K");
action->setCheckable(true);
connect(action, &QAction::triggered, [this,action](){ imageViewer->keepTransformation(action->isChecked()); });
m_moveLeftAction = MAKE_ACTION(tr("Slide Image Left"), "moveLeft", "Left");
connect(action, &QAction::triggered, [this](){ imageViewer->slideImage(QPoint(50, 0)); });
m_moveRightAction = MAKE_ACTION(tr("Slide Image Right"), "moveRight", "Right");
connect(action, &QAction::triggered, [this](){ imageViewer->slideImage(QPoint(-50, 0)); });
m_moveUpAction = MAKE_ACTION(tr("Slide Image Up"), "moveUp", "Up");
connect(action, &QAction::triggered, [this](){ imageViewer->slideImage(QPoint(0, 50)); });
m_moveDownAction = MAKE_ACTION(tr("Slide Image Down"), "moveDown", "Down");
connect(action, &QAction::triggered, [this](){ imageViewer->slideImage(QPoint(0, -50)); });
MAKE_ACTION_NOSC(tr("Invert Selection"), "invertSelection");
connect(action, SIGNAL(triggered()), thumbsViewer, SLOT(invertSelection()));
// There could be a Batch submenu if we had any more items to put there
// QMenu *batchSubMenu = new QMenu(tr("Batch"));
// batchSubMenuAction = new QAction(tr("Batch"), this);
// batchSubMenuAction->setMenu(batchSubMenu);
m_batchTransformAction = MAKE_ACTION_NOSC(tr("Rotate and Crop images"), "batchTransform");
connect(action, SIGNAL(triggered()), this, SLOT(batchTransform()));
// batchSubMenu->addAction(batchTransformAction);
MAKE_ACTION(tr("Filter by Name"), "filterImagesFocus", "Ctrl+F");
connect(action, SIGNAL(triggered()), this, SLOT(filterImagesFocus()));
MAKE_ACTION(tr("Edit Current Path"), "setPathFocus", "Ctrl+L");
connect(action, SIGNAL(triggered()), this, SLOT(setPathFocus()));
m_imageInfoAction = MAKE_ACTION_NOSC(tr("Image Info"), "imageinfo");
action->setCheckable(true);
connect(action, &QAction::triggered, [this,action]() {
if (action->isChecked()) {
m_infoViewer->read(imageViewer->fullImagePath);
imageViewer->setFeedback(m_infoViewer->html(), false);
} else {
imageViewer->setFeedback("", false);
}
});
m_showGridAction = MAKE_ACTION_NOSC(tr("Show Grid"), "showgrid");
action->setCheckable(true);
connect(action, &QAction::triggered, [this,action]() { imageViewer->showGrid(action->isChecked()); });
QTimer::singleShot(500, this, [this]() {
QElapsedTimer profiler;
profiler.start();
QList actionlist = findChildren(Qt::FindDirectChildrenOnly);
for (QAction *action : actionlist) {
if (profiler.elapsed() > 30) {
QApplication::processEvents();
profiler.restart();
}
const QString icon = action->property("icon_name").toString();
if (icon.isEmpty())
continue;
action->setIcon(QIcon::fromTheme(icon, QIcon(":/images/" + icon + ".png")));
action->setProperty("icon_name", QVariant());
}
});
}
QAction *Phototonic::action(const QString name, bool dropCache) const {
static QHash actions;
if (name.isEmpty()) {
actions.clear();
return nullptr;
}
if (actions.isEmpty()) {
QList actionlist = findChildren(Qt::FindDirectChildrenOnly);
if (dropCache) {
for (QAction *action : actionlist)
if (action->objectName() == name)
return action;
qWarning() << "NO SUCH ACTION" << name;
return nullptr;
}
for (QAction *action : actionlist)
actions[action->objectName()] = action;
}
QAction *act = actions.value(name);
if (!act)
qWarning() << "NO SUCH ACTION" << name;
if (dropCache) {
actions.clear();
}
return act;
}
bool Phototonic::focusIsOnBrowsing() const {
return thumbsViewer->hasFocus() || (m_centralLayout->currentWidget() == thumbsViewer && !imageViewer->hasFocus());
}
void Phototonic::createMenus() {
QMenu *menu;
menu = myMainMenu->addMenu(tr("&File"));
menu->addAction(action("createDir"));
menu->addAction(action("setSaveDir"));
menu->addSeparator();
menu->addAction(action("showClipboard"));
menu->addAction(action("addBookmark"));
menu->addSeparator();
menu->addAction(action("findDupes"));
menu->addSeparator();
menu->addAction(action("exit"));
menu = myMainMenu->addMenu(tr("&Edit"));
menu->addAction(action("cut"));
menu->addAction(action("copy"));
menu->addAction(action("copyTo"));
menu->addAction(action("moveTo"));
menu->addAction(action("paste"));
menu->addAction(action("rename"));
menu->addAction(action("removeMetadata"));
menu->addAction(action("moveToTrash"));
menu->addAction(action("delete"));
menu->addSeparator();
menu->addAction(action("selectAll"));
menu->addAction(action("invertSelection"));
menu->addAction(action("batchTransform"));
// menu->addAction(batchSubMenuAction);
addAction(action("filterImagesFocus"));
addAction(action("setPathFocus"));
menu->addSeparator();
menu->addAction(action("chooseApp"));
menu->addAction(action("settings"));
//: "go" like in go forward, backward, etc
menu = myMainMenu->addMenu(tr("&Go"));
menu->addAction(action("goBack"));
menu->addAction(action("goFrwd"));
menu->addAction(action("up"));
menu->addAction(action("goHome"));
menu->addSeparator();
menu->addAction(action("prevImage"));
menu->addAction(action("nextImage"));
menu->addSeparator();
menu->addAction(action("thumbsGoTop"));
menu->addAction(action("thumbsGoBottom"));
menu->addSeparator();
menu->addAction(action("toggleSlideShow"));
//: configure visual features of the app
menu = myMainMenu->addMenu(tr("&View"));
menu->addMenu(createPopupMenu())->setText(tr("Window"));
menu->addSeparator();
QActionGroup *thumbLayoutsGroup = new QActionGroup(this);
thumbLayoutsGroup->addAction(action("setClassicThumbs"));
thumbLayoutsGroup->addAction(action("setSquareThumbs"));
thumbLayoutsGroup->addAction(action("setCompactThumbs"));
menu->addActions(thumbLayoutsGroup->actions());
menu->addSeparator();
menu->addAction(action("thumbsZoomIn"));
menu->addAction(action("thumbsZoomOut"));
QMenu *sortMenu = menu->addMenu(tr("Thumbnails Sorting"));
sortMenu->setIcon(style()->standardIcon(QStyle::SP_FileDialogDetailedView));
QActionGroup *sortTypesGroup = new QActionGroup(this);
sortTypesGroup->addAction(action("sortByName"));
sortTypesGroup->addAction(action("sortByDuplicate"));
sortTypesGroup->addAction(action("sortByTime"));
sortTypesGroup->addAction(action("sortByExifTime"));
sortTypesGroup->addAction(action("sortBySize"));
sortTypesGroup->addAction(action("sortByType"));
sortTypesGroup->addAction(action("sortBySimilarity"));
sortTypesGroup->addAction(action("sortByBrightness"));
sortTypesGroup->addAction(action("sortByColor"));
sortMenu->addActions(sortTypesGroup->actions());
sortMenu->addSeparator();
sortMenu->addAction(action("sortReverse"));
m_sortMenuAction = sortMenu->menuAction();
menu->addSeparator();
menu->addAction(action("includeSubDirs"));
menu->addAction(action("showHidden"));
menu->addSeparator();
menu->addAction(action("refresh"));
menu->addSeparator();
QMenuBar *mb = new QMenuBar;
mb->addActions(myMainMenu->actions());
mb->addMenu(tr("About"))->addAction(action("about"));
setMenuBar(mb);
mb->setVisible(false);
myMainMenu->addAction(action("settings"));
myMainMenu->addAction(action("about"));
// thumbs viewer context menu
thumbsViewer->addAction(action("open"));
thumbsViewer->addAction(action("setwallpaper"));
thumbsViewer->addAction(action("openWithMenu"));
thumbsViewer->addAction("")->setSeparator(true);
thumbsViewer->addAction(m_sortMenuAction);
thumbsViewer->addAction("")->setSeparator(true);
thumbsViewer->addAction(action("cut"));
thumbsViewer->addAction(action("copy"));
thumbsViewer->addAction(action("paste"));
thumbsViewer->addAction("")->setSeparator(true);
thumbsViewer->addAction(action("copyTo"));
thumbsViewer->addAction(action("moveTo"));
thumbsViewer->addAction("")->setSeparator(true);
thumbsViewer->addAction(action("selectAll"));
thumbsViewer->addAction(action("invertSelection"));
thumbsViewer->addAction("")->setSeparator(true);
thumbsViewer->addAction(action("batchTransform"));
// thumbsViewer->addAction(batchSubMenuAction);
thumbsViewer->addAction(action("regenerateThumbnail"));
thumbsViewer->addAction("")->setSeparator(true);
thumbsViewer->addAction(action("removeMetadata"));
thumbsViewer->addAction(action("moveToTrash"));
thumbsViewer->addAction(action("delete"));
thumbsViewer->setContextMenuPolicy(Qt::ActionsContextMenu);
}
void Phototonic::createToolBars() {
myMainToolBar = addToolBar("Toolbar");
myMainToolBar->setObjectName("MainBar");
myMainToolBar->setMovable(false);
// edit
// myMainToolBar->addAction(cutAction);
// myMainToolBar->addAction(copyAction);
// myMainToolBar->addAction(pasteAction);
// myMainToolBar->addAction(deleteAction);
// myMainToolBar->addAction(deletePermanentlyAction);
// myMainToolBar->addAction(showClipboardAction);
// navi
myMainToolBar->addAction(action("goBack"));
myMainToolBar->addAction(action("goFrwd"));
myMainToolBar->addAction(action("up"));
myMainToolBar->addAction(action("goHome"));
myMainToolBar->addAction(action("refresh"));
/* path bar */
m_progressBarAction = myMainToolBar->addWidget(m_progressBar = new QProgressBar);
m_progressBarAction->setVisible(false);
pathLineEdit = new QLineEdit;
DirCompleter *dirCompleter = new DirCompleter(pathLineEdit, fileSystemModel);
pathLineEdit->setCompleter(dirCompleter);
connect(dirCompleter, SIGNAL(activated(QString)), this, SLOT(goPathBarDir()));
std::unique_ptr pconn{new QMetaObject::Connection};
QMetaObject::Connection &conn = *pconn;
conn = connect(pathLineEdit, &QLineEdit::textEdited, [_LCD_](){fileSystemModel->setRootPath("/"); QObject::disconnect(conn);});
pathLineEdit->setMinimumWidth(200);
connect(pathLineEdit, SIGNAL(returnPressed()), this, SLOT(goPathBarDir()));
m_pathLineEditAction = myMainToolBar->addWidget(pathLineEdit);
myMainToolBar->addAction(action("includeSubDirs"));
myMainToolBar->addAction(m_sortMenuAction);
static_cast(myMainToolBar->widgetForAction(m_sortMenuAction))->setPopupMode(QToolButton::InstantPopup);
myMainToolBar->addAction(action("findDupes"));
QToolButton *btn = static_cast(myMainToolBar->widgetForAction(m_findDupesAction));
QMenu *btnmenu = new QMenu(btn);
QWidgetAction *qwa = new QWidgetAction(btnmenu);
QSpinBox *precision = new QSpinBox();
precision->setRange(0, 100);
precision->setSingleStep(5);
precision->setPrefix(tr("Accuracy: "));
precision->setSuffix("%");
precision->setValue(Settings::dupeAccuracy);
m_findDupesAction->setToolTip(m_findDupesAction->text() + "\n" + precision->text());
connect(precision, &QSpinBox::valueChanged, [_LCD_](int v) {
Settings::dupeAccuracy = v;
m_findDupesAction->setToolTip(m_findDupesAction->text() + "\n" + precision->text());
});
QAction *act = new QAction(btn->text());
act->setShortcut(Qt::Key_Enter);
act->setShortcutContext(Qt::WidgetWithChildrenShortcut);
connect(act, &QAction::triggered, [this]() {
m_findDupesAction->setChecked(false); m_findDupesAction->trigger();
});
precision->addAction(act);
btnmenu->addAction(act);
static const QString rtfmalso =
tr( "Ok, this isn't exactly AI driven."
"Duplicates are detected via a grayscale mosaic
"
"(do the desaturated images look the same from very far away?)
"
"and by comparing the color distribution
"
"(immune against mirrors, rotation, anamorphic scales …)
"
"Both can cause funny false positives.
"
"The required proximity of the color distribution can be configured here
"
"60% is a sensible default, but can be too easy if you're dealing with monochrome pictures
"
"Going much lower will cause too many false positives, increase the accuracy to get rid of such
"
"Notice that this can cause disjunct match groups!
"
"[A] can be similar to [B] and [C], while [B] and [C] are not close enough.
"
"The result is that [A] the same image can show up multiple times!
"
"Don't just assume the sorting is wrong these are clearly duplicates
"
"and press delete. They are the same image and deleting one means to
"
"delete both.
Pay attention to the file names!
"
);
precision->setToolTip(rtfmalso);
precision->setToolTipDuration(120000);
qwa->setDefaultWidget(precision);
btnmenu->addAction(qwa);
btn->setMenu(btnmenu);
btn->setPopupMode(QToolButton::MenuButtonPopup);
myMainToolBar->addAction(action("toggleSlideShow"));
/* filter bar */
filterLineEdit = new QLineEdit;
filterLineEdit->setMinimumWidth(100);
filterLineEdit->setMaximumWidth(200);
//: hint for the filter lineedit, "/" triggers more hints at extended features
filterLineEdit->setPlaceholderText(tr("Filter - try \"/?\"..."));
static const QString rtfm =
//: This is a tooltip explaining extended filter features
tr( "[substring] [/ constraint [/ more constraints]]
"
"foo / > 5d < 1M / < 10kb
"
"matches foo, older than 5 days but younger than a month - or below 10kB"
"- Bigger than/After: >
"
"- Smaller than/Before: <
"
"- The exact age or (rounded) size is otherwise implied or explicit with: =
"
"- Dates are absolute (YYYY-MM-DD) or relative (5m:h:d:w:M:y)
"
"- Sizes are suffixed 4kB:MB:GB or 4MP (mega-pixel)
"
"- Dimensions are pre/in/suffixed \"x\" ([width]x[height])
"
"- Chromatic variance is suffixed [0-255]cr (real values will rarely be > 100)
"
"- Hue is suffixed [0-359]° (center red is at 0/360)
"
"- Saturation is suffixed [0-100]%
"
"- Luminance is suffixed [0.0-1.0]|[0-255]lm
"
"All suffixes are case-insensitive but m|inute and M|onth
"
"Subsequent \"/\" start a new sufficient condition group, the substring match is optional."
"
In addition you can filter for
"
"black, white, brown, dark, bright, warm, cold, monochrome, gray and the colors
"
"red, orange, yellow, lime, green, mint, cyan, azure, blue, purple, magenta, pink"
"
!dark, !bright, !warm & !cold will invert the match (they're not complementary)"
"
Leading colons match tags, so '/:foo' finds all images with the tag 'foo'");
QTimer *filterBouncer = new QTimer(this);
filterBouncer->setSingleShot(true);
filterBouncer->setInterval(250);
connect (filterBouncer, &QTimer::timeout, this, [this]() {
if (filterLineEdit->text().contains("/?"))
return;
QString error;
if (thumbsViewer->setFilter(filterLineEdit->text(), &error))
QToolTip::showText(QPoint(), QString());
else
QToolTip::showText(filterLineEdit->mapToGlobal(QPoint(0, filterLineEdit->height()*6/5)),
error, filterLineEdit);
});
connect(filterLineEdit, &QLineEdit::textEdited, [_LCD_](){
if (filterLineEdit->text().contains("/?"))
QToolTip::showText(filterLineEdit->mapToGlobal(QPoint(0, filterLineEdit->height()*6/5)),
rtfm, filterLineEdit, {}, 300000);
filterBouncer->start();
});
filterLineEdit->setMouseTracking(true);
filterLineEdit->installEventFilter(this);
myMainToolBar->addSeparator();
myMainToolBar->addWidget(filterLineEdit);
act = new QAction;
act->setShortcut(Qt::Key_Escape);
act->setShortcutContext(Qt::WidgetWithChildrenShortcut);
connect(act, &QAction::triggered, [this]() {
thumbsViewer->setFocus(Qt::OtherFocusReason);
});
pathLineEdit->addAction(act);
filterLineEdit->addAction(act);
QAction *mainMenu = new QAction(tr("Menu"), this);
mainMenu->setIcon(QIcon::fromTheme("preferences-system", QIcon(":/images/preferences-system.png")));
mainMenu->setMenu(myMainMenu);
myMainToolBar->addAction(mainMenu);
m_menuButton = static_cast(myMainToolBar->widgetForAction(mainMenu));
m_menuButton->setPopupMode(QToolButton::InstantPopup);
m_menuButton->installEventFilter(this);
/* image */
m_imageToolBar = new QToolBar(tr("Viewer Toolbar"));
m_imageToolBar->setObjectName("m_imageToolBar");
for (const QString &s : Settings::imageToolActions) {
const QString ts = s.trimmed();
if (ts == "|")
m_imageToolBar->addSeparator();
else
m_imageToolBar->addAction(action(ts));
}
m_imageToolBar->setOrientation(Qt::Vertical);
QPalette pal = m_imageToolBar->palette();
pal.setColor(m_imageToolBar->backgroundRole(), QColor(0,0,0,128));
pal.setColor(m_imageToolBar->foregroundRole(), QColor(255,255,255,192));
m_imageToolBar->setPalette(pal);
m_imageToolBar->setAutoFillBackground(true);
m_imageToolBar->setPalette(pal);
m_imageToolBar->setIconSize(QSize(24,24));
setToolbarIconSize();
for (QAction *action : myMainToolBar->actions()) {
const QString icon = action->property("icon_name").toString();
if (icon.isEmpty())
continue;
action->setIcon(QIcon::fromTheme(icon, QIcon(":/images/" + icon + ".png")));
action->setProperty("icon_name", QVariant());
}
}
void Phototonic::setToolbarIconSize() {
if (initComplete) {
Settings::smallToolbarIcons = action("smallToolbarIcons", true)->isChecked();
}
int iconSize = Settings::smallToolbarIcons ? 16 : 24;
myMainToolBar->setIconSize(QSize(iconSize, iconSize));
}
void Phototonic::createFileSystemDock() {
fileSystemDock = new QDockWidget(tr("File System"), this);
fileSystemDock->setObjectName("File System");
fileSystemTree = new FileSystemTree(fileSystemDock);
fileSystemTree->addAction(action("createDir"));
fileSystemTree->addAction(action("rename"));
fileSystemTree->addAction(action("moveToTrash"));
fileSystemTree->addAction(action("delete"));
fileSystemTree->addAction(action("setwallpaper"));
fileSystemTree->addAction(action("openWithMenu"));
fileSystemTree->addAction(action("addBookmark"));
fileSystemTree->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(fileSystemTree, &FileSystemTree::clicked, this, [this]() { goTo(getSelectedPath()); });
connect(fileSystemModel, &QFileSystemModel::rowsRemoved, this, &Phototonic::checkDirState);
connect(fileSystemTree, &FileSystemTree::dropOp, this, &Phototonic::dropOp);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->setSpacing(0);
mainLayout->addWidget(fileSystemTree);
QWidget *fileSystemTreeMainWidget = new QWidget(fileSystemDock);
fileSystemTreeMainWidget->setLayout(mainLayout);
fileSystemDock->setWidget(fileSystemTreeMainWidget);
connect(fileSystemDock, &QDockWidget::visibilityChanged, [this](bool visible) {
if (visible && !fileSystemTree->model()) {
QTimer::singleShot(50, [this](){
fileSystemModel->setOptions(QFileSystemModel::Options());
fileSystemTree->setModel(fileSystemModel);
for (int i = 1; i < fileSystemModel->columnCount(); ++i) {
fileSystemTree->hideColumn(i);
}
fileSystemModel->setRootPath("/");
fileSystemTree->setCurrentIndex(fileSystemModel->index(Settings::currentDirectory));
fileSystemTree->scrollTo(fileSystemModel->index(Settings::currentDirectory));
connect(fileSystemTree->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(updateActions()) );
});
}
if (!m_presentationMode) {
Settings::fileSystemDockVisible = visible;
}
});
addDockWidget(Qt::LeftDockWidgetArea, fileSystemDock);
}
void Phototonic::createBookmarksDock() {
bookmarksDock = new QDockWidget(tr("Bookmarks"), this);
bookmarksDock->setObjectName("Bookmarks");
bookmarks = new BookMarks(bookmarksDock);
bookmarksDock->setWidget(bookmarks);
connect(bookmarksDock, &QDockWidget::visibilityChanged, [this](bool visible) {
if (!m_presentationMode) {
Settings::bookmarksDockVisible = visible;
}
});
connect(bookmarks, &BookMarks::itemClicked, [this](QTreeWidgetItem *item, int col) { goTo(item->toolTip(col)); });
connect(action("removeBookmark"), SIGNAL(triggered()), bookmarks, SLOT(removeBookmark()));
connect(bookmarks, SIGNAL(dropOp(Qt::KeyboardModifiers, bool, QString)),
this, SLOT(dropOp(Qt::KeyboardModifiers, bool, QString)));
addDockWidget(Qt::LeftDockWidgetArea, bookmarksDock);
bookmarks->addAction(action("paste"));
bookmarks->addAction(action("removeBookmark"));
bookmarks->setContextMenuPolicy(Qt::ActionsContextMenu);
}
void Phototonic::createImagePreviewDock() {
imagePreviewDock = new QDockWidget(tr("Preview"), this);
imagePreviewDock->setObjectName("ImagePreview");
connect(imagePreviewDock, &QDockWidget::visibilityChanged, [this](bool visible) {
if (!m_presentationMode) {
Settings::imagePreviewDockVisible = visible;
if (visible) {
m_centralLayout->removeWidget(imageViewer);
imagePreviewDock->setWidget(imageViewer);
imagePreviewDock->setContentsMargins(0,0,0,0);
m_thumbViewDock->hide();
int currentRow = thumbsViewer->currentIndex().row();
if (currentRow > -1)
imageViewer->loadImage(thumbsViewer->fullPathOf(currentRow), thumbsViewer->icon(currentRow).pixmap(THUMB_SIZE_MAX).toImage());
} else {
QTimer::singleShot(100, this, [this](){if (!imageViewer->isVisible()) imageViewer->clearImage();});
}
}
});
addDockWidget(Qt::RightDockWidgetArea, imagePreviewDock);
}
void Phototonic::createThumbviewDock() {
m_thumbViewDock = new QDockWidget(tr("Thumbs"), this);
m_thumbViewDock->setObjectName("ThumbView");
connect(m_thumbViewDock, &QDockWidget::visibilityChanged, [this](bool visible) {
if (!m_presentationMode) {
Settings::thumbViewDockVisible = visible;
if (visible) {
m_centralLayout->removeWidget(thumbsViewer);
m_thumbViewDock->setWidget(thumbsViewer);
m_thumbViewDock->setContentsMargins(0,0,0,0);
imagePreviewDock->hide();
m_centralLayout->addWidget(imageViewer);
m_centralLayout->setCurrentWidget(imageViewer);
} else {
m_centralLayout->addWidget(thumbsViewer);
m_centralLayout->setCurrentWidget(thumbsViewer);
}
}
});
addDockWidget(Qt::RightDockWidgetArea, m_thumbViewDock);
}
void Phototonic::createImageTagsDock() {
//: tags are image metadata
tagsDock = new QDockWidget(tr("Tags"), this);
tagsDock->setObjectName("Tags");
m_imageTags = new ImageTags(tagsDock);
tagsDock->setWidget(m_imageTags);
connect(tagsDock, &QDockWidget::visibilityChanged, [this](bool visible) {
if (!m_presentationMode) {
Settings::tagsDockVisible = visible;
}
});
connect(m_imageTags, &ImageTags::filterChanged, this,
[this](const QStringList &mandatory, const QStringList &sufficient, bool invert) {
thumbsViewer->setTagFilters(mandatory, sufficient, invert);
});
connect(m_imageTags, &ImageTags::tagRequest, [this](const QStringList &tagsAdded, const QStringList &tagsRemoved) {
thumbsViewer->tagSelected(tagsAdded, tagsRemoved);
if (m_infoViewer && m_infoViewer->isVisible())
m_infoViewer->reloadExifData();
});
connect(thumbsViewer, &ThumbsViewer::filesHidden, m_imageTags, &ImageTags::removeTagsFor);
connect(thumbsViewer, &ThumbsViewer::filesShown, m_imageTags, &ImageTags::addTagsFor);
connect(thumbsViewer, &ThumbsViewer::lazySelectionChanged, m_imageTags, [this]() {
m_imageTags->setSelectedFiles(thumbsViewer->selectedFiles());
});
m_imageTags->populateTagsTree();
}
void Phototonic::sortThumbnails() {
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
if (QAction *trigger = qobject_cast(sender())) {
thumbsViewer->thumbsSortFlags &= QDir::IgnoreCase|QDir::Reversed;
if (trigger->objectName() == "sortByName") {
thumbModel->setSortRole(Qt::DisplayRole/* ThumbsViewer::SortRole */);
} else if (trigger->objectName() == "sortByDuplicate") {
thumbModel->setSortRole(ThumbsViewer::SortRole);
} else if (trigger->objectName() == "sortByTime") {
thumbsViewer->thumbsSortFlags |= QDir::Time;
thumbModel->setSortRole(ThumbsViewer::TimeRole);
} else if (trigger->objectName() == "sortByExifTime") {
thumbModel->setSortRole(ThumbsViewer::DateTimeOriginal);
} else if (trigger->objectName() == "sortBySize") {
thumbsViewer->thumbsSortFlags |= QDir::Size;
thumbModel->setSortRole(ThumbsViewer::SizeRole);
} else if (trigger->objectName() == "sortByType") {
thumbsViewer->thumbsSortFlags |= QDir::Type;
thumbModel->setSortRole(ThumbsViewer::TypeRole);
} else if (trigger->objectName() == "sortBySimilarity") {
thumbModel->setSortRole(ThumbsViewer::HistogramRole);
} else if (trigger->objectName() == "sortByBrightness") {
thumbModel->setSortRole(ThumbsViewer::BrightnessRole);
} else if (trigger->objectName() == "sortByColor") {
thumbModel->setSortRole(ThumbsViewer::ColorRole);
} else if (trigger->objectName() == "sortReverse") {
if (trigger->isChecked())
thumbsViewer->thumbsSortFlags |= QDir::Reversed;
else
thumbsViewer->thumbsSortFlags &= ~QDir::Reversed;
}
}
if (thumbModel->sortRole() == ThumbsViewer::HistogramRole)
thumbsViewer->scanForSort(ThumbsViewer::HistogramRole);
else if (thumbModel->sortRole() == ThumbsViewer::BrightnessRole || thumbModel->sortRole() == ThumbsViewer::ColorRole)
thumbsViewer->scanForSort(ThumbsViewer::BrightnessRole);
thumbModel->sort(0, (thumbsViewer->thumbsSortFlags & QDir::Reversed) ? Qt::DescendingOrder : Qt::AscendingOrder);
thumbsViewer->loadVisibleThumbs(-1);
}
void Phototonic::reload() {
m_findDupesAction->setChecked(false);
if (focusIsOnBrowsing()) {
refreshThumbs(false);
} else {
imageViewer->reload();
}
}
void Phototonic::setIncludeSubDirs() {
m_findDupesAction->setChecked(false);
Settings::includeSubDirectories = m_includeSubDirsAction->isChecked();
refreshThumbs(false);
}
void Phototonic::refreshThumbs(bool scrollToTop) {
thumbsViewer->setNeedToScroll(scrollToTop);
if (m_reloadPending)
return;
m_reloadPending = true;
QMetaObject::invokeMethod(this, "reloadThumbs", Qt::QueuedConnection);
}
void Phototonic::showHiddenFiles() {
QAction *showHiddenFiles = qobject_cast(sender());
if (!showHiddenFiles || showHiddenFiles->objectName() != "showHidden") {
qWarning() << "showHiddenFiles called w/o showHiddenFiles action!";
return;
}
Settings::showHiddenFiles = showHiddenFiles->isChecked();
if (Settings::showHiddenFiles)
fileSystemModel->setFilter(fileSystemModel->filter() | QDir::Hidden);
else
fileSystemModel->setFilter(fileSystemModel->filter() & ~QDir::Hidden);
refreshThumbs(false);
}
void Phototonic::filterImagesFocus() {
if (thumbsViewer->isVisible()) {
myMainToolBar->show();
filterLineEdit->setFocus(Qt::OtherFocusReason);
filterLineEdit->selectAll();
}
}
void Phototonic::setPathFocus() {
if (thumbsViewer->isVisible()) {
myMainToolBar->show();
pathLineEdit->setFocus(Qt::OtherFocusReason);
pathLineEdit->selectAll();
}
}
void Phototonic::runExternalApp() {
QString execCommand = sender() == m_wallpaperAction ? Settings::wallpaperCommand :
Settings::externalApps[static_cast(sender())->text()];
auto substituteCommand = [this,&execCommand](QString path) {
char parameter = 2;
if (execCommand.contains("%f", Qt::CaseInsensitive))
execCommand.replace("%f", path, Qt::CaseInsensitive);
else if (execCommand.contains("%u", Qt::CaseInsensitive))
execCommand.replace("%u", QUrl::fromLocalFile(path).url(), Qt::CaseInsensitive);
else
--parameter;
if (execCommand.contains("%tf", Qt::CaseInsensitive))
execCommand.replace("%tf", thumbsViewer->locateThumbnail(path), Qt::CaseInsensitive);
else if (execCommand.contains("%tu", Qt::CaseInsensitive))
execCommand.replace("%tu", QUrl::fromLocalFile(thumbsViewer->locateThumbnail(path)).url(), Qt::CaseInsensitive);
else if (execCommand.contains("%lat", Qt::CaseInsensitive) ||
execCommand.contains("%lon", Qt::CaseInsensitive) ||
execCommand.contains("%alt", Qt::CaseInsensitive)) {
double lat, lon, alt;
Metadata::gpsData(path, lat, lon, alt);
execCommand.replace("%lat", QString::number(lat), Qt::CaseInsensitive);
execCommand.replace("%lon", QString::number(lon), Qt::CaseInsensitive);
execCommand.replace("%alt", QString::number(alt), Qt::CaseInsensitive);
} else {
--parameter;
}
if (!parameter)
execCommand += " \"" + path + "\"";
};
if (!focusIsOnBrowsing()) {
if (imageViewer->isNewImage()) {
showNewImageWarning();
return;
}
substituteCommand(imageViewer->fullImagePath);
} else {
if (QApplication::focusWidget() == fileSystemTree) {
substituteCommand(getSelectedPath());
} else {
QModelIndexList selectedIdxList = thumbsViewer->selectionModel()->selectedIndexes();
if (selectedIdxList.size() < 1) {
setStatus(tr("Invalid selection."));
return;
}
if (selectedIdxList.size() == 1) {
substituteCommand(thumbsViewer->fullPathOf(selectedIdxList.at(0).row()));
} else {
if (execCommand.contains("%f", Qt::CaseInsensitive) || execCommand.contains("%u", Qt::CaseInsensitive) ||
execCommand.contains("%tf", Qt::CaseInsensitive) || execCommand.contains("%tu", Qt::CaseInsensitive)) {
setStatus(tr("Commands using %f or %u cannot be used with multiple files."));
return;
}
for (int tn = selectedIdxList.size() - 1; tn >= 0; --tn) {
execCommand += " \"" + thumbsViewer->fullPathOf(selectedIdxList.at(tn).row()) + "\"";
}
}
}
}
QStringList command = QProcess::splitCommand(execCommand);
if (!QProcess::startDetached(command.takeFirst(), command)) {
MessageBox(this).critical(tr("Error"), tr("Failed to start external application."));
}
}
void Phototonic::updateExternalApps() {
m_wallpaperAction->setVisible(!Settings::wallpaperCommand.isEmpty());
int actionNumber = 0;
QMapIterator externalAppsIterator(Settings::externalApps);
QList actionList = openWithSubMenu->actions();
if (!actionList.empty()) {
for (int i = 0; i < actionList.size(); ++i) {
QAction *action = actionList.at(i);
if (action->isSeparator()) {
break;
}
openWithSubMenu->removeAction(action);
imageViewer->removeAction(action);
action->deleteLater();
}
openWithSubMenu->clear();
}
while (externalAppsIterator.hasNext()) {
++actionNumber;
externalAppsIterator.next();
QAction *extAppAct = new QAction(externalAppsIterator.key(), this);
if (actionNumber < 10) {
extAppAct->setShortcut(QKeySequence("Alt+" + QString::number(actionNumber)));
}
extAppAct->setIcon(QIcon::fromTheme(externalAppsIterator.key()));
connect(extAppAct, SIGNAL(triggered()), this, SLOT(runExternalApp()));
openWithSubMenu->addAction(extAppAct);
imageViewer->addAction(extAppAct);
}
openWithSubMenu->addSeparator();
openWithSubMenu->addAction(action("chooseApp", true));
}
void Phototonic::chooseExternalApp() {
ExternalAppsDialog *externalAppsDialog = new ExternalAppsDialog(this);
setSlideShow(false);
imageViewer->setCursorHiding(false);
externalAppsDialog->exec();
updateExternalApps();
externalAppsDialog->deleteLater();
if (isFullScreen()) {
imageViewer->setCursorHiding(true);
}
}
void Phototonic::showSettings() {
setSlideShow(false);
imageViewer->setCursorHiding(false);
SettingsDialog *settingsDialog = new SettingsDialog(this);
if (settingsDialog->exec()) {
imageViewer->setBackgroundColor();
thumbsViewer->setThumbColors();
imageViewer->showFileName(Settings::showImageName);
if (imageViewer->isVisible()) {
imageViewer->reload();
action("rotateMouse", true)->setChecked(Settings::mouseRotateEnabled);
}
needThumbsRefresh = true;
if (thumbsViewer->isVisible()) {
needThumbsRefresh = false;
thumbsViewer->refreshThumbs();
}
if (!Settings::setWindowIcon) {
setWindowIcon(QApplication::windowIcon());
}
m_imageToolBar->clear();
for (const QString &s : Settings::imageToolActions) {
const QString ts = s.trimmed();
if (ts == "|")
m_imageToolBar->addSeparator();
else
m_imageToolBar->addAction(action(ts));
m_imageToolBar->adjustSize();
}
writeSettings();
}
if (isFullScreen()) {
imageViewer->setCursorHiding(true);
}
settingsDialog->deleteLater();
}
void Phototonic::toggleFullScreen() {
Settings::isFullScreen = m_fullScreenAction->isChecked();
imageViewer->setCursorHiding(Settings::isFullScreen);
const bool useDock = imagePreviewDock->isFloating() && imagePreviewDock->isVisible();
if (m_fullScreenAction->isChecked()) {
if (useDock) {
delete imagePreviewDock->titleBarWidget();
imagePreviewDock->setTitleBarWidget(new QWidget(imagePreviewDock));
imagePreviewDock->setWindowState(imagePreviewDock->windowState() | Qt::WindowFullScreen);
} else {
setWindowState(windowState() | Qt::WindowFullScreen);
}
}
else {
if (useDock) {
imagePreviewDock->setWindowState(imagePreviewDock->windowState() & ~Qt::WindowFullScreen);
delete imagePreviewDock->titleBarWidget();
imagePreviewDock->setTitleBarWidget(nullptr);
}
// unconditionally in case the dock state changed and we need to get out of the fullscreen
setWindowState(windowState() & ~Qt::WindowFullScreen);
}
}
void Phototonic::selectAllThumbs() {
thumbsViewer->selectAll();
}
#define ASSERT_IMAGES_SELECTED if(thumbsViewer->selectionModel()->selectedIndexes().size()<1){setStatus(tr("No images selected"));return;}
void Phototonic::copyOrCutThumbs(bool isCopyOperation) {
ASSERT_IMAGES_SELECTED
Settings::copyCutIndexList = thumbsViewer->selectionModel()->selectedIndexes();
copyCutThumbsCount = Settings::copyCutIndexList.size();
Settings::copyCutFileList.clear();
QList urlList;
for (int thumb = 0; thumb < copyCutThumbsCount; ++thumb) {
const QString filePath = thumbsViewer->fullPathOf(Settings::copyCutIndexList.at(thumb).row());
Settings::copyCutFileList.append(filePath);
urlList.append(QUrl::fromLocalFile(filePath)); // The standard apparently is URLs even for local files...
}
QMimeData *mimedata = new QMimeData;
mimedata->setUrls(urlList);
QGuiApplication::clipboard()->setMimeData(mimedata);
Settings::isCopyOperation = isCopyOperation;
action("paste", true)->setEnabled(true);
QString state = Settings::isCopyOperation ? tr("Copied %n image(s) to clipboard", "", copyCutThumbsCount)
: tr("Cut %n image(s) to clipboard", "", copyCutThumbsCount);
setStatus(state);
}
void Phototonic::copyOrMoveImages(bool isCopyOperation) {
setSlideShow(false);
if (!isCopyOperation && thumbsViewer->isBusy()) { // defer, don't alter while the thumbsviewer is loading stuff
QTimer::singleShot(100, this, [_LCD_](){copyOrMoveImages(isCopyOperation);});
return;
}
imageViewer->setCursorHiding(false);
auto cleanup = [this]() { if (isFullScreen()) imageViewer->setCursorHiding(true); };
CopyMoveToDialog copyMoveToDialog(this, getSelectedPath(), isCopyOperation);
if (!copyMoveToDialog.exec())
return cleanup();
bookmarks->reloadBookmarks();
if (focusIsOnBrowsing()) {
copyOrCutThumbs(isCopyOperation);
pasteThumbs(copyMoveToDialog.destination());
return cleanup();
}
if (imageViewer->isNewImage()) {
showNewImageWarning();
return cleanup();
}
QString destFile = copyMoveToDialog.destination() + QDir::separator() + QFileInfo(imageViewer->fullImagePath).fileName();
if (QFileInfo::exists(destFile)) {
QMap conflict;
conflict[imageViewer->fullImagePath] = destFile;
if (CopyOrMove::resolveConflicts(conflict, this) != QDialog::Accepted)
return cleanup();
destFile = conflict.value(imageViewer->fullImagePath);
if (destFile.isEmpty())
return cleanup();
}
int result = CopyOrMove::file(imageViewer->fullImagePath, destFile, isCopyOperation);
if (!result) {
MessageBox(this).critical(tr("Error"), tr("Failed to copy or move image."));
} else {
if (!isCopyOperation) {
int currentRow = thumbsViewer->currentIndex().row();
thumbsViewer->model()->removeRow(currentRow);
loadCurrentImage(currentRow);
}
}
}
void Phototonic::resizeThumbs() {
if (!m_thumbSizeDelta)
return;
const int previous = thumbsViewer->thumbSize;
thumbsViewer->thumbSize += m_thumbSizeDelta*THUMB_SIZE_MIN;
if (m_thumbSizeDelta > 0)
thumbsViewer->thumbSize = qMin(thumbsViewer->thumbSize,THUMB_SIZE_MAX);
else
thumbsViewer->thumbSize = qMax(thumbsViewer->thumbSize,THUMB_SIZE_MIN);
m_thumbSizeDelta = 0;
action("thumbsZoomOut")->setEnabled(thumbsViewer->thumbSize > THUMB_SIZE_MIN);
action("thumbsZoomIn", true)->setEnabled(thumbsViewer->thumbSize < THUMB_SIZE_MAX);
if (thumbsViewer->thumbSize != previous)
thumbsViewer->refreshThumbs();
}
void Phototonic::zoom(float multiplier, QPoint focus) {
// sanitize to 10% step, necessary for unscale image and zoominator
float zoomTarget = qRound(imageViewer->zoom()*10)*0.1;
if (multiplier > 0.0 && zoomTarget == 16.0) {
imageViewer->setFeedback(tr("Maximum Zoom"));
return;
}
if (multiplier < 0.0 && zoomTarget == 0.1) {
imageViewer->setFeedback(tr("Minimum Zoom"));
return;
}
// by size
multiplier *= zoomTarget * 0.5;
if (focus.x() >= 0) {
// by speed
static QElapsedTimer speedometer;
if (!speedometer.isValid() || speedometer.elapsed() > 250)
multiplier *= 0.05;
else if (speedometer.elapsed() > 150)
multiplier *= 0.1;
else if (speedometer.elapsed() > 75)
multiplier *= 0.5;
speedometer.restart();
} else {
multiplier *= 0.5;
}
// round and limit to 10%
multiplier = multiplier > 0.0 ? qMax(0.1, qRound(multiplier*10)*0.1) : qMin(-0.1, qRound(multiplier*10)*0.1);
zoomTarget = qMin(16.0, qMax(0.1, zoomTarget + multiplier));
imageViewer->zoomTo(zoomTarget, focus);
//: nb the trailing "%" for eg. 80%
imageViewer->setFeedback(tr("Zoom %1%").arg(QString::number(zoomTarget * 100)));
}
void Phototonic::rotate(int deg) {
if (!deg)
return;
qreal rotation = imageViewer->rotation() + deg;
if (qAbs(rotation) > 360.0)
rotation -= int(360*rotation)/360;
if (deg > 0) {
rotation = 90*int(rotation/90);
if (rotation > 270)
rotation -= 360;
} else {
rotation = 90*qCeil(rotation/90);
if (rotation < 0)
rotation += 360;
}
imageViewer->rotateTo(rotation, deg > 0 ? ImageViewer::CW : ImageViewer::CCW);
imageViewer->setFeedback(tr("Rotation %1°").arg(QString::number(rotation)));
m_editSteps = qMax(0, m_editSteps + (rotation ? 1 : -1));
m_saveAction->setEnabled(m_editSteps);
m_saveAsAction->setEnabled(m_editSteps);
}
void Phototonic::flipVertical() {
const bool flips = imageViewer->flip(Qt::Vertical);
m_editSteps = qMax(0, m_editSteps + (flips ? 1 : -1));
m_saveAction->setEnabled(m_editSteps);
m_saveAsAction->setEnabled(m_editSteps);
}
void Phototonic::flipHorizontal() {
const bool flips = imageViewer->flip(Qt::Horizontal);
m_editSteps = qMax(0, m_editSteps + (flips ? 1 : -1));
m_saveAction->setEnabled(m_editSteps);
m_saveAsAction->setEnabled(m_editSteps);
}
void Phototonic::cropImage() {
setSlideShow(false);
imageViewer->setCursorHiding(false);
imageViewer->configureLetterbox();
if (isFullScreen())
imageViewer->setCursorHiding(true);
}
void Phototonic::scaleImage() {
setSlideShow(false);
imageViewer->setCursorHiding(false);
// if (m_presentationMode) {
ResizeDialog dlg(imageViewer->currentImageSize(), imageViewer);
if (dlg.exec() == QDialog::Accepted) {
imageViewer->scaleImage(dlg.newSize());
}
// } else {
// ASSERT_IMAGES_SELECTED
/// @todo: looks like there were plans to allow mass-resizing from the thumbnail browser
// }
if (isFullScreen())
imageViewer->setCursorHiding(true);
}
void Phototonic::freeRotate(int deg) {
qreal r = imageViewer->rotation() + deg;
if (r < 0)
r = 359;
if (r > 360)
r = 1;
imageViewer->rotateTo(r, ImageViewer::Direct);
imageViewer->setFeedback(tr("Rotation %1°").arg(QString::number(qRound(r))));
}
void Phototonic::batchTransform() {
QModelIndexList idxs = thumbsViewer->selectionModel()->selectedIndexes();
if (idxs.count() < 2) {
return MessageBox(this).critical(tr("No images selected"), tr("Please select the images to transform."));
}
QRect cropRect = imageViewer->lastCropGeometry();
if (!cropRect.isValid()) {
MessageBox(this).warning( tr("No crop area defined"),
tr( "Define a crop area
"
"Open an image, maybe rotate it.
"
"Then press and hold shift to select a crop rect.
"
"Do not apply the crop by double clicking the selection!
"
"If not using the preview, exit the Viewer.
"
"You can now replay the action on multiple images."));
return;
}
QString message;
bool createBackups = true;
if (Settings::saveDirectory.isEmpty()) {
if (MessageBox(this, MessageBox::Yes|MessageBox::No, MessageBox::Yes).warning(
tr("Create backups?"), tr("No global save directory is defined, the images will be overwritten."
"Do you want to create backups?
")) == MessageBox::No) {
createBackups = false;
}
message = createBackups ? tr("Create backups and overwrite the original files") : tr("Overwrite the original files");
}
else {
message = tr("Save the transformed images to %1").arg(Settings::saveDirectory);
}
MessageBox msgBox(this, MessageBox::Ok | MessageBox::Cancel, MessageBox::Ok);
msgBox.setInformativeText(tr("- Rotate %1 images by %2°
"
"- Crop them to %3+%4+%5x%6
"
"- %7
").arg(idxs.count()).arg(imageViewer->rotation(), 0, 'f', 1)
.arg(cropRect.x()).arg(cropRect.y())
.arg(cropRect.width()).arg(cropRect.height())
.arg(message));
if (msgBox.ask(tr("Batch transformation"), tr("Perform batch transformation?
")) != MessageBox::Ok)
return;
if (createBackups) {
for (QModelIndex i : idxs) {
QString path = thumbsViewer->fullPathOf(i.row()); // copyFile rewrites the destination
int result = CopyOrMove::copyFile(path, path);
if (!result) {
return MessageBox(this).critical(tr("Error"), tr("Failed to copy or move image."));
}
}
}
imageViewer->batchMode = true;
setUpdatesEnabled(false);
for (QModelIndex i : idxs) {
loadSelectedThumbImage(i);
imageViewer->applyCropAndRotation();
imageViewer->saveImage();
}
imageViewer->batchMode = false;
setUpdatesEnabled(true);
thumbsViewer->refreshThumbs();
}
void Phototonic::showColorsDialog() {
setSlideShow(false);
if (!colorsDialog) {
colorsDialog = new ColorsDialog(this, imageViewer);
connect(colorsDialog, &QDialog::finished, [this](){ Settings::colorsActive = false; });
connect(imageViewer, &ImageViewer::imageEdited, [this](bool dirty){ if (!dirty)colorsDialog->reset(); });
}
imageViewer->setCursorHiding(false);
Settings::colorsActive = true;
colorsDialog->exec();
if (isFullScreen())
imageViewer->setCursorHiding(true);
}
static bool isWritableDir(const QString &path) {
QFileInfo info(path);
return info.exists() && info.isDir() && info.isWritable();
}
static bool isReadableDir(const QString &path) {
QDir checkPath(path);
return checkPath.exists() && checkPath.isReadable();
}
void Phototonic::pasteThumbs(QString destDir) {
static bool pasteInProgress = false;
if (!copyCutThumbsCount) {
return;
}
if (destDir.isNull()) {
if (QApplication::focusWidget() != bookmarks) {
destDir = getSelectedPath();
} else if (bookmarks->currentItem()) {
destDir = bookmarks->currentItem()->toolTip(0);
}
}
if (!isWritableDir(destDir)) {
if (destDir.isEmpty())
destDir = "0x0000";
MessageBox(this).critical(tr("Error"), tr("Can not copy or move to %1").arg(destDir));
return selectCurrentViewDir();
}
bool pasteInCurrDir = (Settings::currentDirectory == destDir);
QFileInfo fileInfo;
if (!Settings::isCopyOperation && pasteInCurrDir) {
for (int thumb = 0; thumb < Settings::copyCutFileList.size(); ++thumb) {
fileInfo = QFileInfo(Settings::copyCutFileList.at(thumb));
if (fileInfo.absolutePath() == destDir) {
return MessageBox(this).critical(tr("Error"), tr("Can not move to the same directory"));
}
}
}
if (pasteInProgress || thumbsViewer->isBusy()) { // defer, don't alter while the thumbsviewer is loading stuff
QTimer::singleShot(100, this, [this](){pasteThumbs();});
return;
}
pasteInProgress = true;
copyCutThumbsCount = 0; // setting this here avoids nested pastes
int latestRow = CopyOrMove::list(thumbsViewer, destDir, pasteInCurrDir, this);
int n = 0;
if (!pasteInCurrDir && thumbsViewer->model()->rowCount()) {
n = Settings::copyCutIndexList.size();
thumbsViewer->setCurrentIndex(qMin(latestRow, thumbsViewer->model()->rowCount() - 1));
}
QString state = Settings::isCopyOperation ? tr("Copied %n image(s)", "", n) : tr("Moved %n image(s)", "", n);
setStatus(state);
selectCurrentViewDir();
Settings::copyCutIndexList.clear();
Settings::copyCutFileList.clear();
action("paste", true)->setEnabled(false);
thumbsViewer->loadVisibleThumbs();
pasteInProgress = false;
}
void Phototonic::loadCurrentImage(int currentRow) {
if (thumbsViewer->model()->rowCount() == 0) {
hideViewer();
refreshThumbs(true);
return;
}
bool wrapImageListTmp = Settings::wrapImageList;
Settings::wrapImageList = false;
if (currentRow > thumbsViewer->model()->rowCount() - 1) {
currentRow = thumbsViewer->model()->rowCount() - 1;
}
thumbsViewer->setCurrentIndex(currentRow);
Settings::wrapImageList = wrapImageListTmp;
}
void Phototonic::deleteImages(bool trash) { // Deleting selected thumbnails
if (m_deleteInProgress)
return; // no.
if (thumbsViewer->isBusy()) { // defer, don't alter while the thumbsviewer is loading stuff
QTimer::singleShot(100, this, [_LCD_](){deleteImages(trash);});
return;
}
ASSERT_IMAGES_SELECTED
QStringList deathRow;
for (QModelIndex idx : thumbsViewer->selectionModel()->selectedIndexes())
deathRow << thumbsViewer->fullPathOf(idx.row());
if (Settings::deleteConfirm) {
MessageBox msgBox(this, MessageBox::Yes|MessageBox::Cancel, MessageBox::Yes);
QString ttl = trash ? tr("Move to Trash") : tr("Delete images");
QString msg = trash ? tr("Move %n selected image(s) to the trash?", "", deathRow.size())
: tr("Permanently delete %n selected image(s)?", "", deathRow.size());
QString fileList;
msgBox.setDetailedText(deathRow.join("\n"));
if (QTextEdit *details = msgBox.findChild())
details->setWordWrapMode(QTextOption::NoWrap);
if (msgBox.warning(ttl, msg) != MessageBox::Yes) {
return;
}
}
// To only show progress dialog if deleting actually takes time
QElapsedTimer timer;
timer.start();
int totalTime = 0;
// Avoid a lot of not interesting updates while deleting
QSignalBlocker fsBlocker(fileSystemModel);
QSignalBlocker scrollbarBlocker(thumbsViewer->verticalScrollBar());
// Avoid reloading thumbnails all the time
m_deleteInProgress = true;
QProgressDialog *progress = nullptr;
int deleteFilesCount = 0;
int cycle = 1;
QStringList filesRemoved;
for (int i = 0; i < deathRow.size(); ++i) {
// Only show if it takes a lot of time, since popping this up for just
// deleting a single image is annoying
const QString &fileNameFullPath = deathRow.at(i);
if (timer.elapsed() > 30) {
if ((totalTime += timer.elapsed()) > 250) {
totalTime = 0;
if (!progress && float(i)/deathRow.size() < 1.0f-1.0f/++cycle) {
progress = new QProgressDialog(this);
progress->setMaximum(deathRow.size());
QLabel *l = new QLabel(progress);
l->setWordWrap(true);
l->setFixedWidth(QFontMetrics(l->font()).averageCharWidth()*80);
progress->setLabel(l);
progress->show();
}
}
timer.restart();
if (progress) {
progress->setValue(i);
progress->setLabelText(tr("Deleting %1").arg(fileNameFullPath));
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
// w/o the file the canonical path cannot be resolved
ThumbsViewer::removeFromCache(fileNameFullPath);
QFile fileToRemove(fileNameFullPath);
bool deleteOk;
if (trash)
deleteOk = fileToRemove.moveToTrash();
else
deleteOk = fileToRemove.remove();
++deleteFilesCount;
if (deleteOk) {
filesRemoved << fileNameFullPath;
QModelIndexList indexList = thumbsViewer->model()->match(thumbsViewer->model()->index(0, 0), ThumbsViewer::FileNameRole, fileNameFullPath);
if (indexList.size())
thumbsViewer->model()->removeRow(indexList.at(0).row());
} else {
MessageBox(this).critical(tr("Error"), (trash ? tr("Failed to move image to the trash.") :
tr("Failed to delete image.")) + "\n" + fileToRemove.errorString());
break;
}
Settings::filesList.removeOne(fileNameFullPath);
if (progress && progress->wasCanceled()) {
break;
}
}
if (progress) {
progress->close();
progress->deleteLater();
}
m_imageTags->removeTagsFor(filesRemoved);
for (const QString &path : filesRemoved)
Metadata::forget(path);
setStatus(tr("Deleted %n image(s)", "", deleteFilesCount));
m_deleteInProgress = false;
}
void Phototonic::deleteFromViewer(bool trash) {
if (m_deleteInProgress)
return; // no.
if (imageViewer->isNewImage()) {
showNewImageWarning();
return;
}
setSlideShow(false); // needs to happen now
imageViewer->setCursorHiding(false); // tells that sth. is happening
if (thumbsViewer->isBusy()) { // defer, don't alter while the thumbsviewer is loading stuff
QTimer::singleShot(100, this, [_LCD_](){deleteFromViewer(trash);});
return;
}
const QString fullPath = imageViewer->fullImagePath;
const QString fileName = QFileInfo(fullPath).fileName();
if (Settings::deleteConfirm) {
MessageBox msgBox(imageViewer, MessageBox::Yes|MessageBox::Cancel, MessageBox::Yes);
QString ttl = trash ? tr("Move to Trash") : tr("Delete images");
QString msg = trash ? tr("Move %1 to the trash").arg(fileName) : tr("Permanently delete %1").arg(fileName);
if (msgBox.warning(ttl, msg) != MessageBox::Yes) {
if (isFullScreen())
imageViewer->setCursorHiding(true);
return;
}
}
QString trashError;
if (trash ? QFile::moveToTrash(fullPath) : QFile::remove(fullPath)) {
m_deleteInProgress = true;
int currentRow = thumbsViewer->currentIndex().row();
loadImage(Phototonic::Next);
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); // process index changed, it's a queued connection
thumbsViewer->model()->removeRow(currentRow);
imageViewer->setFeedback(tr("Deleted %1").arg(fileName));
m_deleteInProgress = false;
} else {
MessageBox(imageViewer).critical(tr("Error"), tr("Failed to delete image"));
}
Metadata::forget(fullPath);
ThumbsViewer::removeFromCache(fullPath);
if (isFullScreen())
imageViewer->setCursorHiding(true);
}
// Main delete operation
void Phototonic::deleteOperation() {
if (QApplication::focusWidget() == bookmarks) {
bookmarks->removeBookmark();
return;
}
if (QApplication::focusWidget() == fileSystemTree) {
deleteDirectory(true);
return;
}
if (!thumbsViewer->isVisible() ||
(imagePreviewDock->isFloating() && QApplication::focusWidget() == imageViewer)) {
deleteFromViewer(true);
return;
}
deleteImages(true);
}
void Phototonic::deletePermanentlyOperation() {
if (QApplication::focusWidget() == fileSystemTree) {
deleteDirectory(false);
return;
}
if (!thumbsViewer->isVisible() ||
(imagePreviewDock->isFloating() && QApplication::focusWidget() == imageViewer)) {
deleteFromViewer(false);
return;
}
deleteImages(false);
}
void Phototonic::goTo(QString path) {
m_includeSubDirsAction->setChecked(false);
m_findDupesAction->setChecked(false);
setFileListMode(path == "Phototonic::FileList");
if (!Settings::isFileListLoaded) {
Settings::currentDirectory = path;
fileSystemTree->setCurrentIndex(fileSystemModel->index(path));
selectCurrentViewDir();
}
refreshThumbs(true);
}
void Phototonic::goPathBarDir() {
if (pathLineEdit->completer()->popup())
pathLineEdit->completer()->popup()->hide();
QMap::const_iterator it = Settings::bangs.constFind(pathLineEdit->text().section(':', 0, 0));
if (it != Settings::bangs.constEnd()) {
QString command = it.value();
command.replace("%s", pathLineEdit->text().section(':', 1));
QProcess *job = new QProcess(this);
connect(job, &QProcess::readyReadStandardOutput, this, [_LCD_]() {
QByteArray ba = job->readAllStandardOutput();
QStringList list = QString::fromLocal8Bit(ba).split('\n');
loadStartupFileList(list, 0);
thumbsViewer->reload(true);
});
connect(job, &QProcess::finished, job, &QObject::deleteLater);
Settings::filesList.clear();
setFileListMode(true);
reload();
job->startCommand(command);
return;
}
if (!isReadableDir(pathLineEdit->text())) {
MessageBox(this).critical(tr("Error"), tr("Invalid Path: %1").arg(pathLineEdit->text()));
pathLineEdit->setText(Settings::currentDirectory);
return;
}
thumbsViewer->setFocus(Qt::OtherFocusReason);
goTo(pathLineEdit->text());
}
void Phototonic::updateActions() {
auto toggleFileSpecificActions = [&](bool on) {
m_cutAction->setEnabled(on);
m_copyAction->setEnabled(on);
m_copyToAction->setEnabled(on);
m_moveToAction->setEnabled(on);
m_viewImageAction->setEnabled(on);
m_wallpaperAction->setEnabled(on);
m_openWithMenuAction->setEnabled(on);
// batchSubMenuAction->setEnabled(on);
m_batchTransformAction->setEnabled(on);
m_deleteAction->setEnabled(on);
m_trashAction->setEnabled(on);
};
if (QApplication::focusWidget() == thumbsViewer) {
toggleFileSpecificActions(thumbsViewer->selectionModel()->selectedIndexes().size() > 0);
m_batchTransformAction->setEnabled(thumbsViewer->selectionModel()->selectedIndexes().size() > 1);
} else if (QApplication::focusWidget() == bookmarks) {
toggleFileSpecificActions(false);
} else if (QApplication::focusWidget() == fileSystemTree) {
toggleFileSpecificActions(false);
m_deleteAction->setEnabled(true); // also used for the filesystem tree
m_trashAction->setEnabled(true);
} else {
toggleFileSpecificActions(!focusIsOnBrowsing());
}
if (m_centralLayout->currentWidget() == imageViewer && !focusIsOnBrowsing()) {
setViewerKeyEventsEnabled(true);
m_fullScreenAction->setEnabled(true);
m_closeImageAction->setEnabled(true);
m_imageInfoAction->setShortcuts(QList() << m_imageInfoAction->shortcut() << Qt::Key_I);
m_showGridAction->setShortcuts(QList() << m_showGridAction->shortcut() << Qt::Key_G);
} else {
if (QApplication::focusWidget() == imageViewer) {
setViewerKeyEventsEnabled(true);
m_imageInfoAction->setShortcuts(QList() << m_imageInfoAction->shortcut() << Qt::Key_I);
m_showGridAction->setShortcuts(QList() << m_showGridAction->shortcut() << Qt::Key_G);
m_fullScreenAction->setEnabled(imagePreviewDock->isFloating());
m_closeImageAction->setEnabled(false);
} else {
m_imageInfoAction->setShortcuts(QList() << m_imageInfoAction->shortcut());
m_showGridAction->setShortcuts(QList() << m_showGridAction->shortcut());
setViewerKeyEventsEnabled(false);
m_fullScreenAction->setEnabled(false);
m_closeImageAction->setEnabled(false);
}
}
}
void Phototonic::writeSettings() {
if (!initComplete)
return;
if (!m_presentationMode) {
// withdraw the max/fullscreen states - Qt sucks at tracking them
// the (then to be restored size) more or less encodes the state and we rely on the WM
// to make the best out of what will look like a clumsy maximization attempt *shrug*
setWindowState(windowState() & ~(Qt::WindowMaximized|Qt::WindowFullScreen));
Settings::setValue(Settings::optionGeometry, saveGeometry());
Settings::setValue(Settings::optionWindowState, saveState());
}
Settings::setValue(Settings::optionThumbsSortFlags, (int) thumbsViewer->thumbsSortFlags);
Settings::setValue(Settings::optionThumbsZoomLevel, thumbsViewer->thumbSize);
Settings::setValue(Settings::optionFullScreenMode, (bool) Settings::isFullScreen);
Settings::setValue(Settings::optionViewerBackgroundColor, Settings::viewerBackgroundColor);
Settings::setValue(Settings::optionThumbsBackgroundColor, Settings::thumbsBackgroundColor);
Settings::setValue(Settings::optionThumbsTextColor, Settings::thumbsTextColor);
Settings::setValue(Settings::optionThumbsPagesReadCount, (int) Settings::thumbsPagesReadCount);
Settings::setValue(Settings::optionThumbsLayout, (int) Settings::thumbsLayout);
Settings::setValue(Settings::optionEnableAnimations, (bool) Settings::enableAnimations);
Settings::setValue(Settings::optionExifRotationEnabled, (bool) Settings::exifRotationEnabled);
Settings::setValue(Settings::optionExifThumbRotationEnabled,
(bool) Settings::exifThumbRotationEnabled);
Settings::setValue(Settings::optionReverseMouseBehavior, (bool) Settings::reverseMouseBehavior);
Settings::setValue(Settings::optionScrollZooms, (bool) Settings::scrollZooms);
Settings::setValue(Settings::optionDeleteConfirm, (bool) Settings::deleteConfirm);
Settings::setValue(Settings::optionShowHiddenFiles, (bool) Settings::showHiddenFiles);
Settings::setValue(Settings::optionWrapImageList, (bool) Settings::wrapImageList);
Settings::setValue(Settings::optionDefaultSaveQuality, Settings::defaultSaveQuality);
Settings::setValue(Settings::optionSlideShowDelay, Settings::slideShowDelay);
Settings::setValue(Settings::optionSlideShowRandom, (bool) Settings::slideShowRandom);
Settings::setValue(Settings::optionSlideShowCrossfade, (bool) Settings::slideShowCrossfade);
Settings::setValue(Settings::optionFileSystemDockVisible, (bool) Settings::fileSystemDockVisible);
Settings::setValue(Settings::optionImageInfoDockVisible, (bool) Settings::imageInfoDockVisible);
Settings::setValue(Settings::optionBookmarksDockVisible, (bool) Settings::bookmarksDockVisible);
Settings::setValue(Settings::optionTagsDockVisible, (bool) Settings::tagsDockVisible);
Settings::setValue(Settings::optionImagePreviewDockVisible, (bool) Settings::imagePreviewDockVisible);
Settings::setValue(Settings::optionThumbViewDockVisible, (bool) Settings::thumbViewDockVisible);
Settings::setValue(Settings::optionStartupDir, (int) Settings::startupDir);
Settings::setValue(Settings::optionSpecifiedStartDir, Settings::specifiedStartDir);
Settings::setValue(Settings::optionThumbsBackgroundImage, Settings::thumbsBackgroundImage);
Settings::setValue(Settings::optionLastDir,
Settings::startupDir == Settings::RememberLastDir ? Settings::currentDirectory
: "");
Settings::setValue(Settings::optionShowImageName, (bool) Settings::showImageName);
Settings::setValue(Settings::optionSmallToolbarIcons, (bool) Settings::smallToolbarIcons);
Settings::setValue(Settings::optionHideDockTitlebars, (bool) Settings::hideDockTitlebars);
Settings::setValue(Settings::optionShowViewerToolbar, (bool) Settings::showViewerToolbar);
Settings::setValue(Settings::optionSetWindowIcon, (bool) Settings::setWindowIcon);
Settings::setValue(Settings::optionUpscalePreview, (bool) Settings::upscalePreview);
Settings::setValue("DuplicateHistogramProximity", (int) Settings::dupeAccuracy);
Settings::setValue("ImageToolActions", Settings::imageToolActions);
Settings::setValue("AlwaysUseExifThumb", Settings::alwaysUseExifThumb);
/* Action shortcuts */
Settings::beginGroup(Settings::optionShortcuts);
QMapIterator shortcutsIterator(Settings::actionKeys);
while (shortcutsIterator.hasNext()) {
shortcutsIterator.next();
Settings::appSettings->setValue(shortcutsIterator.key(), shortcutsIterator.value()->shortcut().toString());
}
Settings::appSettings->endGroup();
Settings::setValue(Settings::optionWallpaperCommand, Settings::wallpaperCommand);
/* External apps */
Settings::beginGroup(Settings::optionExternalApps);
Settings::appSettings->remove("");
QMapIterator eaIter(Settings::externalApps);
while (eaIter.hasNext()) {
eaIter.next();
Settings::appSettings->setValue(eaIter.key(), eaIter.value());
}
Settings::appSettings->endGroup();
Settings::beginGroup(Settings::optionBangs);
Settings::appSettings->remove("");
QMapIterator bIter(Settings::bangs);
while (bIter.hasNext()) {
bIter.next();
Settings::appSettings->setValue(bIter.key(), bIter.value());
}
Settings::appSettings->endGroup();
/* save bookmarks */
int idx = 0;
Settings::beginGroup(Settings::optionCopyMoveToPaths);
Settings::appSettings->remove("");
QSetIterator pathsIter(Settings::bookmarkPaths);
while (pathsIter.hasNext()) {
Settings::appSettings->setValue("path" + QString::number(++idx), pathsIter.next());
}
Settings::appSettings->endGroup();
/* save known Tags */
idx = 0;
Settings::beginGroup(Settings::optionKnownTags);
Settings::appSettings->remove("");
QSetIterator tagsIter(Settings::knownTags);
while (tagsIter.hasNext()) {
Settings::appSettings->setValue("tag" + QString::number(++idx), tagsIter.next());
}
Settings::appSettings->endGroup();
/* save exif filters */
Settings::beginGroup(Settings::optionExifFilters);
Settings::appSettings->remove("");
QMapIterator efIter(Settings::exifFilters);
while (efIter.hasNext()) {
efIter.next();
Settings::appSettings->setValue(efIter.key(), efIter.value());
}
Settings::appSettings->endGroup();
}
void Phototonic::readSettings() {
initComplete = false;
needThumbsRefresh = false;
Settings::viewerBackgroundColor = Settings::value(Settings::optionViewerBackgroundColor, QColor(39,39,39)).value();
Settings::enableAnimations = Settings::value(Settings::optionEnableAnimations, true).toBool();
Settings::exifRotationEnabled = Settings::value(Settings::optionExifRotationEnabled, true).toBool();
Settings::exifThumbRotationEnabled = Settings::value(Settings::optionExifThumbRotationEnabled, true).toBool();
Settings::thumbsLayout = Settings::value(Settings::optionThumbsLayout, ThumbsViewer::Classic).toInt();
Settings::reverseMouseBehavior = Settings::value(Settings::optionReverseMouseBehavior, false).toBool();
Settings::scrollZooms = Settings::value(Settings::optionScrollZooms, false).toBool();
Settings::deleteConfirm = Settings::value(Settings::optionDeleteConfirm, true).toBool();
Settings::showHiddenFiles = Settings::value(Settings::optionShowHiddenFiles, false).toBool();
Settings::wrapImageList = Settings::value(Settings::optionWrapImageList, false).toBool();
Settings::defaultSaveQuality = Settings::value(Settings::optionDefaultSaveQuality, 90).toInt();
Settings::slideShowDelay = Settings::value(Settings::optionSlideShowDelay, 5.0).toDouble();
Settings::slideShowRandom = Settings::value(Settings::optionSlideShowRandom, false).toBool();
Settings::slideShowCrossfade = Settings::value(Settings::optionSlideShowCrossfade, true).toBool();
Settings::showImageName = Settings::value(Settings::optionShowImageName, false).toBool();
Settings::smallToolbarIcons = Settings::value(Settings::optionSmallToolbarIcons, true).toBool();
Settings::hideDockTitlebars = Settings::value(Settings::optionHideDockTitlebars, false).toBool();
Settings::showViewerToolbar = Settings::value(Settings::optionShowViewerToolbar, false).toBool();
Settings::setWindowIcon = Settings::value(Settings::optionSetWindowIcon, false).toBool();
Settings::upscalePreview = Settings::value(Settings::optionUpscalePreview, false).toBool();
Settings::dupeAccuracy = Settings::value("DuplicateHistogramProximity", 60).toInt();
Settings::imageToolActions = Settings::value("ImageToolActions", SettingsDialog::defaultImageToolActions()).toStringList();
Settings::alwaysUseExifThumb = Settings::value("AlwaysUseExifThumb", false).toBool();
// meehh
Settings::fileSystemDockVisible = Settings::value(Settings::optionFileSystemDockVisible, true).toBool();
Settings::bookmarksDockVisible = Settings::value(Settings::optionBookmarksDockVisible, true).toBool();
Settings::tagsDockVisible = Settings::value(Settings::optionTagsDockVisible, true).toBool();
Settings::imagePreviewDockVisible = Settings::value(Settings::optionImagePreviewDockVisible, true).toBool();
Settings::thumbViewDockVisible = Settings::value(Settings::optionThumbViewDockVisible, true).toBool();
Settings::imageInfoDockVisible = Settings::value(Settings::optionImageInfoDockVisible, true).toBool();
Settings::startupDir = (Settings::StartupDir) Settings::value(Settings::optionStartupDir, Settings::RememberLastDir).toInt();
Settings::specifiedStartDir = Settings::value(Settings::optionSpecifiedStartDir, QString()).toString();
Settings::thumbsBackgroundImage = Settings::value(Settings::optionThumbsBackgroundImage, QString()).toString();
Settings::wallpaperCommand = Settings::value(Settings::optionWallpaperCommand, QString()).toString();
/* read external apps */
Settings::beginGroup(Settings::optionExternalApps);
QStringList extApps = Settings::appSettings->childKeys();
for (int i = 0; i < extApps.size(); ++i) {
Settings::externalApps[extApps.at(i)] = Settings::appSettings->value(extApps.at(i)).toString();
}
Settings::appSettings->endGroup();
Settings::beginGroup(Settings::optionBangs);
QStringList bangs = Settings::appSettings->childKeys();
for (int i = 0; i < bangs.size(); ++i) {
Settings::bangs[bangs.at(i)] = Settings::appSettings->value(bangs.at(i)).toString();
}
Settings::appSettings->endGroup();
/* read bookmarks */
Settings::beginGroup(Settings::optionCopyMoveToPaths);
QStringList paths = Settings::appSettings->childKeys();
if (paths.isEmpty()) {
Settings::bookmarkPaths.insert(QDir::homePath());
const QString picturesLocation = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
if (!picturesLocation.isEmpty()) {
Settings::bookmarkPaths.insert(picturesLocation);
}
} else {
for (int i = 0; i < paths.size(); ++i) {
Settings::bookmarkPaths.insert(Settings::appSettings->value(paths.at(i)).toString());
}
}
Settings::appSettings->endGroup();
/* read known tags */
Settings::beginGroup(Settings::optionKnownTags);
QStringList tags = Settings::appSettings->childKeys();
for (int i = 0; i < tags.size(); ++i) {
Settings::knownTags.insert(Settings::appSettings->value(tags.at(i)).toString());
}
Settings::appSettings->endGroup();
/* read exif filters */
Settings::beginGroup(Settings::optionExifFilters);
QStringList eFilters = Settings::appSettings->childKeys();
for (int i = 0; i < eFilters.size(); ++i) {
Settings::exifFilters[eFilters.at(i)] = Settings::appSettings->value(eFilters.at(i)).toString();
}
Settings::appSettings->endGroup();
Settings::isFileListLoaded = false;
}
void Phototonic::setupDocks() {
addDockWidget(Qt::RightDockWidgetArea, imageInfoDock);
addDockWidget(Qt::RightDockWidgetArea, tagsDock);
lockDocks();
}
void Phototonic::lockDocks() {
if (initComplete) {
Settings::hideDockTitlebars = action("lockDocks", true)->isChecked();
}
delete fileSystemDock->titleBarWidget();
delete bookmarksDock->titleBarWidget();
delete imagePreviewDock->titleBarWidget();
delete tagsDock->titleBarWidget();
delete imageInfoDock->titleBarWidget();
delete m_thumbViewDock->titleBarWidget();
if (Settings::hideDockTitlebars) {
fileSystemDock->setTitleBarWidget(new QWidget(fileSystemDock));
bookmarksDock->setTitleBarWidget(new QWidget(bookmarksDock));
imagePreviewDock->setTitleBarWidget(new QWidget(imagePreviewDock));
tagsDock->setTitleBarWidget(new QWidget(tagsDock));
imageInfoDock->setTitleBarWidget(new QWidget(imageInfoDock));
m_thumbViewDock->setTitleBarWidget(new QWidget(m_thumbViewDock));
} else {
fileSystemDock->setTitleBarWidget(nullptr);
bookmarksDock->setTitleBarWidget(nullptr);
imagePreviewDock->setTitleBarWidget(nullptr);
tagsDock->setTitleBarWidget(nullptr);
imageInfoDock->setTitleBarWidget(nullptr);
m_thumbViewDock->setTitleBarWidget(nullptr);
}
}
QMenu *Phototonic::createPopupMenu() {
QMenu *extraActsMenu = QMainWindow::createPopupMenu();
if (myMainToolBar)
extraActsMenu->removeAction(myMainToolBar->toggleViewAction());
extraActsMenu->addSeparator();
extraActsMenu->addAction(action("smallToolbarIcons"));
extraActsMenu->addAction(action("lockDocks"));
return extraActsMenu;
}
void Phototonic::loadShortcuts() {
Settings::beginGroup(Settings::optionShortcuts);
QStringList shortcuts = Settings::appSettings->childKeys();
QList actionlist = findChildren(Qt::FindDirectChildrenOnly);
QStringList objectNames; // sanity check only
for (QAction *action : actionlist) {
const QString name = action->objectName();
if (!name.isEmpty()) {
objectNames << name;
Settings::actionKeys[name] = action;
// qDebug() << name << action->property("sc_default");
action->setShortcut(Settings::appSettings->value(name, action->property("sc_default")).toString());
}
}
// objectNames.sort();
// qDebug() << objectNames;
if (objectNames.removeDuplicates()) // sanity check
qWarning() << "DUPLICATE OBJECT NAME FOUND - THIS IS A BUG";
Settings::appSettings->endGroup();
}
void Phototonic::closeEvent(QCloseEvent *event) {
thumbsViewer->abort(true);
writeSettings();
hide();
QClipboard *clip = QApplication::clipboard();
if (clip->ownsClipboard() && !clip->image().isNull()) {
clip->clear();
}
event->accept();
}
void Phototonic::setStatus(QString state) {
if (m_presentationMode) {
return; // use feedback still?
}
m_statusLabel->setText(state);
m_statusLabel->adjustSize();
m_statusLabel->move(16, height() - (m_statusLabel->height() + 10));
m_statusLabel->raise();
m_statusLabel->show();
static QTimer *statusTimer = nullptr;
if (!statusTimer) {
statusTimer = new QTimer(this);
statusTimer->setSingleShot(true);
statusTimer->setInterval(3000);
connect(statusTimer, &QTimer::timeout, m_statusLabel, &QWidget::hide);
}
statusTimer->start();
}
void Phototonic::newImage() {
if (focusIsOnBrowsing()) {
showViewer();
}
imageViewer->loadImage("");
}
void Phototonic::setDocksVisibility(bool visible) {
layout()->setEnabled(false);
auto vis = [_LCD_](QDockWidget *d) { return visible || d->isFloating(); };
fileSystemDock->setVisible(vis(fileSystemDock) && Settings::fileSystemDockVisible);
bookmarksDock->setVisible(vis(bookmarksDock) && Settings::bookmarksDockVisible);
imagePreviewDock->setVisible(vis(imagePreviewDock) && Settings::imagePreviewDockVisible);
m_thumbViewDock->setVisible(vis(m_thumbViewDock) && Settings::thumbViewDockVisible);
tagsDock->setVisible(vis(tagsDock) && Settings::tagsDockVisible);
imageInfoDock->setVisible(vis(imageInfoDock) && Settings::imageInfoDockVisible);
myMainToolBar->setVisible(visible);
setContextMenuPolicy(Qt::PreventContextMenu);
layout()->setEnabled(true);
}
void Phototonic::viewImage() {
if (m_presentationMode) {
hideViewer();
return;
}
if (QApplication::focusWidget() == fileSystemTree) {
goTo(getSelectedPath());
return;
} else if (QApplication::focusWidget() == thumbsViewer || QApplication::focusWidget() == imageViewer) {
QModelIndex selectedImageIndex;
QModelIndexList selectedIndexes = thumbsViewer->selectionModel()->selectedIndexes();
if (selectedIndexes.size() > 0) {
selectedImageIndex = selectedIndexes.first();
} else {
if (thumbsViewer->model()->rowCount() == 0) {
setStatus(tr("No images"));
return;
}
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
selectedImageIndex = thumbModel->indexFromItem(thumbModel->item(0));
thumbsViewer->selectionModel()->select(selectedImageIndex, QItemSelectionModel::Toggle);
thumbsViewer->setCurrentIndex(0);
}
loadSelectedThumbImage(selectedImageIndex);
return;
} else if (QApplication::focusWidget() == filterLineEdit) {
QString error;
if (!thumbsViewer->setFilter(filterLineEdit->text(), &error))
QToolTip::showText(filterLineEdit->mapToGlobal(QPoint(0, filterLineEdit->height())),
error, filterLineEdit);
return;
} else if (QApplication::focusWidget() == pathLineEdit) {
goPathBarDir();
return;
}
}
void Phototonic::showViewer() {
if (imagePreviewDock->isFloating() && imagePreviewDock->isVisible()) {
if (Settings::isFullScreen) {
imagePreviewDock->setWindowState(imagePreviewDock->windowState() | Qt::WindowFullScreen);
imageViewer->setCursorHiding(true);
}
imagePreviewDock->raise();
return;
}
if (!m_presentationMode) {
m_presentationMode = true;
// Settings::setValue("Geometry", saveGeometry());
// Settings::setValue("WindowState", saveState());
thumbsViewer->setResizeEnabled(false);
m_centralLayout->addWidget(imageViewer);
m_centralLayout->setCurrentWidget(imageViewer);
setDocksVisibility(false);
m_statusLabel->hide();
if (Settings::isFullScreen) {
setWindowState(windowState() | Qt::WindowFullScreen);
imageViewer->setCursorHiding(true);
}
imageViewer->setFocus(Qt::OtherFocusReason);
setImageViewerWindowTitle();
QApplication::processEvents(); /// @todo why?
if (m_imageToolBar->isVisible())
positionImageToolbar();
}
}
/// @todo looks like redundant calls?
void Phototonic::loadSelectedThumbImage(const QModelIndex &idx) {
if (!imageViewer->batchMode)
showViewer();
thumbsViewer->setCurrentIndex(idx);
const QString imagePath = thumbsViewer->fullPathOf(idx.row());
if (m_imageInfoAction->isChecked()) {
m_infoViewer->read(imagePath);
imageViewer->setFeedback(m_infoViewer->html(), false);
}
imageViewer->loadImage(imagePath, thumbsViewer->icon(idx.row()).pixmap(THUMB_SIZE_MAX).toImage());
setImageViewerWindowTitle();
}
void Phototonic::setSlideShow(bool active) {
if (m_slideShowActive == active)
return; // idempotent
QAction *toggle = action("toggleSlideShow", true);
m_slideShowActive = active;
if (!m_slideShowActive) {
imageViewer->setCrossfade(false);
slideShowHandler(); // reset
toggle->setText(tr("Slide Show"));
imageViewer->setFeedback(tr("Slide show stopped"));
SlideShowTimer->stop();
SlideShowTimer->deleteLater();
toggle->setIcon(QIcon::fromTheme("media-playback-start", QIcon(":/images/media-playback-start.png")));
} else {
if (thumbsViewer->model()->rowCount() <= 0) {
m_slideShowActive = false;
return;
}
if (!m_presentationMode) {
QModelIndexList selection = thumbsViewer->selectionModel()->selectedIndexes();
if (selection.size() < 2) {
loadImage(Phototonic::First);
} else {
thumbsViewer->selectionModel()->setCurrentIndex(selection.first(), QItemSelectionModel::NoUpdate);
// thumbsViewer->setCurrentIndex(selection.first());
}
showViewer();
}
slideShowHandler(); // init/preload
SlideShowTimer = new QTimer(this);
const int ssTimeout = Settings::slideShowDelay * 1000.0;
connect(SlideShowTimer, SIGNAL(timeout()), this, SLOT(slideShowHandler()));
SlideShowTimer->start(ssTimeout);
toggle->setText(tr("Stop Slide Show"));
imageViewer->setFeedback(tr("Slide show started"));
toggle->setIcon(QIcon::fromTheme("media-playback-stop", QIcon(":/images/media-playback-stop.png")));
const int currentRow = thumbsViewer->currentIndex().row();
imageViewer->loadImage(thumbsViewer->fullPathOf(currentRow),
thumbsViewer->icon(currentRow).pixmap(THUMB_SIZE_MAX).toImage());
imageViewer->setCrossfade(Settings::slideShowCrossfade && ssTimeout >= 1000);
}
}
void Phototonic::slideShowHandler() {
static int next = -1;
static int last = -1;
if (!m_slideShowActive) {
next = -1;
last = -1;
imageViewer->preload("");
return;
}
if (next < -1) {
setSlideShow(false);
return;
}
QModelIndexList selection = thumbsViewer->selectionModel()->selectedIndexes();
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
if (next > -1 && next < thumbModel->rowCount() && last == thumbsViewer->currentIndex().row()) {
thumbsViewer->setCurrentIndex(next, false);
#if 0 // poor man's ken burns - disabled for now
if (imageViewer->crossfade() && !action("keepZoom")->isChecked())
QTimer::singleShot(300, this, [this]() {imageViewer->zoomTo(ImageViewer::ZoomToFill, QPoint(-1,-1), Settings::slideShowDelay * 1000.0 - 500);});
#endif
}
last = thumbsViewer->currentIndex().row();
if (selection.size() > 1) { // use only selected images
if (Settings::slideShowRandom) {
next = QRandomGenerator::global()->bounded(selection.size());
next = selection.at(next).row();
} else {
next = -1;
for (int i = 0; i < selection.size(); ++i) {
if (selection.at(i).row() == last) {
if (i < selection.size() - 1)
next = selection.at(i+1).row();
else if (Settings::wrapImageList)
next = selection.at(0).row();
break;
}
}
}
} else { // use all visible images
if (Settings::slideShowRandom) {
next = QRandomGenerator::global()->bounded(thumbsViewer->visibleThumbs());
if (thumbsViewer->visibleThumbs() != thumbsViewer->model()->rowCount()) {
// for the filtered case we've to figure the n-th non-hidden thumb, naively picking some
// number and moving to the next visible will cause less than random results if a huge
// block is hidden because we'll often end at its adjacent indexes
int n = next;
for (next = 0; next < thumbsViewer->model()->rowCount(); ++next) {
if (!thumbsViewer->isRowHidden(next) && --n < 0)
break;
}
}
} else {
next = thumbsViewer->nextRow();
if (next < 0 && Settings::wrapImageList) {
next = 0;
while (next < thumbsViewer->model()->rowCount() && thumbsViewer->isRowHidden(next))
++next;
if (next >= thumbsViewer->model()->rowCount())
next = -1;
}
}
}
if (next < 0)
next = Settings::wrapImageList ? -1 : -2;
if (next > -1 && next < thumbsViewer->model()->rowCount())
connect (imageViewer, &ImageViewer::imageLoaded, this, [this]() { imageViewer->preload(thumbsViewer->fullPathOf(next));}, Qt::SingleShotConnection);
}
void Phototonic::loadImage(SpecialImageIndex idx) {
if (thumbsViewer->model()->rowCount() <= 0) {
return;
}
int thumb;
switch (idx) {
case Phototonic::First:
thumb = 0;
while (thumb < thumbsViewer->model()->rowCount() && thumbsViewer->isRowHidden(thumb))
++thumb;
if (thumb >= thumbsViewer->model()->rowCount())
thumb = -1;
break;
case Phototonic::Next:
thumb = thumbsViewer->nextRow();
if (thumb < 0 && Settings::wrapImageList)
thumb = 0;
break;
case Phototonic::Previous:
thumb = thumbsViewer->previousRow();
if (thumb < 0 && Settings::wrapImageList)
thumb = thumbsViewer->model()->rowCount() - 1;
break;
case Phototonic::Last:
thumb = thumbsViewer->model()->rowCount() - 1;
while (thumb > -1 && thumbsViewer->isRowHidden(thumb))
--thumb;
break;
case Phototonic::Random:
thumb = QRandomGenerator::global()->bounded(thumbsViewer->model()->rowCount());
break;
default:
qDebug() << "bogus special index" << idx;
return;
}
if (thumb < 0)
return;
// if (imageViewer->isVisible())
// imageViewer->loadImage(thumbsViewer->fullPathOf(thumb), thumbsViewer->icon(thumb).pixmap(THUMB_SIZE_MAX).toImage());
thumbsViewer->setCurrentIndex(thumb, !m_slideShowActive);
}
void Phototonic::setViewerKeyEventsEnabled(bool enabled) {
m_nextImageAction->setEnabled(enabled);
m_prevImageAction->setEnabled(enabled);
m_moveLeftAction->setEnabled(enabled);
m_moveRightAction->setEnabled(enabled);
m_moveUpAction->setEnabled(enabled);
m_moveDownAction->setEnabled(enabled);
}
void Phototonic::hideViewer() {
if (imagePreviewDock->isFloating()) {
imagePreviewDock->setWindowState(imagePreviewDock->windowState() & ~Qt::WindowFullScreen);
}
if (!Settings::imagePreviewDockVisible)
imageViewer->secureEdits();
setWindowState(windowState() & ~Qt::WindowFullScreen);
imageViewer->setCursorHiding(false);
// restoreGeometry(Settings::value(Settings::optionGeometry).toByteArray());
// restoreState(Settings::value(Settings::optionWindowState).toByteArray());
m_presentationMode = false;
m_centralLayout->setCurrentWidget(thumbsViewer);
setDocksVisibility(true);
thumbsViewer->setResizeEnabled(true);
while (QApplication::overrideCursor()) {
QApplication::restoreOverrideCursor();
}
setSlideShow(false);
setThumbsViewerWindowTitle();
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
if (needThumbsRefresh) {
needThumbsRefresh = false;
thumbsViewer->refreshThumbs();
} else {
if (thumbsViewer->model()->rowCount() > 0) {
thumbsViewer->setCurrentIndex(imageViewer->fullImagePath, false);
}
thumbsViewer->scrollTo(thumbsViewer->currentIndex());
thumbsViewer->loadVisibleThumbs();
}
if (!imageViewer->isVisible())
imageViewer->clearImage();
thumbsViewer->setFocus(Qt::OtherFocusReason);
setContextMenuPolicy(Qt::DefaultContextMenu);
}
void Phototonic::dropOp(Qt::KeyboardModifiers keyMods, bool dirOp, QString copyMoveDirPath) {
QApplication::restoreOverrideCursor();
Settings::isCopyOperation = (keyMods == Qt::ControlModifier);
QString destDir;
if (QObject::sender() == fileSystemTree) {
destDir = getSelectedPath();
} else if (QObject::sender() == bookmarks) {
if (bookmarks->currentItem()) {
destDir = bookmarks->currentItem()->toolTip(0);
} else {
addBookmark(copyMoveDirPath);
return;
}
} else {
// Unknown sender
return;
}
if (!isWritableDir(destDir)) {
MessageBox(this).critical(tr("Error"), tr("Can not move or copy images to this directory."));
return selectCurrentViewDir();
}
if (destDir == (dirOp ? QFileInfo(copyMoveDirPath).absolutePath() : Settings::currentDirectory)) {
return MessageBox(this).critical(tr("Error"), tr("Destination directory is the same as the source directory."));
}
if (!Settings::isCopyOperation && (m_deleteInProgress || thumbsViewer->isBusy())) { // defer, don't alter while the thumbsviewer is loading stuff
QTimer::singleShot(100, this, [_LCD_](){dropOp(keyMods, dirOp, copyMoveDirPath);});
return;
}
if (dirOp) {
QString baseName = copyMoveDirPath.section(QDir::separator(), -1);
MessageBox msgBox(this, MessageBox::Yes|MessageBox::Cancel, MessageBox::Cancel);
msgBox.button(MessageBox::Yes)->setText(tr("Move Directory"));
if (msgBox.warning(tr("Move directory"), tr("Move directory %1 to %2?").arg(baseName).arg(destDir)) == MessageBox::Yes) {
QFile dir(copyMoveDirPath);
if (!dir.rename(destDir + QDir::separator() + baseName)) {
msgBox.critical(tr("Error"), tr("Failed to move directory."));
}
setStatus(tr("Directory moved"));
}
} else {
if (!Settings::isCopyOperation)
m_deleteInProgress = true;
Settings::copyCutIndexList = thumbsViewer->selectionModel()->selectedIndexes();
int latestRow = CopyOrMove::list(thumbsViewer, destDir, false, this);
if (!Settings::isCopyOperation) {
if (thumbsViewer->model()->rowCount()) {
thumbsViewer->setCurrentIndex(qMin(latestRow, thumbsViewer->model()->rowCount() - 1));
}
m_deleteInProgress = false;
}
QString state = Settings::isCopyOperation ? tr("Copied %n image(s)", "", Settings::copyCutIndexList.size())
: tr("Moved %n image(s)", "", Settings::copyCutIndexList.size());
setStatus(state);
}
thumbsViewer->loadVisibleThumbs();
}
void Phototonic::selectCurrentViewDir() {
QModelIndex idx = fileSystemModel->index(Settings::currentDirectory);
if (idx.isValid()) {
fileSystemTree->expand(idx);
fileSystemTree->setCurrentIndex(idx);
fileSystemTree->scrollTo(idx);
}
}
void Phototonic::checkDirState(const QModelIndex &, int, int) {
if (!initComplete) {
return;
}
thumbsViewer->abort();
if (!QDir().exists(Settings::currentDirectory)) {
Settings::currentDirectory.clear();
refreshThumbs(false);
}
}
void Phototonic::addPathHistoryRecord(QString dir) {
if (!needHistoryRecord) {
needHistoryRecord = true;
return;
}
if (pathHistoryList.size() && dir == pathHistoryList.at(currentHistoryIdx)) {
return;
}
pathHistoryList.insert(++currentHistoryIdx, dir);
// Need to clear irrelevant items from list
if (currentHistoryIdx != pathHistoryList.size() - 1) {
m_goFrwdAction->setEnabled(false);
for (int i = pathHistoryList.size() - 1; i > currentHistoryIdx; --i) {
pathHistoryList.removeAt(i);
}
}
}
void Phototonic::reloadThumbs() {
if (m_deleteInProgress || !initComplete || thumbsViewer->isBusy()) {
thumbsViewer->abort();
QTimer::singleShot(32, this, SLOT(reloadThumbs())); // rate control @30Hz
return;
}
m_reloadPending = false;
if (Settings::isFileListLoaded) {
addPathHistoryRecord("Phototonic::FileList");
} else {
if (Settings::currentDirectory.isEmpty()) {
Settings::currentDirectory = getSelectedPath();
if (Settings::currentDirectory.isEmpty()) {
return;
}
}
if (!isReadableDir(Settings::currentDirectory)) {
setStatus(tr("No directory selected"));
return MessageBox(this).critical(tr("Error"), tr("Failed to open directory %1").arg(Settings::currentDirectory));
}
m_infoViewer->clear();
if (Settings::setWindowIcon && !m_presentationMode) {
setWindowIcon(QApplication::windowIcon());
}
pathLineEdit->setText(Settings::currentDirectory);
addPathHistoryRecord(Settings::currentDirectory);
if (currentHistoryIdx > 0) {
m_goBackAction->setEnabled(true);
}
}
if (!m_presentationMode) {
setThumbsViewerWindowTitle();
}
m_imageTags->removeTransientTags();
if (m_findDupesAction->isChecked()) {
const bool actionEnabled[5] = { m_goBackAction->isEnabled(), m_goFrwdAction->isEnabled(),
m_goUpAction->isEnabled(), m_goHomeAction->isEnabled(), m_refreshAction->isEnabled() };
m_goBackAction->setEnabled(false);
m_goFrwdAction->setEnabled(false);
m_goUpAction->setEnabled(false);
m_goHomeAction->setEnabled(false);
m_refreshAction->setEnabled(false);
fileSystemTree->setEnabled(false);
m_pathLineEditAction->setVisible(false);
//: %v and %m are literal pattterns for QProgressBar (value and maximum)
m_progressBar->setFormat(tr("Searching duplicates: %v / %m"));
if (!m_progressBarAction->isVisible())
m_progressBar->reset();
m_progressBarAction->setVisible(true);
thumbsViewer->loadDuplicates();
m_progressBarAction->setVisible(false);
m_pathLineEditAction->setVisible(true);
fileSystemTree->setEnabled(true);
m_goBackAction->setEnabled(actionEnabled[0]);
m_goFrwdAction->setEnabled(actionEnabled[1]);
m_goUpAction->setEnabled(actionEnabled[2]);
m_goHomeAction->setEnabled(actionEnabled[3]);
m_refreshAction->setEnabled(actionEnabled[4]);
} else {
m_progressBarAction->setVisible(false);
m_pathLineEditAction->setVisible(true);
m_progressBar->reset();
thumbsViewer->reload();
}
sortThumbnails();
}
void Phototonic::setImageViewerWindowTitle() {
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
const int currentRow = thumbsViewer->currentIndex().row();
if (currentRow < 0) { // model is still loading, yay threads
setWindowTitle(QFileInfo(imageViewer->fullImagePath).fileName());
return;
}
QString title = thumbModel->item(currentRow)->data(Qt::DisplayRole).toString()
+ QString::fromLatin1(" - [ %1 / %2 ] - Phototonic").arg(currentRow + 1).arg(thumbModel->rowCount());
setWindowTitle(title);
}
void Phototonic::setThumbsViewerWindowTitle() {
if (m_findDupesAction->isChecked()) {
setWindowTitle(tr("Duplicate images in %1").arg(Settings::currentDirectory) + " - Phototonic");
} else if (Settings::isFileListLoaded) {
setWindowTitle(tr("Files List") + " - Phototonic");
} else {
setWindowTitle(Settings::currentDirectory + " - Phototonic");
}
}
void Phototonic::renameDir() {
QModelIndexList selectedDirs = fileSystemTree->selectionModel()->selectedRows();
QFileInfo dirInfo = QFileInfo(fileSystemModel->filePath(selectedDirs[0]));
bool renameOk;
QString title = tr("Rename %1").arg(dirInfo.completeBaseName());
QString newDirName = QInputDialog::getText(this, title,
tr("New name:"), QLineEdit::Normal, dirInfo.completeBaseName(),
&renameOk);
if (!renameOk) {
return selectCurrentViewDir();
}
if (newDirName.isEmpty()) {
MessageBox(this).critical(tr("Error"), tr("Invalid name entered."));
return selectCurrentViewDir();
}
QFile dir(dirInfo.absoluteFilePath());
QString newFullPathName = dirInfo.absolutePath() + QDir::separator() + newDirName;
renameOk = dir.rename(newFullPathName);
if (!renameOk) {
MessageBox(this).critical(tr("Error"), tr("Failed to rename directory."));
return selectCurrentViewDir();
}
if (Settings::currentDirectory == dirInfo.absoluteFilePath()) {
fileSystemTree->setCurrentIndex(fileSystemModel->index(newFullPathName));
} else {
selectCurrentViewDir();
}
}
void Phototonic::rename() {
if (QApplication::focusWidget() == fileSystemTree) {
renameDir();
return;
}
if (!focusIsOnBrowsing()) {
if (imageViewer->isNewImage()) {
showNewImageWarning();
return;
}
if (thumbsViewer->model()->rowCount() > 0) {
thumbsViewer->setCurrentIndex(imageViewer->fullImagePath);
}
}
QModelIndexList selection = thumbsViewer->selectionModel()->selectedIndexes();
if (selection.size() < 1) {
setStatus(tr("Invalid selection"));
return;
}
RenameDialog *renameDialog = new RenameDialog(this);
if (selection.size() == 1) {
QFile file(thumbsViewer->fullPathOf(selection.first().row()));
QFileInfo fileInfo(file);
renameDialog->setFileName(fileInfo.fileName());
}
setSlideShow(false);
imageViewer->setCursorHiding(false);
QString newNameOrPattern;
bool ack = renameDialog->exec();
if (ack)
newNameOrPattern = renameDialog->fileName();
renameDialog->deleteLater();
if (ack && newNameOrPattern.isEmpty()) {
ack = false;
MessageBox(this).critical(tr("Error"), tr("No name entered."));
}
if (!ack) {
if (isFullScreen())
imageViewer->setCursorHiding(true);
return;
}
QString failures;
QStringList sources, destinations;
QList rows;
for (QModelIndex idx : selection) {
sources << thumbsViewer->fullPathOf(idx.row());
rows << idx.row();
}
int index = 0;
bool needDualPass = false, needConflictResolution = false;
for (const QString &oldPath : sources) {
QFile file(oldPath);
QFileInfo fileInfo(file);
QString newPath, mdate, exifdate, size;
if (newNameOrPattern.contains("%date"))
mdate = fileInfo.lastModified().toString(Qt::ISODate);
if (newNameOrPattern.contains("%exifdate")) {
qint64 exifTime = Metadata::dateTimeOriginal(fileInfo.filePath());
if (!exifTime)
exifTime = fileInfo.birthTime().toSecsSinceEpoch();
exifdate = QDateTime::fromSecsSinceEpoch(exifTime).toString(Qt::ISODate);
}
if (newNameOrPattern.contains("%size")) {
QSize res = QImageReader(fileInfo.filePath()).size();
size = QString("%1x%2").arg(res.width()).arg(res.height());
}
while (true) {
QString newFileName = newNameOrPattern;
newFileName.replace("%index", QStringLiteral("%1").arg(++index, 1+log10(selection.size()), 10, QLatin1Char('0')));
newFileName.replace("%date", mdate);
newFileName.replace("%exifdate", exifdate);
newFileName.replace("%size", size);
if (sources.size() > 1)
newFileName.append("." + oldPath.section('.', -1));
newPath = fileInfo.absolutePath() + QDir::separator() + newFileName;
if (!QFileInfo::exists(newPath))
break;
// needs some conflict reolution
if (sources.contains(newPath)) {
needDualPass = true;
break;
} else if (newNameOrPattern.contains("%index")) {
needConflictResolution = true;
continue; // try again w/ increased index
} else { // cannot be resolved
return MessageBox(this).critical(tr("File collision!"), tr("Existing files collide with the rename."));
}
}
destinations << newPath;
}
if (destinations.removeDuplicates()) {
// ambiguous destination pattern provided. ABORT
return MessageBox(this).critical(tr("Error"), tr("Refusing ambigious rename pattern.\nMultiple files would get the same name."));
}
if (needConflictResolution && newNameOrPattern.contains("%index")) {
if (MessageBox(this, MessageBox::Yes|MessageBox::Cancel, MessageBox::Yes).ask(
tr("File collision!"), tr("Existing files collide with the rename.") + "\n" +
tr("Do you want to incorporate them (ie. skip their indexes)?")) == MessageBox::Cancel)
return;
}
if (needDualPass) {
// qDebug() << "dual pass rename";
for (int i = sources.size() - 1; i >=0 ; --i) {
if (QFile(sources.at(i)).rename(sources.at(i) + ".ptt_helper"))
sources[i].append(".ptt_helper");
else {
failures += QFileInfo(sources.at(i)).fileName() + " => " + QFileInfo(destinations.at(i)).fileName() + "\n";
sources.remove(i);
destinations.remove(i);
rows.remove(i);
}
}
}
for (int i = 0; i < destinations.size(); ++i) {
const QString oldPath = sources.at(i);
const QString newPath = destinations.at(i);
const QString newFileName = QFileInfo(newPath).fileName();
QFile file(oldPath);
QFileInfo fileInfo(file);
if (file.rename(newPath)) {
ThumbsViewer::moveCache(oldPath, newPath);
Metadata::rename(oldPath, newPath);
QStandardItemModel *thumbModel = static_cast(thumbsViewer->model());
const int row = rows.at(i);
thumbModel->item(row)->setData(newPath, thumbsViewer->FileNameRole);
thumbModel->item(row)->setData(newFileName, Qt::DisplayRole);
if (row == thumbsViewer->currentIndex().row()) {
imageViewer->setInfo(newFileName);
imageViewer->fullImagePath = newPath;
}
if (Settings::filesList.contains(fileInfo.absoluteFilePath())) {
Settings::filesList.replace(Settings::filesList.indexOf(fileInfo.absoluteFilePath()), newPath);
}
if (m_presentationMode) {
setImageViewerWindowTitle();
}
} else {
failures += fileInfo.fileName() + " => " + newFileName + "\n";
}
}
if (!failures.isEmpty()) {
MessageBox msgBox(this);
msgBox.setDetailedText(failures);
msgBox.critical(tr("Error"), tr("Failed to rename image."));
}
if (isFullScreen())
imageViewer->setCursorHiding(true);
}
void Phototonic::removeMetadata() {
QStringList fileList = thumbsViewer->selectedFiles();
if (fileList.isEmpty()) {
setStatus(tr("Invalid selection"));
return;
}
setSlideShow(false);
MessageBox msgBox(this, MessageBox::Yes|MessageBox::Cancel, MessageBox::Cancel);
msgBox.button(MessageBox::Yes)->setText(tr("Remove Metadata"));
if (msgBox.warning(tr("Remove Metadata"), tr("Permanently remove all Exif metadata from selected images?")) == MessageBox::Yes) {
for (int i = 0; i < fileList.size(); ++i) {
if (!Metadata::wipeFrom(fileList.at(i)))
msgBox.critical(tr("Error"), tr("Failed to remove Exif metadata."));
}
if (m_imageTags->currentDisplayMode == SelectionTagsDisplay)
m_imageTags->showSelectedImagesTags();
setStatus(tr("Metadata removed from selected images"));
}
}
void Phototonic::regenerateThumbnails() {
QModelIndexList selection = thumbsViewer->selectionModel()->selectedIndexes();
if (selection.isEmpty()) {
setStatus(tr("Invalid selection"));
return;
}
setSlideShow(false);
MessageBox msgBox(this, MessageBox::Yes|MessageBox::No|MessageBox::Cancel, MessageBox::Cancel);
msgBox.button(MessageBox::Yes)->setText(tr("Write Exif Thumbnail"));
int ret = msgBox.warning(tr("Regenerate Thumbnail"), tr("Do you also want to write the thumbnail to the images metadata?"));
if (ret == MessageBox::Cancel)
return;
const bool writeExif = ret == MessageBox::Yes;
for (QModelIndex idx : selection) {
thumbsViewer->regenerateThumb(idx.row(), writeExif);
}
}
void Phototonic::deleteDirectory(bool trash) {
bool removeDirectoryOk;
QModelIndexList selectedDirs = fileSystemTree->selectionModel()->selectedRows();
QString deletePath = fileSystemModel->filePath(selectedDirs[0]);
QModelIndex idxAbove = fileSystemTree->indexAbove(selectedDirs[0]);
QFileInfo dirInfo = QFileInfo(deletePath);
QString question = (trash ? tr("Move directory %1 to the trash?")
: tr("Permanently delete the directory %1 and all of its contents?")
).arg(dirInfo.completeBaseName());
MessageBox msgBox(this, MessageBox::Yes|MessageBox::Cancel, MessageBox::Cancel);
msgBox.button(MessageBox::Yes)->setText(trash ? tr("OK") : tr("Delete Directory"));
if (msgBox.warning(tr("Delete Directory"), question) == MessageBox::Yes) {
removeDirectoryOk = trash ? QFile::moveToTrash(deletePath) : removeDirectoryOperation(deletePath);
} else {
return selectCurrentViewDir();
}
if (!removeDirectoryOk) {
msgBox.critical(tr("Error"), trash ? tr("Failed to move directory to the trash.")
: tr("Failed to delete directory."));
return selectCurrentViewDir();
}
QString state = QString(tr("Removed \"%1\"").arg(deletePath));
setStatus(state);
if (Settings::currentDirectory == deletePath) {
if (idxAbove.isValid()) {
fileSystemTree->setCurrentIndex(idxAbove);
}
} else {
selectCurrentViewDir();
}
}
void Phototonic::createSubDirectory() {
QModelIndexList selectedDirs = fileSystemTree->selectionModel()->selectedRows();
QFileInfo dirInfo = QFileInfo(fileSystemModel->filePath(selectedDirs[0]));
bool ok;
QString newDirName = QInputDialog::getText(this, tr("New Sub directory"),
tr("New directory name:"), QLineEdit::Normal, "", &ok);
if (!ok) {
return selectCurrentViewDir();
}
if (newDirName.isEmpty()) {
MessageBox(this).critical(tr("Error"), tr("Invalid name entered."));
return selectCurrentViewDir();
}
QDir dir(dirInfo.absoluteFilePath());
ok = dir.mkdir(dirInfo.absoluteFilePath() + QDir::separator() + newDirName);
if (!ok) {
MessageBox(this).critical(tr("Error"), tr("Failed to create new directory."));
return selectCurrentViewDir();
}
setStatus(tr("Created %1").arg(newDirName));
fileSystemTree->expand(selectedDirs[0]);
}
void Phototonic::setSaveDirectory(QString path) {
Settings::saveDirectory = path.isEmpty() ?
QFileDialog::getExistingDirectory(this, tr("Directory to save images into:"),
QString(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks) :
path;
}
QString Phototonic::getSelectedPath() {
if (!fileSystemTree->selectionModel())
return Settings::currentDirectory; // if there's no filesystem tree, this means the open directory
QModelIndexList selectedDirs = fileSystemTree->selectionModel()->selectedRows();
if (selectedDirs.size() && selectedDirs[0].isValid()) {
QFileInfo dirInfo = QFileInfo(fileSystemModel->filePath(selectedDirs[0]));
return dirInfo.absoluteFilePath();
} else
return "";
}
void Phototonic::positionImageToolbar() {
const QSize s16(16,16);
if (m_imageToolBar->orientation() == Qt::Horizontal) {
// can we get this back to vertical?
if (m_imageToolBar->width() < imageViewer->height()) {
m_imageToolBar->setOrientation(Qt::Vertical); // yay
m_imageToolBar->adjustSize();
} else if (m_imageToolBar->iconSize() != s16 && 17*m_imageToolBar->width()/24 < imageViewer->height()) {
m_imageToolBar->setIconSize(s16);
m_imageToolBar->setOrientation(Qt::Vertical); // yay
m_imageToolBar->adjustSize();
}
}
int tl = m_imageToolBar->height();
int vl = imageViewer->height();
if (m_imageToolBar->orientation() == Qt::Horizontal) {
tl = m_imageToolBar->width();
vl = imageViewer->width();
}
if (tl > vl) {
// shrink
if (m_imageToolBar->iconSize() != s16) {
m_imageToolBar->setIconSize(s16);
m_imageToolBar->adjustSize();
}
if (m_imageToolBar->orientation() == Qt::Vertical &&
m_imageToolBar->height() > imageViewer->height() &&
imageViewer->width() > 4*imageViewer->height()/3) {
m_imageToolBar->setOrientation(Qt::Horizontal); // sacrifice position
m_imageToolBar->adjustSize();
}
} else if (m_imageToolBar->iconSize() == s16) {
// can we upscale this?
if (tl < 17*vl/24) {
m_imageToolBar->setIconSize(QSize(24,24));
m_imageToolBar->adjustSize();
}
}
if (m_imageToolBar->orientation() == Qt::Horizontal)
m_imageToolBar->move((imageViewer->width() - m_imageToolBar->width())/2,
imageViewer->height() - 2*m_imageToolBar->height());
else
m_imageToolBar->move(imageViewer->width() - 2*m_imageToolBar->width(),
(imageViewer->height() - m_imageToolBar->height())/2);
}
bool Phototonic::eventFilter(QObject *o, QEvent *e)
{
if (o == m_menuButton) {
if (e->type() == QEvent::Enter) {
m_statusLabel->move(16, height() - (m_statusLabel->height() + 10));
m_statusLabel->raise();
m_statusLabel->show();
}
else if (e->type() == QEvent::Leave) {
m_statusLabel->hide();
}
return QMainWindow::eventFilter(o, e);
}
if (o == filterLineEdit) {
if (e->type() == QEvent::Enter) {
filterLineEdit->setClearButtonEnabled(!filterLineEdit->text().isEmpty());
} else if (e->type() == QEvent::Leave) {
filterLineEdit->setClearButtonEnabled(false);
} else if (e->type() == QEvent::KeyPress) {
// since we filter it anyway, allow some thumb navigation w/ keys irrelevant to the lineedit
QKeyEvent *ke = static_cast(e);
if (ke->key() == Qt::Key_PageUp || ke->key() == Qt::Key_PageDown ||
ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) {
QApplication::sendEvent(thumbsViewer, e);
return true;
}
}
return QMainWindow::eventFilter(o, e);
}
static QPropertyAnimation *animator = nullptr;
auto scrollThumbs = [this](int steps) {
if (!animator) {
animator = new QPropertyAnimation(thumbsViewer->verticalScrollBar(), "value");
animator->setDuration(150); // default is 250
animator->setEasingCurve(QEasingCurve::InOutQuad);
}
int grid = thumbsViewer->gridSize().height();
if (grid < 1)
grid = thumbsViewer->thumbSize;
int v = (animator->state() == QAbstractAnimation::Running) ? animator->endValue().toInt() :
thumbsViewer->verticalScrollBar()->value();
animator->setStartValue(v);
if (qAbs(steps) == 1000) {
if (steps > 0)
v = thumbsViewer->verticalScrollBar()->maximum();
else
v = thumbsViewer->verticalScrollBar()->minimum();
} else {
if (qAbs(steps) == 100)
v += grid*qMax(1,int(thumbsViewer->height()/grid))*(steps/qAbs(steps));
else
v += grid*steps;
v = grid*int(steps < 0 ? qCeil(v/float(grid)) : v/grid);
}
animator->setEndValue(v);
animator->start();
};
if (o == thumbsViewer && e->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast(e);
if (ke->key() == Qt::Key_PageUp && !ke->modifiers()) {
scrollThumbs(-100);
return true;
} else if (ke->key() == Qt::Key_PageDown && !ke->modifiers()) {
scrollThumbs(100);
return true;
} else if (ke->key() == Qt::Key_Home && !ke->modifiers()) {
scrollThumbs(-1000);
return true;
} else if (ke->key() == Qt::Key_End && !ke->modifiers()) {
scrollThumbs(1000);
return true;
} else if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Left) {
if (!ke->modifiers() && !thumbsViewer->rect().intersects(thumbsViewer->visualRect(thumbsViewer->currentIndex()))) {
thumbsViewer->setCurrentIndex(thumbsViewer->lastVisibleThumb());
return true;
}
} else if (ke->key() == Qt::Key_Down || ke->key() == Qt::Key_Right) {
if (!ke->modifiers() && !thumbsViewer->rect().intersects(thumbsViewer->visualRect(thumbsViewer->currentIndex()))) {
thumbsViewer->setCurrentIndex(thumbsViewer->firstVisibleThumb());
return true;
}
} else if (m_copyAction->shortcut() == ke->keyCombination() || // these are sucked away by an enabled action
m_cutAction->shortcut() == ke->keyCombination()) { // issue a warning for the disabled one
setStatus(tr("No images selected"));
}
return QMainWindow::eventFilter(o, e);
}
if (e->type() == QEvent::Resize && imageViewer && o == imageViewer) {
if (m_imageToolBar->isVisible())
positionImageToolbar();
return QMainWindow::eventFilter(o, e);
}
if ((e->type() == QEvent::MouseButtonDblClick ||
e->type() == QEvent::MouseButtonPress) && o == imageViewer) {
QMouseEvent *me = static_cast(e);
bool dblclk = (me->button() == Qt::LeftButton && e->type() == QEvent::MouseButtonDblClick);
if (Settings::reverseMouseBehavior)
dblclk = (me->button() == Qt::MiddleButton && e->type() == QEvent::MouseButtonPress);
if (dblclk) {
if (me->modifiers() == Qt::ControlModifier) {
imageViewer->zoomTo(imageViewer->zoom() == 1.0 ?
ImageViewer::ZoomToFit :
ImageViewer::ZoomOriginal, me->position().toPoint());
} else if (m_presentationMode) {
if (me->modifiers() == Qt::ShiftModifier) {
m_fullScreenAction->trigger();
} else
hideViewer();
} else {
viewImage();
if (me->modifiers() == Qt::ShiftModifier && !m_fullScreenAction->isChecked()) {
m_fullScreenAction->setChecked(true);
toggleFullScreen();
}
}
return QMainWindow::eventFilter(o, e);
}
}
if (e->type() != QEvent::Wheel)
return QMainWindow::eventFilter(o, e);
QWheelEvent *we = static_cast(e);
const int scrollDelta = we->angleDelta().y();
if (scrollDelta == 0) {
return QMainWindow::eventFilter(o, e);
}
if (o == imageViewer) {
if (we->modifiers() == Qt::ControlModifier || Settings::scrollZooms) {
zoom(scrollDelta / 120.0, we->position().toPoint());
} else if (true /* m_nextImageAction->isEnabled() */) { /// @todo, why would we discriminate this?
static int delta = 0;
delta += scrollDelta;
if (qAbs(scrollDelta) < 100 && qAbs(delta) < 360)
return true;
if (scrollDelta != delta || scrollDelta % 120) // actual wheels run at 120° per click - it's unlikely to hit that w/ a touchpad
delta = -delta;
if (delta < 0) {
loadImage(Phototonic::Next);
} else {
loadImage(Phototonic::Previous);
}
delta = 0;
return true;
}
} else if (o == thumbsViewer->viewport()) {
if (we->modifiers() == Qt::ControlModifier) {
static int delta = 0;
delta += scrollDelta;
if (qAbs(scrollDelta) < 100 && qAbs(delta) < 360)
return true;
m_thumbSizeDelta += qRound(delta / 120.0);
delta = 0;
static QTimer *thumbResizer = nullptr;
if (!thumbResizer) {
thumbResizer = new QTimer(this);
thumbResizer->setInterval(125);
thumbResizer->setSingleShot(true);
connect(thumbResizer, &QTimer::timeout, [this](){resizeThumbs();});
}
thumbResizer->start();
} else {
if (qAbs(scrollDelta) < 100)
return false; // doesn't reasonably work w/ touchpads or other high-res wheels
if (we->modifiers() == Qt::ShiftModifier)
scrollThumbs(100*(scrollDelta/-qAbs(scrollDelta)));
else
scrollThumbs(qRound(scrollDelta / -120.0));
}
return true;
}
return QMainWindow::eventFilter(o, e);
}
void Phototonic::showNewImageWarning() {
MessageBox(this).warning(tr("Warning"), tr("Cannot perform action with temporary image."));
}
bool Phototonic::removeDirectoryOperation(QString dirToDelete) {
bool removeDirOk;
QDir dir(dirToDelete);
Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden |
QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
if (info.isDir()) {
removeDirOk = removeDirectoryOperation(info.absoluteFilePath());
} else {
removeDirOk = QFile::remove(info.absoluteFilePath());
}
if (!removeDirOk) {
return removeDirOk;
}
}
removeDirOk = dir.rmdir(dirToDelete);
return removeDirOk;
}
void Phototonic::addBookmark(QString path) {
Settings::bookmarkPaths.insert(path);
bookmarks->reloadBookmarks();
}
phototonic-3.3.0/Phototonic.h 0000664 0000000 0000000 00000015474 15271130355 0016217 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2015 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef PHOTOTONIC_H
#define PHOTOTONIC_H
class BookMarks;
class ColorsDialog;
class FileSystemTree;
class ImageTags;
class ImageViewer;
class InfoView;
class SettingsDialog;
class ThumbsViewer;
class QFileSystemModel;
class QLabel;
class QLineEdit;
class QProgressBar;
class QStackedLayout;
class QToolButton;
#include
#include
#include
#define VERSION "Phototonic v3.3.0"
class Phototonic : public QMainWindow {
Q_OBJECT
public:
Phototonic(QStringList argumentsList, int filesStartAt, QString filter = QString(), QWidget *parent = 0);
QMenu *createPopupMenu() override;
void setCurrentFileOrDirectory(const QString &path);
enum CentralWidgets {
ThumbViewWidget = 0,
ImageViewWidget
};
protected:
void closeEvent(QCloseEvent *event) override;
bool eventFilter(QObject *o, QEvent *e) override;
public slots:
void setSaveDirectory(QString path = QString());
private slots:
void loadSelectedThumbImage(const QModelIndex &idx);
void showViewer();
void hideViewer();
void dropOp(Qt::KeyboardModifiers keyMods, bool dirOp, QString copyMoveDirPath);
void sortThumbnails();
void setFileListMode(bool on);
void reload();
void setIncludeSubDirs();
void showSettings();
void toggleFullScreen();
void updateActions();
void reloadThumbs();
void renameDir();
void setImageViewerWindowTitle();
void setThumbsViewerWindowTitle();
void rename();
void removeMetadata();
void viewImage();
void newImage();
void deleteDirectory(bool trash);
void createSubDirectory();
void checkDirState(const QModelIndex &, int, int);
void goPathBarDir();
void goTo(QString path);
void setSlideShow(bool active);
void slideShowHandler();
void selectAllThumbs();
void deleteOperation();
void deletePermanentlyOperation();
void pasteThumbs(QString destDir = QString());
void resizeThumbs();
void rotate(int deg);
void flipVertical();
void cropImage();
void scaleImage();
void freeRotate(int deg);
void batchTransform();
void showColorsDialog();
void flipHorizontal();
void setDocksVisibility(bool visible);
void showHiddenFiles();
void setToolbarIconSize();
void chooseExternalApp();
void updateExternalApps();
void runExternalApp();
void lockDocks();
void filterImagesFocus();
void setPathFocus();
void regenerateThumbnails();
private:
enum SpecialImageIndex {
First = 0, Previous, Next, Last, Random
};
QMenu *myMainMenu;
QMenu *openWithSubMenu;
QToolBar *myMainToolBar;
QToolBar *m_imageToolBar;
// used frequently in ::updateActions, m_imageInfoAction on every tumbnail change
QAction *m_cutAction, *m_copyAction, *m_copyToAction, *m_moveToAction, *m_deleteAction,
*m_trashAction, *m_viewImageAction, *m_openWithMenuAction, *m_fullScreenAction,
*m_closeImageAction, *m_imageInfoAction, *m_batchTransformAction, *m_wallpaperAction,
*m_showGridAction;
// dto. via ::setViewerKeyEventsEnabled
QAction *m_nextImageAction, *m_prevImageAction, *m_moveLeftAction,
*m_moveRightAction, *m_moveUpAction, *m_moveDownAction;
// setFileListMode, called on path changes - maybe drop
QAction *m_includeSubDirsAction, *m_findDupesAction;
// dto.
QAction *m_refreshAction, *m_goBackAction, *m_goFrwdAction, *m_goUpAction, *m_goHomeAction;
// updated on edits, rotations, etc.
QAction *m_saveAction, *m_saveAsAction;
// not a child of ours
QAction *m_sortMenuAction;
QProgressBar *m_progressBar;
QAction *m_progressBarAction;
QLineEdit *pathLineEdit;
QAction *m_pathLineEditAction;
QLineEdit *filterLineEdit;
QDockWidget *fileSystemDock;
QDockWidget *bookmarksDock;
QDockWidget *imagePreviewDock;
QDockWidget *m_thumbViewDock;
QDockWidget *tagsDock;
FileSystemTree *fileSystemTree;
BookMarks *bookmarks;
QDockWidget *imageInfoDock;
ThumbsViewer *thumbsViewer;
ImageViewer *imageViewer;
QList pathHistoryList;
QTimer *SlideShowTimer;
QFileSystemModel *fileSystemModel;
QStackedLayout *m_centralLayout;
bool m_presentationMode;
int currentHistoryIdx;
bool needHistoryRecord;
bool initComplete;
bool needThumbsRefresh;
bool m_deleteInProgress;
InfoView *m_infoViewer;
QToolButton *m_menuButton;
QLabel *m_statusLabel;
int m_thumbSizeDelta;
bool m_logHistogram;
bool m_reloadPending;
int m_editSteps;
ImageTags *m_imageTags;
bool m_slideShowActive;
QPointer colorsDialog;
void refreshThumbs(bool noScroll);
void loadImage(SpecialImageIndex idx);
void loadShortcuts();
void setupDocks();
void deleteImages(bool trash);
void deleteFromViewer(bool trash);
void loadCurrentImage(int currentRow);
void selectCurrentViewDir();
void processStartupArguments(QStringList argumentsList, int filesStartAt);
void loadStartupFileList(QStringList argumentsList, int filesStartAt);
void createImageViewer();
void createThumbsViewer();
void createActions();
void createMenus();
void createToolBars();
void createFileSystemDock();
void createBookmarksDock();
void createImagePreviewDock();
void createThumbviewDock();
void createImageTagsDock();
void writeSettings();
void readSettings();
void addPathHistoryRecord(QString dir);
QString getSelectedPath();
void copyOrCutThumbs(bool copy);
void showNewImageWarning();
bool removeDirectoryOperation(QString dirToDelete);
void addBookmark(QString path);
void copyOrMoveImages(bool isCopyOperation);
void setViewerKeyEventsEnabled(bool enabled);
void zoom(float multiplier = 1., QPoint focus = QPoint(-1, -1));
int copyCutThumbsCount;
void setStatus(QString state);
void positionImageToolbar();
QAction *action(const QString name, bool dropHash = false) const;
bool focusIsOnBrowsing() const;
};
#endif // PHOTOTONIC_H
phototonic-3.3.0/README.md 0000664 0000000 0000000 00000015073 15271130355 0015172 0 ustar 00root root 0000000 0000000 # Phototonic Image Viewer
### About
Phototonic is an image viewer and organizer built with Qt and Exiv2, released under GNU General Public License v3.
### Features
+ Support for [common image formats](https://doc.qt.io/qt-6/qimage.html#reading-and-writing-image-files) and GIF animation
+ Display image information and edit metadata
+ Supports tagging images (IPTC)
+ Powerful filtering by image attributes (eg. average color) and tags - also non-interactively in scripts
+ Find duplicate images
+ Basic image transformation and color manipulation (screenshot editing)
+ Browse externally and internally generated image lists (find, locate, …)
+ View slideshows
+ Execute custom actions on images (eg. to set as wallpaper or look up GPS coordinates in a browser)
+ Browse thumbnails recursively down a folder tree
+ Dynamic thumbnails loading
+ Does not depend on any desktop environment
---
### Updates:
#### 30. October 2026
Release 3.3.0
* Improve touchpad/hi-res wheel scrolling
* Improve input handling with central viewer and docked thumbnails
* Improve duplicate grouping
* Use ctrl as rotation and shift as cropping modifier (aligns with overall ctrl use)
* Be more conservative when upscaling exif thumbnails
* Filter for hue and saturation and inversions of dark/bright/cold/warm
* Non-interactive --filter to filter directories in scripts
* Show image text metadata next to exif data
* Delay action icon loading for faster startup
* Some bugfixes on the road
* Introduce some brand new bugs
#### 4. April 2026
Release 3.2.0
* Support embedded thumbnails (use for preview, update and write back)
* Allow to either dock thumbnails or preview
* Add toggleabble ("g") grid to viewer to check for horizont, falling lines and warping
* AI support for better AI display (**A**nimated **I**mages use the same acclerated viewer )
* Code streamlining and cleanup
* Add "GUI" to cofigure the viewer toolbar
* Fixed some bugs ()
* Added entirely new bugs
#### 2. November 2025
Release 3.1.0
* Fixes a race condition on slow thumbnail loading over the alpha release and has more translations.
#### 11. September 2025
First 3.1 alpha
* Basic Exif editing
* Enhanced Exif filtering
* Mass/auto renaming
* Interactive file collision resolution on copy/move
* Filter images by tags
* New image filters for "warm", "cold" and brown
* Much better support for external viewer window (starting with "it no longer crashes")
* Modular translation files
* Bring back the irregular grid for the compact mode (instead of two square displays)
* Nicer viewer toolbar (secretly also configurable)
* Basic screenshot editing (annotate, blackout and encircle)
* Code cleanup
* Fixed some bugs
* Probably added new ones instead
##### 20. April 2025
With the release of 3.0.0 the 3.1 cycle starts into the summer
##### 29. March 2025
Second and final beta of 3.0
Some small bugfixes
- align collation between model and fs and preserve setting
- account for rotation when sliding images around
- upscale preview to match image
- update image info overlay when loading image from thumbviewer
- fix tag subset selection logic
- lazy inode watching
##### 12. March 2025
1st beta release
- Final new features:
- filter for colors, colorfulness and brightness
- take an image list from stdin and
- support bangs to invoke external commands (locate, find, baloo, tracker, …) to generate image lists from the path bar
- allow phototonic to run as singleton (ie. subsequent starts remote-control the existing process)
- Some UI tweaks
- most notably removed various questionable auto-scale options for sane defaults and dynamic adjustment
- More code clean-up
- Fixed bugs (mostly just introduced ones) - and I just realized one more (but completely uncritical and it's too late now)
##### 23. February 2025
3rd and omega alpha release
+ lots of code cleanup and bugfixes
+ the biggest changes are that
+ the filter now operates on the view instead of reloading the directory
+ the duplicate search incorporates histogram similarity to find potential duplicates
+ the filesystem is monitored and updated on external changes (new images saved by gimp show up automatically)
+ animated zoom and rotation and multithreaded color correction and also transactions (move/delete) are aplied to the thumbnail cache
+ I hopefully didn't introduce too many bugs…
##### 7. February 2025
Second alpha release
+ Proper thread usage - snappier behavior, less crashes
+ Reviewed the entire tag handling
+ lot's of fixes when using the viewer as preview (including the crop rect)
Improve colorizing performance
+ sort by exif date
+ lots of UI tweaks and bug fixes
+ introduced a couple of bugs (likely)
##### 27. January 2025
First alpha release
##### January 2025
+ OpenGL for the the image viewer
+ Load images outside the GUI thread
+ Cleaned up the GUI / restructured features
+ Improved performance by
+ avoiding and deferring expensive actions and
+ utilizing the thumbnails for heuristics
+ Loads of code refactoring
+ Fixed many, many bugs…
+ Added many, many bugs (probably)
##### December 2024
+ revive and Qt6 port
[Older updates](HISTORY.md)
##### Optional Dependencies
+ qt6-imageformats (TIFF and TGA support)
+ qt6-svg (SVG support)
##### Quick Build Instructions on Linux
```
$ tar -zxvf phototonic.tar.gz
$ cd phototonic
$ qmake
$ make
$ make install
$ sudo make install
```
##### Building on Windows
Building on Windows is only supported with mingw at the moment (the source code is probably compatible with msvc, but this was not tested yet).
First get the exiv2 library. Binary version is available from http://www.exiv2.org/download.html (download mingw version) or build it manually.
Note that Qt libraries must be built against the same major mingw version as exiv2 is built against (i.e. Qt built with mingw 5 and higher won't be compatible with exiv2 built with mingw 4.9).
Currently exiv2 binary package for mingw is built with mingw 4.9 therefore the latest compatible Qt version available in binary is 5.6.3 (available via Qt Maintenance Tool).
If using the binary package from exiv2 website, unpack the `mingw` directory to the root of the repository (only mingw/lib and mingw/include are essential).
Then build phototonic as usual - via qmake + mingw32-make in the console, or via QtCreator (remember to choose the compatible Qt Kit).
phototonic-3.3.0/RenameDialog.cpp 0000664 0000000 0000000 00000005476 15271130355 0016754 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include "RenameDialog.h"
RenameDialog::RenameDialog(QWidget *parent) : QDialog(parent) {
setWindowTitle(tr("Rename Image"));
QHBoxLayout *buttonsLayout = new QHBoxLayout;
QPushButton *okButton = new QPushButton(tr("Rename"));
connect(okButton, SIGNAL(clicked()), this, SLOT(ok()));
okButton->setDefault(true);
QPushButton *cancelButton = new QPushButton(tr("Cancel"));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(abort()));
buttonsLayout->addWidget(cancelButton, 1, Qt::AlignRight);
buttonsLayout->addWidget(okButton, 0, Qt::AlignRight);
QHBoxLayout *renameLayout = new QHBoxLayout;
QLabel *label = new QLabel(tr("New name: "));
m_fileName = new QLineEdit();
m_fileName->setMinimumWidth(200);
renameLayout->addWidget(label);
renameLayout->addWidget(m_fileName);
m_patternHint = new QLabel(tr("Rename files according to pattern
"
"Supported placeholders:
"
"| %index : | 0-padded index, based on selection order |
"
"| %date : | Date and time of last modification, ISO8601 format |
"
"| %exifdate : | Date and time of EXIF timestamp or file creation, ISO8601 format |
"
"| %size : | Image size, WxH |
|---|
"), this);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(m_patternHint);
mainLayout->addLayout(renameLayout);
mainLayout->addLayout(buttonsLayout);
setLayout(mainLayout);
setWindowIcon(QIcon(":/images/phototonic.png"));
setMinimumWidth(480);
}
void RenameDialog::ok() {
accept();
}
void RenameDialog::abort() {
reject();
}
void RenameDialog::setFileName(QString name) {
m_patternHint->setVisible(name.isEmpty());
m_fileName->setText(name);
m_fileName->setSelection(0, name.lastIndexOf("."));
}
QString RenameDialog::fileName() const {
return m_fileName->text();
}
phototonic-3.3.0/RenameDialog.h 0000664 0000000 0000000 00000002222 15271130355 0016403 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef RENAME_DIALOG_H
#define RENAME_DIALOG_H
class QLabel;
class QLineEdit;
#include
class RenameDialog : public QDialog {
Q_OBJECT
public:
RenameDialog(QWidget *parent);
void setFileName(QString name);
QString fileName() const;
public slots:
void ok();
void abort();
private:
QLabel *m_patternHint;
QLineEdit *m_fileName;
};
#endif // RENAME_DIALOG_H phototonic-3.3.0/ResizeDialog.cpp 0000664 0000000 0000000 00000014656 15271130355 0017006 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include "ResizeDialog.h"
ResizeDialog::ResizeDialog(QSize originalSize, QWidget *parent) : QDialog(parent) {
setWindowTitle(tr("Scale Image"));
setWindowIcon(QIcon::fromTheme("transform-scale", QIcon(":/images/transform-scale.png")));
QHBoxLayout *buttonsHbox = new QHBoxLayout;
QPushButton *okButton = new QPushButton(tr("Scale"));
connect(okButton, &QPushButton::clicked, [this]() { accept(); });
okButton->setDefault(true);
QPushButton *cancelButton = new QPushButton(tr("Cancel"));
connect(cancelButton, &QPushButton::clicked, [this]() { reject(); });
buttonsHbox->addWidget(cancelButton, 1, Qt::AlignRight);
buttonsHbox->addWidget(okButton, 0, Qt::AlignRight);
widthSpinBox = new QSpinBox;
widthSpinBox->setRange(0, originalSize.width() * 10);
widthSpinBox->setValue(originalSize.width());
connect(widthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(adjustSizes()));
heightSpinBox = new QSpinBox;
heightSpinBox->setRange(0, originalSize.height() * 10);
heightSpinBox->setValue(originalSize.height());
connect(heightSpinBox, SIGNAL(valueChanged(int)), this, SLOT(adjustSizes()));
QGridLayout *mainGbox = new QGridLayout;
QLabel *origSizeLab = new QLabel(tr("Current size:"));
QString imageSizeStr = QString("%1 x %2").arg(originalSize.width()).arg(originalSize.height());
QLabel *origSizePixelsLab = new QLabel(imageSizeStr);
QLabel *widthLab = new QLabel(tr("New Width:"));
QLabel *heightLab = new QLabel(tr("New Height:"));
QLabel *unitsLab = new QLabel(tr("Units:"));
QLabel *newSizeLab = new QLabel(tr("New size:"));
newSizePixelsLabel = new QLabel(imageSizeStr);
pixelsRadioButton = new QRadioButton(tr("Pixels"));
pixelsRadioButton->setChecked(true);
connect(pixelsRadioButton, SIGNAL(toggled(bool)), this, SLOT(setUnits()));
keepAspect = new QCheckBox(tr("Keep aspect ratio"), this);
keepAspect->setChecked(true);
connect(keepAspect, SIGNAL(toggled(bool)), this, SLOT(adjustSizes()));
QHBoxLayout *radiosHbox = new QHBoxLayout;
radiosHbox->addStretch(1);
radiosHbox->addWidget(pixelsRadioButton);
radiosHbox->addWidget(new QRadioButton(tr("Percent")));
mainGbox->addWidget(origSizeLab, 2, 2, 1, 1);
mainGbox->addWidget(origSizePixelsLab, 2, 4, 1, 1);
mainGbox->addWidget(widthLab, 6, 2, 1, 1);
mainGbox->addWidget(heightLab, 7, 2, 1, 1);
mainGbox->addWidget(unitsLab, 3, 2, 1, 1);
mainGbox->addWidget(widthSpinBox, 6, 4, 1, 2);
mainGbox->addWidget(heightSpinBox, 7, 4, 1, 2);
mainGbox->addLayout(radiosHbox, 3, 4, 1, 3);
mainGbox->addWidget(keepAspect, 5, 2, 1, 3);
mainGbox->addWidget(newSizeLab, 8, 2, 1, 1);
mainGbox->addWidget(newSizePixelsLabel, 8, 4, 1, 1);
mainGbox->setRowStretch(9, 1);
mainGbox->setColumnStretch(3, 1);
QVBoxLayout *mainVbox = new QVBoxLayout;
mainVbox->addLayout(mainGbox);
mainVbox->addLayout(buttonsHbox);
setLayout(mainVbox);
widthSpinBox->setFocus(Qt::OtherFocusReason);
m_last = m_originalSize = originalSize;
}
QSize ResizeDialog::newSize() {
return m_last;
}
void ResizeDialog::setUnits() {
int w = widthSpinBox->value(), h = heightSpinBox->value(); // preserve against range changes
widthSpinBox->blockSignals(true);
heightSpinBox->blockSignals(true);
if (pixelsRadioButton->isChecked()) { // percent -> pixels
widthSpinBox->setRange(0, m_originalSize.width() * 10);
heightSpinBox->setRange(0, m_originalSize.height() * 10);
widthSpinBox->setValue(qRound((m_originalSize.width() * w) / 100.));
heightSpinBox->setValue(qRound((m_originalSize.height() * h) / 100.0));
m_last = QSize(widthSpinBox->value(), heightSpinBox->value());
} else { // pixels -> percent
widthSpinBox->setRange(0, 100 * 10);
heightSpinBox->setRange(0, 100 * 10);
widthSpinBox->setValue(qRound((100.0 * w) / m_originalSize.width()));
heightSpinBox->setValue(qRound((100.0 * h) / m_originalSize.height()));
m_last = QSize(qRound((widthSpinBox->value() * m_originalSize.width()) / 100.0),
qRound((heightSpinBox->value() * m_originalSize.height()) / 100.0));
}
widthSpinBox->blockSignals(false);
heightSpinBox->blockSignals(false);
}
void ResizeDialog::adjustSizes() {
widthSpinBox->blockSignals(true);
heightSpinBox->blockSignals(true);
if (keepAspect->isChecked()) {
if (pixelsRadioButton->isChecked()) {
QSize imageSize = m_originalSize;
Qt::AspectRatioMode aspect = Qt::KeepAspectRatio;
if (widthSpinBox->value() > m_last.width() || heightSpinBox->value() > m_last.height())
aspect = Qt::KeepAspectRatioByExpanding;
imageSize.scale(widthSpinBox->value(), heightSpinBox->value(), aspect);
widthSpinBox->setValue(imageSize.width());
heightSpinBox->setValue(imageSize.height());
} else {
if (sender() == heightSpinBox) {
widthSpinBox->setValue(heightSpinBox->value());
} else {
heightSpinBox->setValue(widthSpinBox->value());
}
}
}
int width = widthSpinBox->value(), height = heightSpinBox->value();
if (!pixelsRadioButton->isChecked()) {
width = qRound((width * m_originalSize.width()) / 100.0);
height = qRound((height * m_originalSize.height()) / 100.0);
}
m_last = QSize(width, height);
newSizePixelsLabel->setText(QString("%1 x %2").arg(width).arg(height));
widthSpinBox->blockSignals(false);
heightSpinBox->blockSignals(false);
}
phototonic-3.3.0/ResizeDialog.h 0000664 0000000 0000000 00000002503 15271130355 0016437 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef RESIZE_DIALOG_H
#define RESIZE_DIALOG_H
class QCheckBox;
class QLabel;
class QRadioButton;
class QSpinBox;
#include
class ResizeDialog : public QDialog {
Q_OBJECT
public:
ResizeDialog(QSize originalSize, QWidget *parent = nullptr);
QSize newSize();
private slots:
void setUnits();
void adjustSizes();
private:
QSize m_originalSize;
QSize m_last;
QCheckBox *keepAspect;
QSpinBox *widthSpinBox;
QSpinBox *heightSpinBox;
QRadioButton *pixelsRadioButton;
QLabel *newSizePixelsLabel;
};
#endif // RESIZE_DIALOG_H phototonic-3.3.0/Settings.cpp 0000664 0000000 0000000 00000013430 15271130355 0016212 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include "Settings.h"
namespace Settings {
const char optionThumbsSortFlags[] = "optionThumbsSortFlags";
const char optionThumbsZoomLevel[] = "optionThumbsZoomLevel";
const char optionFullScreenMode[] = "optionFullScreenMode";
const char optionViewerBackgroundColor[] = "optionViewerBackgroundColor";
const char optionThumbsBackgroundColor[] = "optionThumbsBackgroundColor";
const char optionThumbsTextColor[] = "optionThumbsTextColor";
const char optionThumbsPagesReadCount[] = "optionThumbsPagesReadCount";
const char optionThumbsLayout[] = "optionThumbsLayout";
const char optionShowImageName[] = "optionShowImageName";
const char optionEnableAnimations[] = "enableAnimations";
const char optionWrapImageList[] = "wrapImageList";
const char optionExifRotationEnabled[] = "exifRotationEnabled";
const char optionExifThumbRotationEnabled[] = "exifThumbRotationEnabled";
const char optionReverseMouseBehavior[] = "reverseMouseBehavior";
const char optionDeleteConfirm[] = "deleteConfirm";
const char optionShowHiddenFiles[] = "showHiddenFiles";
const char optionDefaultSaveQuality[] = "defaultSaveQuality";
const char optionSlideShowDelay[] = "slideShowDelay";
const char optionSlideShowRandom[] = "slideShowRandom";
const char optionSlideShowCrossfade[] = "slideShowCrossfade";
const char optionFileSystemDockVisible[] = "fileSystemDockVisible";
const char optionBookmarksDockVisible[] = "bookmarksDockVisible";
const char optionImagePreviewDockVisible[] = "imagePreviewDockVisible";
const char optionThumbViewDockVisible[] = "thumbViewDockVisible";
const char optionTagsDockVisible[] = "tagsDockVisible";
const char optionImageInfoDockVisible[] = "imageInfoDockVisible";
const char optionSmallToolbarIcons[] = "smallToolbarIcons";
const char optionHideDockTitlebars[] = "hideDockTitlebars";
const char optionStartupDir[] = "startupDir";
const char optionSpecifiedStartDir[] = "specifiedStartDir";
const char optionThumbsBackgroundImage[] = "thumbsBackgroundImage";
const char optionShowViewerToolbar[] = "showViewerToolbar";
const char optionLastDir[] = "lastDir";
const char optionGeometry[] = "Geometry";
const char optionWindowState[] = "WindowState";
const char optionShortcuts[] = "Shortcuts";
const char optionExternalApps[] = "ExternalApps";
const char optionBangs[] = "Bangs";
const char optionExifFilters[] = "ExifFilters";
const char optionWallpaperCommand[] = "WallpaperCommand";
const char optionCopyMoveToPaths[] = "CopyMoveToPaths";
const char optionKnownTags[] = "KnownTags";
const char optionSetWindowIcon[] = "setWindowIcon";
const char optionUpscalePreview[] = "upscalePreview";
const char optionScrollZooms[] = "scrollZooms";
QSettings *appSettings;
QVariant value(const char *c, const QVariant &defaultValue) { return appSettings->value(QByteArray(c), defaultValue); }
void setValue(const char *c, const QVariant &value) { appSettings->setValue(QByteArray(c), value); }
void beginGroup(const char *c) { appSettings->beginGroup(QByteArray(c)); }
QColor viewerBackgroundColor;
QColor thumbsBackgroundColor;
QColor thumbsTextColor;
unsigned int thumbsLayout;
unsigned int thumbsPagesReadCount;
bool wrapImageList;
bool enableAnimations;
bool mouseRotateEnabled = false;
int defaultSaveQuality;
double slideShowDelay;
bool slideShowRandom;
bool slideShowCrossfade;
QMap actionKeys;
int hueVal;
int saturationVal;
int lightnessVal;
int contrastVal;
int brightVal;
int redVal;
int greenVal;
int blueVal;
bool colorsActive;
bool colorizeEnabled;
bool rNegateEnabled;
bool gNegateEnabled;
bool bNegateEnabled;
bool hueRedChannel;
bool hueGreenChannel;
bool hueBlueChannel;
bool exifRotationEnabled;
bool exifThumbRotationEnabled;
bool includeSubDirectories;
bool showHiddenFiles;
bool showViewerToolbar;
QMap externalApps;
QMap bangs;
QMap exifFilters;
QString wallpaperCommand;
QSet bookmarkPaths;
QSet knownTags;
bool reverseMouseBehavior;
bool deleteConfirm;
QModelIndexList copyCutIndexList;
bool isCopyOperation;
QStringList copyCutFileList;
bool isFullScreen;
int dialogLastX;
int dialogLastY;
StartupDir startupDir;
QString specifiedStartDir;
bool showImageName;
bool smallToolbarIcons;
bool hideDockTitlebars;
bool tagsDockVisible;
bool fileSystemDockVisible;
bool bookmarksDockVisible;
bool imagePreviewDockVisible;
bool thumbViewDockVisible;
bool imageInfoDockVisible;
QString currentDirectory;
QString saveDirectory;
QString thumbsBackgroundImage;
QStringList filesList;
bool isFileListLoaded;
bool setWindowIcon;
bool upscalePreview;
bool scrollZooms;
int dupeAccuracy;
QStringList imageToolActions;
bool alwaysUseExifThumb;
}
phototonic-3.3.0/Settings.h 0000664 0000000 0000000 00000013541 15271130355 0015662 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef SETTINGS_H
#define SETTINGS_H
#define BAD_IMAGE_SIZE 64
#define THUMB_SIZE_MIN 25
#define THUMB_SIZE_MAX 512
#define WINDOW_ICON_SIZE 48
class QAction;
class QSettings;
#include
#include
#include
#include
namespace Settings {
enum StartupDir {
RememberLastDir = 0,
DefaultDir,
SpecifiedDir
};
extern const char optionThumbsSortFlags[];
extern const char optionThumbsZoomLevel[];
extern const char optionFullScreenMode[];
extern const char optionViewerBackgroundColor[];
extern const char optionThumbsBackgroundColor[];
extern const char optionThumbsTextColor[];
extern const char optionThumbsPagesReadCount[];
extern const char optionThumbsLayout[];
extern const char optionShowImageName[];
extern const char optionEnableAnimations[];
extern const char optionWrapImageList[];
extern const char optionExifRotationEnabled[];
extern const char optionExifThumbRotationEnabled[];
extern const char optionReverseMouseBehavior[];
extern const char optionDeleteConfirm[];
extern const char optionShowHiddenFiles[];
extern const char optionDefaultSaveQuality[];
extern const char optionSlideShowDelay[];
extern const char optionSlideShowRandom[];
extern const char optionSlideShowCrossfade[];
extern const char optionFileSystemDockVisible[];
extern const char optionBookmarksDockVisible[];
extern const char optionImagePreviewDockVisible[];
extern const char optionThumbViewDockVisible[];
extern const char optionTagsDockVisible[];
extern const char optionImageInfoDockVisible[];
extern const char optionSmallToolbarIcons[];
extern const char optionHideDockTitlebars[];
extern const char optionStartupDir[];
extern const char optionSpecifiedStartDir[];
extern const char optionThumbsBackgroundImage[];
extern const char optionShowViewerToolbar[];
extern const char optionLastDir[];
extern const char optionGeometry[];
extern const char optionWindowState[];
extern const char optionShortcuts[];
extern const char optionExternalApps[];
extern const char optionBangs[];
extern const char optionExifFilters[];
extern const char optionWallpaperCommand[];
extern const char optionCopyMoveToPaths[];
extern const char optionKnownTags[];
extern const char optionSetWindowIcon[];
extern const char optionUpscalePreview[];
extern const char optionScrollZooms[];
extern QSettings *appSettings;
QVariant value(const char *c, const QVariant &defaultValue);
void setValue(const char *c, const QVariant &value);
void beginGroup(const char *c);
extern QColor viewerBackgroundColor;
extern QColor thumbsBackgroundColor;
extern QColor thumbsTextColor;
extern unsigned int thumbsLayout;
extern unsigned int thumbsPagesReadCount;
extern bool wrapImageList;
extern bool enableAnimations;
extern bool mouseRotateEnabled;
extern int defaultSaveQuality;
extern double slideShowDelay;
extern bool slideShowRandom;
extern bool slideShowCrossfade;
extern QMap actionKeys;
extern int hueVal;
extern int saturationVal;
extern int lightnessVal;
extern int contrastVal;
extern int brightVal;
extern int redVal;
extern int greenVal;
extern int blueVal;
extern bool colorsActive;
extern bool colorizeEnabled;
extern bool rNegateEnabled;
extern bool gNegateEnabled;
extern bool bNegateEnabled;
extern bool hueRedChannel;
extern bool hueGreenChannel;
extern bool hueBlueChannel;
extern bool exifRotationEnabled;
extern bool exifThumbRotationEnabled;
extern bool includeSubDirectories;
extern bool showHiddenFiles;
extern bool showViewerToolbar;
extern QMap externalApps;
extern QMap bangs;
extern QMap exifFilters;
extern QString wallpaperCommand;
extern QSet bookmarkPaths;
extern QSet knownTags;
extern bool reverseMouseBehavior;
extern bool deleteConfirm;
extern QModelIndexList copyCutIndexList;
extern bool isCopyOperation;
extern QStringList copyCutFileList;
extern bool isFullScreen;
extern int dialogLastX;
extern int dialogLastY;
extern StartupDir startupDir;
extern QString specifiedStartDir;
extern bool showImageName;
extern bool smallToolbarIcons;
extern bool hideDockTitlebars;
extern bool fileSystemDockVisible;
extern bool bookmarksDockVisible;
extern bool imagePreviewDockVisible;
extern bool thumbViewDockVisible;
extern bool tagsDockVisible;
extern bool imageInfoDockVisible;
extern QString currentDirectory;
extern QString saveDirectory;
extern QString thumbsBackgroundImage;
extern bool thumbsRepeatBackgroundImage;
extern QStringList filesList;
extern bool isFileListLoaded;
extern bool setWindowIcon;
extern bool upscalePreview;
extern bool scrollZooms;
extern int dupeAccuracy;
extern QStringList imageToolActions;
extern bool alwaysUseExifThumb;
}
#endif // SETTINGS_H
phototonic-3.3.0/SettingsDialog.cpp 0000664 0000000 0000000 00000057741 15271130355 0017347 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Settings.h"
#include "SettingsDialog.h"
#include "ShortcutsTable.h"
QStringList SettingsDialog::defaultImageToolActions() {
const QString defaultTools(
"prevImage,nextImage,firstImage,lastImage,toggleSlideShow,|,save,saveAs,moveToTrash,delete,"
"|,zoomIn,zoomOut,resetZoom,origZoom,rotateRight,rotateLeft,rotateMouse,flipH,flipV,|,"
"resize,crop,blackout,cartouche,annotate,colors");
return defaultTools.split(',');
}
SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent) {
setWindowTitle(tr("Preferences"));
setWindowIcon(QIcon::fromTheme("preferences-system", QIcon(":/images/preferences-system.png")));
// imageViewer background color
QLabel *backgroundColorLabel = new QLabel(tr("Background color:"));
backgroundColorButton = new QToolButton();
backgroundColorButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
QHBoxLayout *backgroundColorHBox = new QHBoxLayout;
backgroundColorHBox->addWidget(backgroundColorLabel);
backgroundColorHBox->addWidget(backgroundColorButton);
backgroundColorHBox->addStretch(1);
connect(backgroundColorButton, SIGNAL(clicked()), this, SLOT(pickColor()));
setButtonBgColor(Settings::viewerBackgroundColor, backgroundColorButton);
imageViewerBackgroundColor = Settings::viewerBackgroundColor;
// Wrap image list
wrapListCheckBox = new QCheckBox(tr("Wrap image list when reaching last or first image"), this);
wrapListCheckBox->setChecked(Settings::wrapImageList);
// Save quality
QLabel *saveQualityLabel = new QLabel(tr("Default quality when saving:"));
saveQualitySpinBox = new QSpinBox;
saveQualitySpinBox->setRange(0, 100);
saveQualitySpinBox->setValue(Settings::defaultSaveQuality);
QHBoxLayout *saveQualityHbox = new QHBoxLayout;
saveQualityHbox->addWidget(saveQualityLabel);
saveQualityHbox->addWidget(saveQualitySpinBox);
saveQualityHbox->addStretch(1);
// Enable animations
enableAnimCheckBox = new QCheckBox(tr("Enable GIF animation"), this);
enableAnimCheckBox->setChecked(Settings::enableAnimations);
// Enable image Exif rotation
enableExifCheckBox = new QCheckBox(tr("Rotate image according to Exif orientation value"), this);
enableExifCheckBox->setChecked(Settings::exifRotationEnabled);
// Image name
showImageNameCheckBox = new QCheckBox(tr("Show image file name in viewer"), this);
showImageNameCheckBox->setChecked(Settings::showImageName);
scrollZoomCheckBox = new QCheckBox(tr("Use scroll wheel for zooming"), this);
scrollZoomCheckBox->setChecked(Settings::scrollZooms);
// Slide show delay
QLabel *slideDelayLab = new QLabel(tr("Delay between slides in seconds:"));
slideDelaySpinBox = new QDoubleSpinBox;
slideDelaySpinBox->setRange(0.1, 3600.0);
slideDelaySpinBox->setValue(Settings::slideShowDelay);
QHBoxLayout *slideDelayLayout = new QHBoxLayout;
slideDelayLayout->addWidget(slideDelayLab);
slideDelayLayout->addWidget(slideDelaySpinBox);
slideDelayLayout->addStretch(1);
// Slide show random
slideRandomCheckBox = new QCheckBox(tr("Show random images"), this);
slideRandomCheckBox->setChecked(Settings::slideShowRandom);
// Slide show random
slideCrossfadeCheckBox = new QCheckBox(tr("Crossfade images"), this);
slideCrossfadeCheckBox->setChecked(Settings::slideShowCrossfade);
connect(slideDelaySpinBox, &QDoubleSpinBox::valueChanged, [this](double d){ slideCrossfadeCheckBox->setEnabled(d >= 1.0);});
// Slide show options
QGroupBox *slideshowGroupBox = new QGroupBox(tr("Slideshow"));
QVBoxLayout *slideshowLayout = new QVBoxLayout(slideshowGroupBox);
slideshowLayout->addLayout(slideDelayLayout);
slideshowLayout->addWidget(slideRandomCheckBox);
slideshowLayout->addWidget(slideCrossfadeCheckBox);
slideshowLayout->addStretch(1);
QHBoxLayout *toolbarItems = new QHBoxLayout;
toolbarItems->addWidget(new QLabel(tr("Viewer toolbar items:")));
toolbarItemActions = new QLineEdit;
QStringList list = defaultImageToolActions();
list.removeDuplicates();
list.sort();
QCompleter *completer = new QCompleter(list, this);
completer->setWidget(toolbarItemActions);
connect(toolbarItemActions, &QLineEdit::textEdited, [this,completer](const QString &text) {
completer->setCompletionPrefix(text.section(',',-1));
completer->complete();
});
connect(completer, qOverload(&QCompleter::highlighted), [this](const QString &text) {
toolbarItemActions->setText(toolbarItemActions->text().section(',',0,-2) + ',' + text);
});
toolbarItemActions->setText(Settings::imageToolActions.join(','));
toolbarItemActions->setClearButtonEnabled(true);
toolbarItems->addWidget(toolbarItemActions);
// Viewer options
QVBoxLayout *viewerOptsBox = new QVBoxLayout;
viewerOptsBox->addLayout(backgroundColorHBox);
viewerOptsBox->addWidget(enableExifCheckBox);
viewerOptsBox->addWidget(enableAnimCheckBox);
viewerOptsBox->addWidget(showImageNameCheckBox);
viewerOptsBox->addWidget(scrollZoomCheckBox);
viewerOptsBox->addWidget(wrapListCheckBox);
viewerOptsBox->addLayout(saveQualityHbox);
viewerOptsBox->addWidget(slideshowGroupBox);
viewerOptsBox->addLayout(toolbarItems);
viewerOptsBox->addStretch(1);
// thumbsViewer background color
QLabel *thumbsBackgroundColorLabel = new QLabel(tr("Thumbnails and Preview Background Color:"));
thumbsColorPickerButton = new QToolButton();
thumbsColorPickerButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
QHBoxLayout *thumbsBackgroundColorLayout = new QHBoxLayout;
thumbsBackgroundColorLayout->addWidget(thumbsBackgroundColorLabel);
thumbsBackgroundColorLayout->addWidget(thumbsColorPickerButton);
thumbsBackgroundColorLayout->addStretch(1);
connect(thumbsColorPickerButton, SIGNAL(clicked()), this, SLOT(pickThumbsColor()));
setButtonBgColor(Settings::thumbsBackgroundColor, thumbsColorPickerButton);
thumbsBackgroundColor = Settings::thumbsBackgroundColor;
// thumbsViewer text color
QLabel *thumbLabelColorLabel = new QLabel(tr("Label color:"));
thumbsLabelColorButton = new QToolButton();
thumbsLabelColorButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
QHBoxLayout *thumbsLabelColorLayout = new QHBoxLayout;
thumbsLabelColorLayout->addWidget(thumbLabelColorLabel);
thumbsLabelColorLayout->addWidget(thumbsLabelColorButton);
thumbsLabelColorLayout->addStretch(1);
connect(thumbsLabelColorButton, SIGNAL(clicked()), this, SLOT(pickThumbsTextColor()));
setButtonBgColor(Settings::thumbsTextColor, thumbsLabelColorButton);
thumbsTextColor = Settings::thumbsTextColor;
// thumbsViewer background image
QLabel *thumbsBackgroundImageLabel = new QLabel(tr("Background image:"));
thumbsBackgroundImageLineEdit = new QLineEdit;
thumbsBackgroundImageLineEdit->setClearButtonEnabled(true);
thumbsBackgroundImageLineEdit->setMinimumWidth(200);
QPushButton *chooseThumbsBackImageButton = new QPushButton();
chooseThumbsBackImageButton->setIcon(QIcon::fromTheme("document-open", QIcon(":/images/document-open.png")));
chooseThumbsBackImageButton->setFixedSize(26, 26);
chooseThumbsBackImageButton->setIconSize(QSize(16, 16));
connect(chooseThumbsBackImageButton, SIGNAL(clicked()), this, SLOT(pickBackgroundImage()));
QHBoxLayout *thumbsBackgroundImageLayout = new QHBoxLayout;
thumbsBackgroundImageLayout->addWidget(thumbsBackgroundImageLabel);
thumbsBackgroundImageLayout->addWidget(thumbsBackgroundImageLineEdit);
thumbsBackgroundImageLayout->addWidget(chooseThumbsBackImageButton);
thumbsBackgroundImageLayout->addStretch(1);
thumbsBackgroundImageLineEdit->setText(Settings::thumbsBackgroundImage);
// Thumbnail pages to read ahead
QLabel *thumbsPagesReadLabel = new QLabel(tr("Number of thumbnail pages to read ahead:"));
thumbPagesSpinBox = new QSpinBox;
thumbPagesSpinBox->setRange(1, 10);
thumbPagesSpinBox->setValue(Settings::thumbsPagesReadCount);
QHBoxLayout *thumbPagesReadLayout = new QHBoxLayout;
thumbPagesReadLayout->addWidget(thumbsPagesReadLabel);
thumbPagesReadLayout->addWidget(thumbPagesSpinBox);
thumbPagesReadLayout->addStretch(1);
enableThumbExifCheckBox = new QCheckBox(tr("Rotate thumbnail according to Exif orientation value"), this);
enableThumbExifCheckBox->setChecked(Settings::exifThumbRotationEnabled);
// Upscale preview image
upscalePreviewCheckBox = new QCheckBox(tr("Scale up small images in preview"), this);
upscalePreviewCheckBox->setChecked(Settings::upscalePreview);
alwaysExifThumbs = new QCheckBox(tr("Always use the thumbnail embedded in the image"), this);
alwaysExifThumbs->setToolTip(tr("Othwise it will only be used and upscaled if its at least half the required size"));
alwaysExifThumbs->setChecked(Settings::alwaysUseExifThumb);
// Thumbnail options
QVBoxLayout *thumbsOptsBox = new QVBoxLayout;
thumbsOptsBox->addLayout(thumbsBackgroundColorLayout);
thumbsOptsBox->addLayout(thumbsBackgroundImageLayout);
thumbsOptsBox->addLayout(thumbsLabelColorLayout);
thumbsOptsBox->addWidget(enableThumbExifCheckBox);
thumbsOptsBox->addWidget(upscalePreviewCheckBox);
thumbsOptsBox->addWidget(alwaysExifThumbs);
thumbsOptsBox->addLayout(thumbPagesReadLayout);
thumbsOptsBox->addStretch(1);
// Mouse settings
reverseMouseCheckBox = new QCheckBox(tr("Swap mouse double-click and middle-click actions"), this);
reverseMouseCheckBox->setChecked(Settings::reverseMouseBehavior);
// Delete confirmation setting
deleteConfirmCheckBox = new QCheckBox(tr("Delete confirmation"), this);
deleteConfirmCheckBox->setChecked(Settings::deleteConfirm);
// Startup directory
QGroupBox *startupDirGroupBox = new QGroupBox(tr("Startup directory if not specified by command line"));
startupDirectoryRadioButtons[Settings::RememberLastDir] = new QRadioButton(tr("Remember last"));
startupDirectoryRadioButtons[Settings::DefaultDir] = new QRadioButton(tr("Default"));
//: specificy a startup directory
startupDirectoryRadioButtons[Settings::SpecifiedDir] = new QRadioButton(tr("Specify:"));
startupDirLineEdit = new QLineEdit;
startupDirLineEdit->setClearButtonEnabled(true);
startupDirLineEdit->setMinimumWidth(300);
startupDirLineEdit->setMaximumWidth(400);
QPushButton *chooseStartupDirButton = new QPushButton();
chooseStartupDirButton->setIcon(QIcon::fromTheme("document-open", QIcon(":/images/document-open.png")));
chooseStartupDirButton->setFixedSize(26, 26);
chooseStartupDirButton->setIconSize(QSize(16, 16));
connect(chooseStartupDirButton, SIGNAL(clicked()), this, SLOT(pickStartupDir()));
QHBoxLayout *startupDirectoryLayout = new QHBoxLayout;
startupDirectoryLayout->addWidget(startupDirectoryRadioButtons[2]);
startupDirectoryLayout->addWidget(startupDirLineEdit);
startupDirectoryLayout->addWidget(chooseStartupDirButton);
startupDirectoryLayout->addStretch(1);
QVBoxLayout *startupDirectoryMainLayout = new QVBoxLayout;
for (int i = 0; i < 2; ++i) {
startupDirectoryMainLayout->addWidget(startupDirectoryRadioButtons[i]);
startupDirectoryRadioButtons[i]->setChecked(false);
}
startupDirectoryMainLayout->addLayout(startupDirectoryLayout);
startupDirectoryMainLayout->addStretch(1);
startupDirGroupBox->setLayout(startupDirectoryMainLayout);
if (Settings::startupDir == Settings::SpecifiedDir) {
startupDirectoryRadioButtons[Settings::SpecifiedDir]->setChecked(true);
} else if (Settings::startupDir == Settings::RememberLastDir) {
startupDirectoryRadioButtons[Settings::RememberLastDir]->setChecked(true);
} else {
startupDirectoryRadioButtons[Settings::DefaultDir]->setChecked(true);
}
startupDirLineEdit->setText(Settings::specifiedStartDir);
// Keyboard shortcuts
ShortcutsTable *shortcutsTable = new ShortcutsTable();
shortcutsTable->refreshShortcuts();
QGroupBox *keyboardGroupBox = new QGroupBox(tr("Shortcuts"));
QVBoxLayout *keyboardSettingsLayout = new QVBoxLayout;
QHBoxLayout *filterShortcutsLayout = new QHBoxLayout;
QLineEdit *shortcutsFilterLineEdit = new QLineEdit;
shortcutsFilterLineEdit->setClearButtonEnabled(true);
shortcutsFilterLineEdit->setPlaceholderText(tr("Filter Items"));
connect(shortcutsFilterLineEdit, SIGNAL(textChanged(
const QString&)), shortcutsTable, SLOT(setFilter(
const QString&)));
keyboardSettingsLayout->addWidget(new QLabel(tr("Select an entry and press a key to set a new shortcut")));
keyboardSettingsLayout->addWidget(shortcutsFilterLineEdit);
keyboardSettingsLayout->addWidget(shortcutsTable);
keyboardSettingsLayout->addLayout(filterShortcutsLayout);
keyboardGroupBox->setLayout(keyboardSettingsLayout);
// Set window icon
setWindowIconCheckBox = new QCheckBox(tr("Set the application icon according to the current image"), this);
setWindowIconCheckBox->setChecked(Settings::setWindowIcon);
QVBoxLayout *generalSettingsLayout = new QVBoxLayout;
generalSettingsLayout->addWidget(reverseMouseCheckBox);
generalSettingsLayout->addWidget(deleteConfirmCheckBox);
generalSettingsLayout->addWidget(startupDirGroupBox);
generalSettingsLayout->addWidget(setWindowIconCheckBox);
generalSettingsLayout->addStretch(1);
QVBoxLayout *bangLayout = new QVBoxLayout;
QLabel *rtfm = new QLabel(
tr("Bangs allow you to use external commands to generate the list of shown images.
"
"The main purpose is to query databases like locate, baloo or tracker, "
"but anything that can generate a list of image files is suitable
"
"The token %s in the command will be replaced with the parameter.
"
"Eg. for plocate, using the shortcut locate and the command
"
"bash -c \"locate -i '*%s*' | grep --line-buffered -iE '(jpe?g|png)$'\"
"
"allows you to enter locate:waldo to display indexed jpg's and png's of waldo.
"
"Phototonic tests the files for existence and will remove duplicates (including file and "
"directory symlinks.
"));
rtfm->setWordWrap(true);
bangLayout->addWidget(rtfm);
bangTable = new QTableWidget(this);
bangTable->setColumnCount(2);
bangTable->setSelectionMode(QAbstractItemView::SingleSelection);
bangTable->setSelectionBehavior(QAbstractItemView::SelectItems);
bangTable->verticalHeader()->setVisible(false);
bangTable->verticalHeader()->setDefaultSectionSize(bangTable->verticalHeader()->minimumSectionSize());
bangTable->setHorizontalHeaderItem(0, new QTableWidgetItem(tr("Shortcut")));
bangTable->setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Command")));
bangTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);
bangTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
bangTable->setShowGrid(true);
bangTable->setRowCount(Settings::bangs.size()+1);
int row = 0;
for (auto i = Settings::bangs.cbegin(), end = Settings::bangs.cend(); i != end; ++i) {
bangTable->setItem(row, 0, new QTableWidgetItem(i.key()));
bangTable->setItem(row++, 1, new QTableWidgetItem(i.value()));
}
bangLayout->addWidget(bangTable);
connect (bangTable, &QTableWidget::cellChanged, this, [this](int row, int col) {
if (row < bangTable->rowCount() - 1 && bangTable->item(row,0)->text().isEmpty() && bangTable->item(row,1)->text().isEmpty()) {
bangTable->removeRow(row);
} else {
if (col == 0) {
bangTable->blockSignals(true);
for (int i = 0; i < bangTable->rowCount(); ++i) {
if (QTableWidgetItem *item = bangTable->item(i, 0))
item->setForeground(QBrush());
}
for (int i = 0; i < bangTable->rowCount() - 1; ++i) {
QTableWidgetItem *item_i = bangTable->item(i, 0);
if (!item_i)
continue;
for (int j = i + 1; j < bangTable->rowCount(); ++j) {
QTableWidgetItem *item_j = bangTable->item(j, 0);
if (!item_j || item_j->text() != item_i->text())
continue;
item_i->setForeground(QColor(208,23,23));
item_j->setForeground(QColor(208,23,23));
}
}
bangTable->blockSignals(false);
}
if (row == bangTable->rowCount()-1 && !bangTable->item(row,col)->text().isEmpty())
bangTable->setRowCount(bangTable->rowCount() + 1);
}
});
QAction *act = new QAction;
act->setShortcut(Qt::Key_Delete);
act->setShortcutContext(Qt::WidgetShortcut);
connect(act, &QAction::triggered, [this]() {
bangTable->currentItem()->setText(QString());
});
bangTable->addAction(act);
/* Confirmation buttons */
QHBoxLayout *confirmSettingsLayout = new QHBoxLayout;
QPushButton *okButton = new QPushButton(tr("OK"));
okButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(okButton, SIGNAL(clicked()), this, SLOT(saveSettings()));
okButton->setDefault(true);
QPushButton *closeButton = new QPushButton(tr("Cancel"));
closeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(closeButton, SIGNAL(clicked()), this, SLOT(abort()));
confirmSettingsLayout->addWidget(closeButton, 1, Qt::AlignRight);
confirmSettingsLayout->addWidget(okButton, 0, Qt::AlignRight);
/* Tabs */
QTabWidget *settingsTabs = new QTabWidget;
QWidget *viewerSettings = new QWidget;
viewerSettings->setLayout(viewerOptsBox);
settingsTabs->addTab(viewerSettings, tr("Viewer"));
QWidget *thumbSettings = new QWidget;
thumbSettings->setLayout(thumbsOptsBox);
settingsTabs->addTab(thumbSettings, tr("Thumbnails"));
QWidget *generalSettings = new QWidget;
generalSettings->setLayout(generalSettingsLayout);
settingsTabs->addTab(generalSettings, tr("General"));
QWidget *keyboardSettings = new QWidget;
keyboardSettings->setLayout(keyboardSettingsLayout);
settingsTabs->addTab(keyboardSettings, tr("Shortcuts"));
QWidget *bangSettings = new QWidget;
bangSettings->setLayout(bangLayout);
settingsTabs->addTab(bangSettings, tr("Bangs"));
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(settingsTabs);
mainLayout->addLayout(confirmSettingsLayout);
setLayout(mainLayout);
}
void SettingsDialog::saveSettings() {
Settings::viewerBackgroundColor = imageViewerBackgroundColor;
Settings::thumbsBackgroundColor = thumbsBackgroundColor;
Settings::thumbsTextColor = thumbsTextColor;
Settings::thumbsBackgroundImage = thumbsBackgroundImageLineEdit->text();
Settings::thumbsPagesReadCount = (unsigned int) thumbPagesSpinBox->value();
Settings::wrapImageList = wrapListCheckBox->isChecked();
Settings::defaultSaveQuality = saveQualitySpinBox->value();
Settings::slideShowDelay = slideDelaySpinBox->value();
Settings::slideShowRandom = slideRandomCheckBox->isChecked();
Settings::slideShowCrossfade = slideCrossfadeCheckBox->isChecked();
Settings::imageToolActions = toolbarItemActions->text().split(',', Qt::SkipEmptyParts);
if (Settings::imageToolActions.isEmpty())
Settings::imageToolActions = defaultImageToolActions();
Settings::enableAnimations = enableAnimCheckBox->isChecked();
Settings::exifRotationEnabled = enableExifCheckBox->isChecked();
Settings::exifThumbRotationEnabled = enableThumbExifCheckBox->isChecked();
Settings::showImageName = showImageNameCheckBox->isChecked();
Settings::reverseMouseBehavior = reverseMouseCheckBox->isChecked();
Settings::scrollZooms = scrollZoomCheckBox->isChecked();
Settings::deleteConfirm = deleteConfirmCheckBox->isChecked();
Settings::setWindowIcon = setWindowIconCheckBox->isChecked();
Settings::upscalePreview = upscalePreviewCheckBox->isChecked();
Settings::alwaysUseExifThumb = alwaysExifThumbs->isChecked();
if (startupDirectoryRadioButtons[Settings::RememberLastDir]->isChecked()) {
Settings::startupDir = Settings::RememberLastDir;
} else if (startupDirectoryRadioButtons[Settings::DefaultDir]->isChecked()) {
Settings::startupDir = Settings::DefaultDir;
} else {
Settings::startupDir = Settings::SpecifiedDir;
Settings::specifiedStartDir = startupDirLineEdit->text();
}
Settings::bangs.clear();
for (int i = 0; i < bangTable->rowCount() - 1; ++i) {
QString key = QString("bang_%1").arg(i);
if (bangTable->item(i,0) && !bangTable->item(i,0)->text().isEmpty())
key = bangTable->item(i,0)->text();
QString value;
if (bangTable->item(i,1))
value = bangTable->item(i,1)->text();
Settings::bangs[key] = value;
}
accept();
}
void SettingsDialog::abort() {
reject();
}
void SettingsDialog::pickColor() {
QColor userColor = QColorDialog::getColor(Settings::viewerBackgroundColor, this);
if (userColor.isValid()) {
setButtonBgColor(userColor, backgroundColorButton);
imageViewerBackgroundColor = userColor;
}
}
void SettingsDialog::setButtonBgColor(QColor &color, QAbstractButton *button) {
const int s = qMin(button->width(),button->height());
QPixmap pix(s, s);
pix.fill(Qt::transparent);
QPainter p(&pix);
p.setRenderHint(QPainter::Antialiasing);
p.setBrush(color);
p.drawEllipse(pix.rect());
p.end();
button->setIcon(pix);
button->setText(color.name());
}
void SettingsDialog::pickThumbsColor() {
QColor userColor = QColorDialog::getColor(Settings::thumbsBackgroundColor, this, tr("Select background color"), QColorDialog::ShowAlphaChannel);
if (userColor.isValid()) {
setButtonBgColor(userColor, thumbsColorPickerButton);
thumbsBackgroundColor = userColor;
}
}
void SettingsDialog::pickThumbsTextColor() {
QColor userColor = QColorDialog::getColor(Settings::thumbsTextColor, this);
if (userColor.isValid()) {
setButtonBgColor(userColor, thumbsLabelColorButton);
thumbsTextColor = userColor;
}
}
void SettingsDialog::pickStartupDir() {
QString dirName = QFileDialog::getExistingDirectory(this, tr("Choose Startup Directory"), "",
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
startupDirLineEdit->setText(dirName);
}
void SettingsDialog::pickBackgroundImage() {
QString dirName = QFileDialog::getOpenFileName(this, tr("Open File"), "",
tr("Images") +
" (*.jpg *.jpeg *.jpe *.png *.bmp *.tiff *.tif *.ppm *.xbm *.xpm)");
thumbsBackgroundImageLineEdit->setText(dirName);
}
phototonic-3.3.0/SettingsDialog.h 0000664 0000000 0000000 00000004742 15271130355 0017005 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef SETTINGS_DIALOG_H
#define SETTINGS_DIALOG_H
class QAbstractButton;
class QCheckBox;
class QLineEdit;
class QRadioButton;
class QSpinBox;
class QTableWidget;
class QToolButton;
class QDoubleSpinBox;
#include
class SettingsDialog : public QDialog {
Q_OBJECT
public:
SettingsDialog(QWidget *parent);
static QStringList defaultImageToolActions();
private slots:
void pickColor();
void pickThumbsColor();
void pickThumbsTextColor();
void pickStartupDir();
void pickBackgroundImage();
public slots:
void abort();
void saveSettings();
private:
QToolButton *backgroundColorButton;
QToolButton *thumbsColorPickerButton;
QToolButton *thumbsLabelColorButton;
QSpinBox *thumbPagesSpinBox;
QSpinBox *saveQualitySpinBox;
QColor imageViewerBackgroundColor;
QColor thumbsBackgroundColor;
QColor thumbsTextColor;
QCheckBox *wrapListCheckBox;
QCheckBox *enableAnimCheckBox;
QCheckBox *enableExifCheckBox;
QCheckBox *enableThumbExifCheckBox;
QCheckBox *showImageNameCheckBox;
QCheckBox *reverseMouseCheckBox;
QCheckBox *scrollZoomCheckBox;
QCheckBox *deleteConfirmCheckBox;
QDoubleSpinBox *slideDelaySpinBox;
QCheckBox *slideRandomCheckBox;
QCheckBox *slideCrossfadeCheckBox;
QRadioButton *startupDirectoryRadioButtons[3];
QLineEdit *startupDirLineEdit;
QLineEdit *thumbsBackgroundImageLineEdit;
QCheckBox *thumbsRepeatBackgroundImageCheckBox;
QCheckBox *setWindowIconCheckBox;
QCheckBox *upscalePreviewCheckBox;
QTableWidget *bangTable;
QLineEdit *toolbarItemActions;
QCheckBox *alwaysExifThumbs;
void setButtonBgColor(QColor &color, QAbstractButton *button);
};
#endif // SETTINGS_DIALOG_H
phototonic-3.3.0/ShortcutsTable.cpp 0000664 0000000 0000000 00000013671 15271130355 0017367 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include "ShortcutsTable.h"
#include "Settings.h"
#include "MessageBox.h"
ShortcutsTable::ShortcutsTable() {
keysModel = new QStandardItemModel(this);
setModel(keysModel);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
setEditTriggers(QAbstractItemView::NoEditTriggers);
verticalHeader()->hide();
verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
verticalHeader()->setDefaultSectionSize(verticalHeader()->minimumSectionSize());
horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
horizontalHeader()->setHighlightSections(false);
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setColumnHidden(2, true);
shortcutsMenu = new QMenu("");
clearAction = new QAction(tr("Delete shortcut"), this);
connect(clearAction, SIGNAL(triggered()), this, SLOT(clearSelectedShortcut()));
shortcutsMenu->addAction(clearAction);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showShortcutPopupMenu(QPoint)));
shortcutsFilter.clear();
}
void ShortcutsTable::addRow(QString action, QString description, QString shortcut) {
keysModel->appendRow(QList() << new QStandardItem(description)
<< new QStandardItem(shortcut)
<< new QStandardItem(action));
}
void ShortcutsTable::keyPressEvent(QKeyEvent *keyEvent) {
if (!this->selectedIndexes().count()) {
return;
}
QString keySequenceText;
QString keyText("");
QString modifierText("");
if (keyEvent->modifiers() & Qt::ShiftModifier)
modifierText += "Shift+";
if (keyEvent->modifiers() & Qt::ControlModifier)
modifierText += "Ctrl+";
if (keyEvent->modifiers() & Qt::AltModifier)
modifierText += "Alt+";
if ((keyEvent->key() >= Qt::Key_Shift && keyEvent->key() <= Qt::Key_ScrollLock)
|| (keyEvent->key() >= Qt::Key_Super_L && keyEvent->key() <= Qt::Key_Direction_R)
|| keyEvent->key() == Qt::Key_AltGr
|| keyEvent->key() < 0) {
return;
}
keyText = QKeySequence(keyEvent->key()).toString();
keySequenceText = modifierText + keyText;
if ((keyEvent->modifiers() & Qt::AltModifier) &&
(keyEvent->key() > Qt::Key_0 && keyEvent->key() <= Qt::Key_Colon)) {
return MessageBox(this).critical(tr("Set shortcut"), tr("%1 is reserved for launching external applications.").arg(keySequenceText));
}
QMapIterator keysIterator(Settings::actionKeys);
bool needToRefreshShortCuts = false;
while (keysIterator.hasNext()) {
keysIterator.next();
QAction tmpAction(this);
tmpAction.setShortcut(keySequenceText);
if (keysIterator.value()->shortcut().toString() == tmpAction.shortcut().toString()) {
if (!confirmOverwriteShortcut(keysIterator.value()->text(), keySequenceText)) {
return;
}
Settings::actionKeys.value(keysIterator.key())->setShortcut(QKeySequence());
needToRefreshShortCuts = true;
}
}
int row = selectedIndexes().first().row();
keysModel->item(row, 1)->setText(keySequenceText);
Settings::actionKeys.value(keysModel->item(row, 2)->text())->setShortcut(QKeySequence(keySequenceText));
if (needToRefreshShortCuts) {
refreshShortcuts();
}
}
bool ShortcutsTable::confirmOverwriteShortcut(QString action, QString shortcut) {
return MessageBox(this, MessageBox::Yes | MessageBox::Cancel, MessageBox::Cancel).warning(
tr("Overwrite Shortcut"), tr("%1 is already assigned to %2, reassign shortcut?").arg(shortcut).arg(action))
== MessageBox::Yes;
}
void ShortcutsTable::clearSelectedShortcut() {
if (selectedEntry.isValid()) {
QStandardItemModel *itemsModel = (QStandardItemModel *) model();
itemsModel->item(selectedEntry.row(), 1)->setText("");
Settings::actionKeys.value(itemsModel->item(selectedEntry.row(), 2)->text())->setShortcut(QKeySequence(""));
}
}
void ShortcutsTable::showShortcutPopupMenu(QPoint point) {
selectedEntry = indexAt(point);
if (selectedEntry.isValid())
shortcutsMenu->popup(viewport()->mapToGlobal(point));
}
void ShortcutsTable::setFilter(QString filter) {
this->shortcutsFilter = filter;
refreshShortcuts();
}
void ShortcutsTable::refreshShortcuts() {
keysModel->clear();
keysModel->setHorizontalHeaderItem(0, new QStandardItem(tr("Action")));
keysModel->setHorizontalHeaderItem(1, new QStandardItem(tr("Shortcut")));
QMapIterator it(Settings::actionKeys);
while (it.hasNext()) {
it.next();
if (!shortcutsFilter.isEmpty()
&& !Settings::actionKeys.value(it.key())->text().toLower().contains(shortcutsFilter.toLower())) {
continue;
}
addRow(it.key(), Settings::actionKeys.value(it.key())->text(),
Settings::actionKeys.value(it.key())->shortcut().toString());
}
setColumnHidden(2, true);
}
phototonic-3.3.0/ShortcutsTable.h 0000664 0000000 0000000 00000002761 15271130355 0017032 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2018 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef SHORTCUTS_TABLE_H
#define SHORTCUTS_TABLE_H
class QMenu;
class QStandardItemModel;
#include
class ShortcutsTable : public QTableView {
Q_OBJECT
public:
ShortcutsTable();
void addRow(QString action, QString description, QString shortcut);
void refreshShortcuts();
public slots:
void setFilter(QString filter);
void showShortcutPopupMenu(QPoint point);
void clearSelectedShortcut();
protected:
void keyPressEvent(QKeyEvent *keyEvent);
private:
bool confirmOverwriteShortcut(QString action, QString shortcut);
QStandardItemModel *keysModel;
QModelIndex selectedEntry;
QMenu *shortcutsMenu;
QAction *clearAction;
QString shortcutsFilter;
};
#endif // SHORTCUTS_TABLE_H
phototonic-3.3.0/SmartCrop.cpp 0000664 0000000 0000000 00000027001 15271130355 0016323 0 ustar 00root root 0000000 0000000 #include "SmartCrop.h"
#include
#include
#include
namespace SmartCrop {
static inline qreal cie(qreal r, qreal g, qreal b) {
return 0.5126 * b + 0.7152 * g + 0.0722 * r;
}
static inline qreal sample(const uchar *id, int p) {
return cie(id[p], id[p + 1], id[p + 2]);
}
static void edgeDetect(const QImage &i, QImage &o) {
const int obpl = o.bytesPerLine();
const int bpl = i.bytesPerLine();
const uchar *id = i.constBits();
uchar *obits = const_cast(o.constBits());
const int h = i.height();
for (int y = 0; y < h; ++y) {
uchar *od = obits + (y * obpl);
for (int x = 0; x < i.width(); ++x) {
int p = y * bpl + x * 4;
qreal lightness;
if (x == 0 || x >= i.width() - 1 || y == 0 || y >= h - 1) {
lightness = sample(id, p);
} else {
lightness = sample(id, p) * 4. -
sample(id, p - bpl) -
sample(id, p - 4) -
sample(id, p + 4) -
sample(id, p + bpl);
}
od[x * 4 + 1] = qMax(lightness, 0);
}
}
}
static qreal skinColor(const CropOptions &options, qreal r,qreal g, qreal b) {
qreal mag = sqrt(r * r + g * g + b * b);
if (Q_UNLIKELY(mag == 0.)) {
return 0.;
}
qreal rd = r / mag - options.skinColor[0];
qreal gd = g / mag - options.skinColor[1];
qreal bd = b / mag - options.skinColor[2];
qreal d = sqrt(rd * rd + gd * gd + bd * bd);
return 1 - d;
}
static void skinDetect(const CropOptions &options, const QImage &i, QImage &o) {
int w = i.width();
int h = i.height();
const int ibpl = i.bytesPerLine();
const int obpl = o.bytesPerLine();
const uchar *ibits = i.constBits();
uchar *obits = const_cast(o.constBits());
for (int y = 0; y < h; ++y) {
const uchar *id = ibits + (y * ibpl);
uchar *od = obits + (y * obpl);
for (int x = 0; x < w; ++x) {
int p = x * 4;
qreal lightness = cie(id[p], id[p + 1], id[p + 2]) / 255.;
qreal skin = skinColor(options, id[p], id[p + 1], id[p + 2]);
bool isSkinColor = skin > options.skinThreshold;
bool isSkinBrightness =
lightness >= options.skinBrightnessMin &&
lightness <= options.skinBrightnessMax;
if (isSkinColor && isSkinBrightness) {
od[p] =
(skin - options.skinThreshold) *
(255. / (1. - options.skinThreshold));
} else {
od[p] = 0;
}
}
}
}
static qreal saturation(qreal r, qreal g, qreal b) {
qreal maximum = qMax(r / 255., qMax(g / 255., b / 255.));
qreal minimum = qMin(r / 255., qMin(g / 255., b / 255.));
if (qFuzzyCompare(maximum, minimum)) {
return 0;
}
qreal l = (maximum + minimum) / 2.;
qreal d = maximum - minimum;
return l > 0.5 ? d / (2. - maximum - minimum) : d / (maximum + minimum);
}
static void saturationDetect(const CropOptions &options, const QImage &i, QImage &o) {
int w = i.width();
int h = i.height();
const int ibpl = i.bytesPerLine();
const int obpl = o.bytesPerLine();
const uchar *ibits = i.constBits();
uchar *obits = const_cast(o.constBits());
for (int y = 0; y < h; ++y) {
const uchar *id = ibits + (y * ibpl);
uchar *od = obits + (y * obpl);
for (int x = 0; x < w; ++x) {
int p = x * 4;
qreal lightness = cie(id[p], id[p + 1], id[p + 2]) / 255.;
qreal sat = saturation(id[p], id[p + 1], id[p + 2]);
bool acceptableSaturation = sat > options.saturationThreshold;
bool acceptableLightness =
lightness >= options.saturationBrightnessMin &&
lightness <= options.saturationBrightnessMax;
if (acceptableLightness && acceptableSaturation) {
od[p + 2] =
(sat - options.saturationThreshold) *
(255. / (1 - options.saturationThreshold));
} else {
od[p + 2] = 0;
}
}
}
}
static QImage downSample(QImage &input, qreal factor) {
int width = qFloor(input.width() / factor);
int height = qFloor(input.height() / factor);
QImage output(width, height, QImage::Format_RGBA8888);
qreal ifactor2 = 1. / (factor * factor);
const int ibpl = input.bytesPerLine();
const int obpl = output.bytesPerLine();
const uchar *ibits = input.constBits();
uchar *obits = const_cast(output.constBits());
for (int y = 0; y < height; ++y) {
uchar *data = obits + (y * obpl);
for (int x = 0; x < width; ++x) {
int i = x * 4;
qreal r = 0;
qreal g = 0;
qreal b = 0;
qreal a = 0;
qreal mr = 0;
qreal mg = 0;
for (int v = 0; v < factor; ++v) {
const uchar *idata = ibits + ibpl*(int(y * factor) + v);
for (int u = 0; u < factor; ++u) {
int j = (x * factor + u) * 4;
r += idata[j];
g += idata[j + 1];
b += idata[j + 2];
a += idata[j + 3];
mr = qMax(mr, qreal(idata[j]));
mg = qMax(mg, qreal(idata[j + 1]));
}
}
// this is some funky magic to preserve detail a bit more for
// skin (r) and detail (g). Saturation (b) does not get this boost.
data[i] = r * ifactor2 * 0.5 + mr * 0.5;
data[i + 1] = g * ifactor2 * 0.7 + mg * 0.3;
data[i + 2] = b * ifactor2;
data[i + 3] = a * ifactor2;
}
}
return output;
}
struct ScoreResult {
};
// Gets value in the range of [0, 1] where 0 is the center of the pictures
// returns weight of rule of thirds [0, 1]
static qreal thirds(qreal x) {
x = ((int(x - 1 / 3 + 1.0) % 2) * 0.5 - 0.5) * 16;
return qMax(1.0 - x * x, 0.0);
}
static inline qreal importance(const CropOptions &options, const QRectF &crop, qreal x, qreal y) {
if (
crop.x() > x ||
x >= crop.x() + crop.width() ||
crop.y() > y ||
y >= crop.y() + crop.height()
) {
return options.outsideImportance;
}
x = (x - crop.x()) / qreal(crop.width());
y = (y - crop.y()) / qreal(crop.height());
qreal px = abs(0.5 - x) * 2.;
qreal py = abs(0.5 - y) * 2.;
// Distance from edge
qreal dx = qMax(px - 1.0 + options.edgeRadius, 0);
qreal dy = qMax(py - 1.0 + options.edgeRadius, 0);
qreal d = (dx * dx + dy * dy) * options.edgeWeight;
qreal s = 1.41 - sqrt(px * px + py * py);
if (options.ruleOfThirds) {
s += qMax(0., s + d + 0.5) * 1.2 * (thirds(px) + thirds(py));
}
return s + d;
}
static QList generateCrops(const CropOptions &options, qreal width, qreal height) {
QList results;
int minDimension = qMin(width, height);
qreal cropWidth = options.cropWidth > 0 ? options.cropWidth : minDimension;
qreal cropHeight = options.cropHeight > 0 ? options.cropHeight : minDimension;
for (
qreal scale = options.maxScale;
scale >= options.minScale;
scale -= options.scaleStep
) {
for (qreal y = 0; y + cropHeight * scale <= height; y += options.step) {
for (qreal x = 0; x + cropWidth * scale <= width; x += options.step) {
results.append({x, y, cropWidth * scale, cropHeight * scale});
}
}
}
return results;
}
static float score(const CropOptions &options, const QImage &output, const QRectF &crop) {
qreal detail = 0;
qreal saturation = 0;
qreal skin = 0;
qreal boost = 0;
qreal downSample = options.scoreDownSample;
qreal invDownSample = 1. / downSample;
qreal outputHeightDownSample = output.height() * downSample;
qreal outputWidthDownSample = output.width() * downSample;
const int bpl = output.bytesPerLine();
const uchar *bits = output.constBits();
for (int y = 0; y < outputHeightDownSample; y += downSample) {
const uchar *od = bits + (qFloor(y * invDownSample) * bpl);
for (int x = 0; x < outputWidthDownSample; x += downSample) {
int p = (qFloor(x * invDownSample)) * 4;
qreal i = importance(options, crop, x, y);
qreal dtl = od[p + 1] / 255.;
skin += (od[p] / 255.) * (dtl + options.skinBias) * i;
detail += dtl * i;
saturation +=
(od[p + 2] / 255) * (dtl + options.saturationBias) * i;
boost += (od[p + 3] / 255.) * i;
}
}
return
(detail * options.detailWeight +
skin * options.skinWeight +
saturation * options.saturationWeight +
boost * options.boostWeight) /
(crop.width() * crop.height());
}
QRect smartCropRect(const QImage &input, CropOptions options)
{
if (input.isNull()) {
qWarning() << "Invalid image";
return input.rect();
}
if (options.aspect) {
options.width = options.aspect;
options.height = 1;
}
QImage image = input;
qreal scale = 1;
qreal prescale = 1;
if (options.width && options.height) {
scale = qMin(
image.width() / options.width,
image.height() / options.height
);
options.cropWidth = qFloor(options.width * scale);
options.cropHeight = qFloor(options.height * scale);
// Img = 100x100, width = 95x95, scale = 100/95, 1/scale > min
// don't set minscale smaller than 1/scale
// -> don't pick crops that need upscaling
options.minScale = qMin(
options.maxScale,
qMax(1 / scale, options.minScale)
);
// prescale if possible
if (options.prescale != false) {
prescale = qMin(qMax(256. / image.width(), 256. / image.height()), 1.);
if (prescale < 1) {
image = image.scaled(image.width() * prescale, image.height () * prescale);
options.cropWidth = qFloor(options.cropWidth * prescale);
options.cropHeight = qFloor(options.cropHeight * prescale);
} else {
prescale = 1;
}
}
}
image = image.convertToFormat(QImage::Format_RGBA8888);
QImage filtered = image.copy();
if (filtered.isNull()) {
qWarning() << "Failed to copy image!";
return input.rect();
}
edgeDetect(image, filtered);
skinDetect(options, image, filtered);
saturationDetect(options, image, filtered);
QImage toScore = downSample(filtered, options.scoreDownSample);
QList crops = generateCrops(options, image.width(), image.height());
QRectF topCrop;
qreal topScore = -1;
for (const QRectF &crop : crops) {
float scr = score(options, toScore, crop);
if (scr > topScore || topCrop.isEmpty()) {
topCrop = crop;
topScore = scr;
}
}
return QRectF(topCrop.x() / prescale, topCrop.y() / prescale, topCrop.width() / prescale, topCrop.height() / prescale).toAlignedRect();
}
QImage crop(const QImage &input, CropOptions options)
{
if (input.isNull()) {
qWarning() << "Invalid image";
return input;
}
return input.copy(smartCropRect(input, options));
}
} // namespace SmartCrop
phototonic-3.3.0/SmartCrop.h 0000664 0000000 0000000 00000002504 15271130355 0015771 0 ustar 00root root 0000000 0000000 #ifndef SMARTCROP_H
#define SMARTCROP_H
#pragma once
// Algorithm from https://github.com/jwagner/smartcrop.js/
#include
namespace SmartCrop {
struct CropOptions {
CropOptions(const QSize &targetSize) : width(targetSize.width()), height(targetSize.height()) {}
CropOptions() = default;
qreal width = 0;
qreal height= 0;
qreal aspect= 0;
qreal cropWidth= 0;
qreal cropHeight= 0;
qreal detailWeight= 0.2;
qreal skinColor[3] = {0.78, 0.57, 0.44};
qreal skinBias= 0.01;
qreal skinBrightnessMin= 0.2;
qreal skinBrightnessMax= 0.9;
qreal skinThreshold= 0.8;
qreal skinWeight= 1.8;
qreal saturationBrightnessMin= 0.05;
qreal saturationBrightnessMax= 0.9;
qreal saturationThreshold= 0.4;
qreal saturationBias= 0.2;
qreal saturationWeight= 0.1;
// Step * minscale rounded down to the next power of two should be good
qreal scoreDownSample= 8;
qreal step= 8;
qreal scaleStep= 0.1;
qreal minScale= 1.0;
qreal maxScale= 1.0;
qreal edgeRadius= 0.4;
qreal edgeWeight= -20.0;
qreal outsideImportance= -0.5;
qreal boostWeight= 100.0;
bool ruleOfThirds= true;
bool prescale= true;
};
QImage crop(const QImage &input, CropOptions options);
QRect smartCropRect(const QImage &input, CropOptions options);
}
#endif // SMARTCROP_H phototonic-3.3.0/Tags.cpp 0000664 0000000 0000000 00000060020 15271130355 0015305 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2015 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "MessageBox.h"
#include "MetadataCache.h"
#include "Settings.h"
#include "Tags.h"
#define BLOCK_RECURSION QSignalBlocker blocker(tagsTree);
#if __cplusplus >= 202002L
#define _LCD_ =,this
#else
#define _LCD_ =
#endif
enum { NewTag = Qt::UserRole + 1, InScope };
ImageTags::ImageTags(QWidget *parent) : QWidget(parent) {
m_populated = false;
m_needToSort =false;
tagsTree = new QListWidget;
tagsTree->setDragEnabled(false);
tagsTree->setSortingEnabled(true);
tabs = new QTabBar(this);
tabs->addTab(tr("Selection"));
tabs->addTab(tr("Filter"));
tabs->setTabIcon(0, QIcon(":/images/tag_yellow.png"));
tabs->setTabIcon(1, QIcon(":/images/tag_filter_off.png"));
tabs->setExpanding(false);
connect(tabs, &QTabBar::currentChanged, this, [this](int idx) { idx ? showTagsFilter() : showSelectedImagesTags(); });
QToolButton *btn = new QToolButton;
btn->setToolTip(tr("Show only library tags"));
m_tagGroup = 3;
btn->setIcon(QIcon(":/images/tag_multi.png"));
connect (btn, &QToolButton::clicked, this, [_LCD_]() {
if (m_tagGroup == 3) {
m_tagGroup = 1;
btn->setIcon(QIcon(":/images/tag_grey.png"));
btn->setToolTip(tr("Show only relevant tags"));
} else if (m_tagGroup == 1) {
m_tagGroup = 2;
btn->setIcon(QIcon(":/images/tag_red.png"));
btn->setToolTip(tr("Show all tags"));
} else {
m_tagGroup = 3;
btn->setIcon(QIcon(":/images/tag_multi.png"));
btn->setToolTip(tr("Show only library tags"));
}
if (tabs->currentIndex() == 0)
showSelectedImagesTags();
});
tabs->setTabButton(0, QTabBar::RightSide, btn);
btn = new QToolButton;
btn->setToolTip(tr("Clear Filters"));
btn->setIcon(QIcon::fromTheme("edit-delete", QIcon(":/images/edit-delete.png")));
connect (btn, &QToolButton::clicked, this, &ImageTags::clearTagFilters);
tabs->setTabButton(1, QTabBar::RightSide, btn);
btn->setEnabled(false);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->setContentsMargins(0, 3, 0, 0);
mainLayout->setSpacing(0);
mainLayout->addWidget(tabs);
mainLayout->addWidget(tagsTree);
setLayout(mainLayout);
currentDisplayMode = SelectionTagsDisplay;
tagsTree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(tagsTree, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showMenu(QPoint)));
addToSelectionAction = new QAction(tr("Tag"), this);
addToSelectionAction->setIcon(QIcon(":/images/tag_yellow.png"));
connect(addToSelectionAction, SIGNAL(triggered()), this, SLOT(addTagsToSelection()));
removeFromSelectionAction = new QAction(tr("Untag"), this);
connect(removeFromSelectionAction, SIGNAL(triggered()), this, SLOT(removeTagsFromSelection()));
actionAddTag = new QAction(tr("New Tag"), this);
actionAddTag->setIcon(QIcon(":/images/new_tag.png"));
connect(actionAddTag, SIGNAL(triggered()), this, SLOT(addNewTag()));
learnTagAction = new QAction(tr("Add to library"), this);
connect(learnTagAction, SIGNAL(triggered()), this, SLOT(learnTags()));
removeTagAction = new QAction(tr("Remove from library"), this);
removeTagAction->setIcon(QIcon::fromTheme("edit-delete", QIcon(":/images/edit-delete.png")));
connect(removeTagAction, SIGNAL(triggered()), this, SLOT(removeTags()));
actionClearTagsFilter = new QAction(tr("Clear Filters"), this);
actionClearTagsFilter->setIcon(QIcon(":/images/tag_filter_off.png"));
connect(actionClearTagsFilter, SIGNAL(triggered()), this, SLOT(clearTagFilters()));
negateAction = new QAction(this);
negateAction->setCheckable(true);
connect(negateAction, &QAction::triggered, this, [this]() {applyTagFiltering();});
tagsMenu = new QMenu("");
tagsMenu->addAction(addToSelectionAction);
tagsMenu->addAction(removeFromSelectionAction);
tagsMenu->addSeparator();
tagsMenu->addAction(learnTagAction);
tagsMenu->addAction(actionAddTag);
tagsMenu->addAction(removeTagAction);
tagsMenu->addSeparator();
tagsMenu->addAction(actionClearTagsFilter);
tagsMenu->addAction(negateAction);
QObject::connect(tagsTree, &QListWidget::itemChanged, this, [this](QListWidgetItem *item) {
BLOCK_RECURSION
if (currentDisplayMode == DirectoryTagsDisplay)
applyTagFiltering(item);
else
applyUserAction(QList() << item);
});
}
void ImageTags::sortTags() {
if (!isVisible()) {
m_needToSort = true;
return; // the below is slow AF for large lists
}
static QTimer *bouncer = nullptr;
if (!bouncer) {
bouncer = new QTimer(this);
bouncer->setSingleShot(true);
bouncer->setInterval(250);
connect (bouncer, &QTimer::timeout, this, [this]() {
BLOCK_RECURSION
tagsTree->sortItems(Qt::AscendingOrder);
m_needToSort = false;
});
}
bouncer->start();
}
void ImageTags::showMenu(QPoint point) {
QListWidgetItem *item = tagsTree->itemAt(point);
addToSelectionAction->setEnabled(item && item->checkState() == Qt::Unchecked);
removeFromSelectionAction->setEnabled(item && item->checkState() == Qt::Checked);
removeTagAction->setEnabled(item && !item->data(NewTag).toBool());
learnTagAction->setEnabled(item && item->data(NewTag).toBool());
bool noSelection = m_mandatoryFilterTags.isEmpty() && m_sufficientFilterTags.isEmpty();
negateAction->setText(noSelection ? tr("Show untagged") : tr("Invert filter"));
actionClearTagsFilter->setEnabled(!noSelection);
tagsMenu->popup(tagsTree->viewport()->mapToGlobal(point));
}
void ImageTags::showEvent(QShowEvent *event) {
QWidget::showEvent(event);
if (m_needToSort)
sortTags();
}
void ImageTags::setTagIcon(QListWidgetItem *tagItem, TagIcon icon) {
BLOCK_RECURSION
static QIcon grey(":/images/tag_grey.png"),
yellow(":/images/tag_yellow.png"),
multi(":/images/tag_multi.png"),
red(":/images/tag_red.png"),
on(":/images/tag_filter_on.png"),
off(":/images/tag_filter_off.png"),
negate(":/images/tag_filter_negate.png");
switch (icon) {
case TagIconDisabled:
tagItem->setIcon(tagItem->data(NewTag).toBool() ? red : grey);
break;
case TagIconEnabled:
tagItem->setIcon(tagItem->data(NewTag).toBool() ? red : yellow);
break;
case TagIconMultiple:
tagItem->setIcon(multi);
break;
case TagIconNew:
tagItem->setData(NewTag, true);
tagItem->setIcon(red);
break;
case TagIconFilterEnabled:
tagItem->setIcon(on);
break;
case TagIconFilterDisabled:
tagItem->setIcon(off);
break;
case TagIconFilterNegate:
tagItem->setIcon(negate);
break;
}
}
QListWidgetItem* ImageTags::addTag(QString tagName, bool tagChecked, TagIcon icon) {
BLOCK_RECURSION
QListWidgetItem *tagItem = new QListWidgetItem();
tagItem->setText(tagName);
tagItem->setCheckState(tagChecked ? Qt::Checked : Qt::Unchecked);
if (currentDisplayMode == DirectoryTagsDisplay) {
setTagIcon(tagItem, tagChecked ? TagIconFilterEnabled : TagIconFilterDisabled);
tagItem->setFlags(tagItem->flags() | Qt::ItemIsUserCheckable|Qt::ItemIsUserTristate);
// setToolTip(tagItem);
} else {
setTagIcon(tagItem, icon);
}
tagsTree->addItem(tagItem);
return tagItem;
}
void ImageTags::addTagsFor(const QStringList &files) {
BLOCK_RECURSION
bool dunnit = false;
for (const QString &file : files) {
size_t hash = qHash(file);
if (m_trackedFiles.contains(hash))
continue;
m_trackedFiles << hash;
QSet tags = Metadata::tags(file);
for (auto tag = tags.cbegin(), end = tags.cend(); tag != end; ++tag) {
QList present = tagsTree->findItems(*tag, Qt::MatchExactly);
if (present.isEmpty()) {
QListWidgetItem *item = addTag(*tag, false, TagIconNew);
item->setData(NewTag, true);
item->setData(InScope, 1);
dunnit = true;
} else {
for (QListWidgetItem *item : present) {
item->setData(InScope, item->data(InScope).toInt() + 1);
}
}
}
}
if (dunnit)
sortTags();
}
void ImageTags::removeTagsFor(const QStringList &files) {
BLOCK_RECURSION
for (const QString &file : files) {
m_trackedFiles.removeOne(qHash(file));
QSet tags = Metadata::tags(file);
for (auto tag = tags.cbegin(), end = tags.cend(); tag != end; ++tag) {
QList present = tagsTree->findItems(*tag, Qt::MatchExactly);
if (present.isEmpty())
continue;
for (QListWidgetItem *item : present) {
if (!item->data(NewTag).toBool())
continue;
const int scope = item->data(InScope).toInt() - 1;
if (scope <= 0)
delete tagsTree->takeItem(tagsTree->row(item));
else
item->setData(InScope, scope);
}
}
}
}
void ImageTags::setSelectedFiles(const QStringList &files) {
m_selectedFiles = files;
if (isVisible() && currentDisplayMode == SelectionTagsDisplay)
showSelectedImagesTags();
}
void ImageTags::showSelectedImagesTags() {
BLOCK_RECURSION
QStringList selectedThumbs = m_selectedFiles;
setActiveViewMode(SelectionTagsDisplay);
tagsTree->setSelectionMode(QAbstractItemView::ExtendedSelection);
if (!m_deathRow.isEmpty()) {
for (int i = tagsTree->count() - 1; i > -1; --i) {
QListWidgetItem *item = tagsTree->item(i);
if (m_deathRow.contains(item->text()))
delete tagsTree->takeItem(tagsTree->row(item));
}
m_deathRow.clear();
}
int selectedThumbsNum = selectedThumbs.size();
QMap tagsCount;
for (int i = 0; i < selectedThumbsNum; ++i) {
QSetIterator imageTagsIter(Metadata::tags(selectedThumbs.at(i)));
while (imageTagsIter.hasNext()) {
QString imageTag = imageTagsIter.next();
tagsCount[imageTag]++;
if (tagsTree->findItems(imageTag, Qt::MatchExactly).isEmpty()) {
qDebug() << "meek: why is there an unknown tag during the selection?";
addTag(imageTag, true, TagIconNew);
}
}
}
bool imagesTagged = false, imagesTaggedMixed = false;
for (int i = 0; i < tagsTree->count(); ++i) {
QListWidgetItem *item = tagsTree->item(i);
bool newTag = item->data(NewTag).toBool();
// 1: library, 2: relevant
int flag = 0;
if (!newTag) // in library
flag |= 1;
if (item->data(InScope).toInt())
flag |= 2; // relevant
item->setHidden(!(m_tagGroup & flag));
QString tagName = item->text();
item->setSelected(m_selectedTags.contains(tagName));
int tagCountTotal = tagsCount.value(tagName, 0);
if (selectedThumbsNum == 0) {
item->setCheckState(Qt::Unchecked);
item->setFlags(item->flags() & ~(Qt::ItemIsUserCheckable|Qt::ItemIsUserTristate));
setTagIcon(item, newTag ? TagIconNew : TagIconDisabled);
} else if (tagCountTotal == selectedThumbsNum) {
item->setCheckState(Qt::Checked);
item->setFlags((item->flags() | Qt::ItemIsUserCheckable) & ~Qt::ItemIsUserTristate);
setTagIcon(item, newTag ? TagIconNew : TagIconEnabled);
imagesTagged = true;
} else if (tagCountTotal) {
item->setCheckState(Qt::PartiallyChecked);
item->setFlags((item->flags() | Qt::ItemIsUserCheckable) & ~Qt::ItemIsUserTristate);
setTagIcon(item, TagIconMultiple);
imagesTaggedMixed = true;
} else {
item->setCheckState(Qt::Unchecked);
item->setFlags((item->flags() | Qt::ItemIsUserCheckable) & ~Qt::ItemIsUserTristate);
setTagIcon(item, newTag ? TagIconNew : TagIconDisabled);
}
updateToolTip(item);
}
if (imagesTagged) {
tabs->setTabIcon(0, QIcon(":/images/tag_yellow.png"));
} else if (imagesTaggedMixed) {
tabs->setTabIcon(0, QIcon(":/images/tag_multi.png"));
} else {
tabs->setTabIcon(0, QIcon(":/images/tag_grey.png"));
}
addToSelectionAction->setEnabled(selectedThumbsNum ? true : false);
removeFromSelectionAction->setEnabled(selectedThumbsNum ? true : false);
// sortTags(); // see above meek
}
void ImageTags::updateToolTip(QListWidgetItem *item) {
BLOCK_RECURSION
static const QString mandatory = tr("Mandatory:");
static const QString sufficient = tr("Sufficient:");
static const QString mustnot = tr("The image must not have this tag");
static const QString must = tr("The image must have this tag");
static const QString mustany = tr("The image must have any of these tags");
if (currentDisplayMode == SelectionTagsDisplay || item->checkState() == Qt::Unchecked)
item->setToolTip(QString());
else if (item->checkState() == Qt::PartiallyChecked)
item->setToolTip(sufficient + "\n" + (negateAction->isChecked() ? mustnot : mustany));
else if (item->checkState() == Qt::Checked)
item->setToolTip(mandatory + "\n" + (negateAction->isChecked() ? mustnot : must));
}
void ImageTags::showTagsFilter() {
BLOCK_RECURSION
setActiveViewMode(DirectoryTagsDisplay);
m_selectedTags.clear();
for (int i = 0; i < tagsTree->count(); ++i) {
QListWidgetItem *item = tagsTree->item(i);
QString tagName = item->text();
if (item->isSelected()) {
m_selectedTags << tagName;
item->setSelected(false);
}
item->setFlags(item->flags() | Qt::ItemIsUserCheckable|Qt::ItemIsUserTristate);
if (m_mandatoryFilterTags.contains(tagName)) {
item->setCheckState(Qt::Checked);
setTagIcon(item, negateAction->isChecked() ? TagIconFilterNegate : TagIconFilterEnabled);
updateToolTip(item);
} else if (m_sufficientFilterTags.contains(tagName)) {
item->setCheckState(Qt::PartiallyChecked);
setTagIcon(item, negateAction->isChecked() ? TagIconFilterNegate : TagIconFilterEnabled);
updateToolTip(item);
} else if (!item->data(InScope).toBool()) {
item->setHidden(true);
} else {
item->setCheckState(Qt::Unchecked);
setTagIcon(item, TagIconFilterDisabled);
updateToolTip(item);
}
}
tagsTree->setSelectionMode(QAbstractItemView::SingleSelection);
sortTags();
}
void ImageTags::populateTagsTree() {
if (m_populated)
return;
BLOCK_RECURSION
// technically unnecessary now
tagsTree->clear();
// tagsTree->sortItems() on many unsorted items is slow AF, so we set the order ahead
tagsTree->sortItems(Qt::AscendingOrder);
// and pre-sort a list to speed that up *A LOT*
QList list(Settings::knownTags.cbegin(), Settings::knownTags.cend());
std::sort(list.begin(), list.end());
for (const QString &tag : list)
addTag(tag, false, TagIconDisabled);
if (currentDisplayMode == SelectionTagsDisplay) {
showSelectedImagesTags();
} else {
showTagsFilter();
}
sortTags();
m_populated = true;
}
void ImageTags::setActiveViewMode(TagsDisplayMode mode) {
BLOCK_RECURSION
currentDisplayMode = mode;
actionAddTag->setVisible(currentDisplayMode == SelectionTagsDisplay);
removeTagAction->setVisible(currentDisplayMode == SelectionTagsDisplay);
learnTagAction->setVisible(currentDisplayMode == SelectionTagsDisplay);
addToSelectionAction->setVisible(currentDisplayMode == SelectionTagsDisplay);
removeFromSelectionAction->setVisible(currentDisplayMode == SelectionTagsDisplay);
actionClearTagsFilter->setVisible(currentDisplayMode == DirectoryTagsDisplay);
negateAction->setVisible(currentDisplayMode == DirectoryTagsDisplay);
}
QStringList ImageTags::getCheckedTags(Qt::CheckState tagState) {
QStringList checkedTags;
for (int i = 0; i < tagsTree->count(); ++i) {
QListWidgetItem *item = tagsTree->item(i);
if (item->checkState() == tagState) {
checkedTags << item->text();
}
}
return checkedTags;
}
void ImageTags::applyTagFiltering(QListWidgetItem *item) {
BLOCK_RECURSION
TagIcon icon = negateAction->isChecked() ? TagIconFilterNegate : TagIconFilterEnabled;
if (item) {
if (item->checkState() == Qt::Unchecked &&
item->data(NewTag).toBool() &&
item->data(InScope).toInt() < 1) {
delete tagsTree->takeItem(tagsTree->row(item));
} else {
updateToolTip(item);
setTagIcon(item, item->checkState() == Qt::Unchecked ? TagIconFilterDisabled : icon);
}
} else { // inversion
for (int i = 0; i < tagsTree->count(); ++i) {
QListWidgetItem *item = tagsTree->item(i);
updateToolTip(item);
if (item->checkState() != Qt::Unchecked)
setTagIcon(item, icon);
}
}
m_mandatoryFilterTags = getCheckedTags(Qt::Checked);
m_sufficientFilterTags = getCheckedTags(Qt::PartiallyChecked);
tabs->tabButton(1, QTabBar::RightSide)->setEnabled(true);
if (m_mandatoryFilterTags.isEmpty() && m_sufficientFilterTags.isEmpty()) {
tabs->tabButton(1, QTabBar::RightSide)->setEnabled(false);
tabs->setTabIcon(1, QIcon(":/images/tag_filter_off.png"));
}
else if (negateAction->isChecked())
tabs->setTabIcon(1, QIcon(":/images/tag_filter_negate.png"));
else
tabs->setTabIcon(1, QIcon(":/images/tag_filter_on.png"));
emit filterChanged(m_mandatoryFilterTags, m_sufficientFilterTags, negateAction->isChecked());
}
void ImageTags::applyUserAction(QList tagsList) {
BLOCK_RECURSION
QStringList tagsAdded, tagsRemoved;
m_deathRow.clear();
for (int i = tagsList.size() - 1; i > -1; --i) {
QListWidgetItem *item = tagsList.at(i);
Qt::CheckState tagState = item->checkState();
TagIcon icon = TagIconDisabled;
if (item->data(NewTag).toBool())
icon = TagIconNew;
else if (tagState == Qt::Checked)
icon = TagIconEnabled;
setTagIcon(item, icon);
int scope = item->data(InScope).toInt();
if (tagState == Qt::Checked) {
tagsAdded << item->text();
++scope;
} else {
tagsRemoved << item->text();
--scope;
}
if (scope < 1 && item->data(NewTag).toBool() && // out of scope former transient tag
!m_mandatoryFilterTags.contains(item->text()) && // not used by either …
!m_sufficientFilterTags.contains(item->text())) { // … filter
m_deathRow << item->text();
item->setData(InScope, 0);
} else {
item->setData(InScope, qMax(0, scope));
}
}
emit tagRequest(tagsAdded, tagsRemoved);
}
void ImageTags::removeTagsFromSelection() {
BLOCK_RECURSION
for (int i = tagsTree->selectedItems().size() - 1; i > -1; --i) {
tagsTree->selectedItems().at(i)->setCheckState(Qt::Unchecked);
}
applyUserAction(tagsTree->selectedItems());
}
void ImageTags::addTagsToSelection() {
BLOCK_RECURSION
for (int i = tagsTree->selectedItems().size() - 1; i > -1; --i) {
tagsTree->selectedItems().at(i)->setCheckState(Qt::Checked);
}
applyUserAction(tagsTree->selectedItems());
}
void ImageTags::clearTagFilters() {
BLOCK_RECURSION
const bool juggle = currentDisplayMode != DirectoryTagsDisplay;
if (juggle) {
setUpdatesEnabled(false);
showTagsFilter();
}
for (int i = 0; i < tagsTree->count(); ++i)
tagsTree->item(i)->setCheckState(Qt::Unchecked);
applyTagFiltering();
if (juggle) {
showSelectedImagesTags();
setUpdatesEnabled(true);
}
}
void ImageTags::addNewTag() {
bool ok;
QString title = tr("Add a new tag");
QString newTagName = QInputDialog::getText(this, title, tr("Enter new tag name"),
QLineEdit::Normal, "", &ok);
if (!ok) {
return;
}
if (newTagName.isEmpty()) {
return MessageBox(this).critical(tr("Error"), tr("No name entered"));
}
BLOCK_RECURSION
QSetIterator knownTagsIt(Settings::knownTags);
while (knownTagsIt.hasNext()) {
QString tag = knownTagsIt.next();
if (newTagName == tag) {
return MessageBox(this).critical(tr("Error"), tr("Tag %1 already exists").arg(newTagName));
}
}
addTag(newTagName, false, TagIconDisabled);
Settings::knownTags.insert(newTagName);
sortTags();
}
void ImageTags::removeTags() {
if (!tagsTree->selectedItems().size()) {
return;
}
if (MessageBox(this, MessageBox::Yes|MessageBox::Cancel, MessageBox::Cancel).warning(
tr("Delete tag"), tr("Delete %n selected tags(s)?", "", tagsTree->selectedItems().size()))
!= MessageBox::Yes) {
return;
}
BLOCK_RECURSION
bool removedTagWasChecked = false;
for (int i = tagsTree->selectedItems().size() - 1; i > -1; --i) {
QListWidgetItem *item = tagsTree->selectedItems().at(i);
QString tagName = item->text();
Settings::knownTags.remove(tagName);
if (m_mandatoryFilterTags.removeOne(tagName) | m_sufficientFilterTags.removeOne(tagName))
removedTagWasChecked = true;
if (item->data(InScope).toBool())
setTagIcon(item, TagIconNew);
else
delete tagsTree->takeItem(tagsTree->row(item));
}
if (removedTagWasChecked) {
applyTagFiltering();
}
}
void ImageTags::removeTransientTags() {
BLOCK_RECURSION
m_trackedFiles.clear();
for (int i = tagsTree->count() - 1; i > -1; --i) {
QListWidgetItem *item = tagsTree->item(i);
if (!item->data(NewTag).toBool() ||
m_mandatoryFilterTags.contains(item->text()) ||
m_sufficientFilterTags.contains(item->text())) {
item->setData(InScope, 0);
continue;
}
delete tagsTree->takeItem(i);
}
}
void ImageTags::learnTags() {
if (!tagsTree->selectedItems().size()) {
return;
}
BLOCK_RECURSION
for (int i = 0; i < tagsTree->selectedItems().size(); ++i) {
QListWidgetItem *item = tagsTree->selectedItems().at(i);
QString tagName = item->text();
item->setData(NewTag, false);
if (item->checkState() == Qt::Unchecked)
setTagIcon(item, TagIconDisabled);
else if (item->checkState() == Qt::Checked)
setTagIcon(item, TagIconEnabled);
// tristate is the multi-icon, we ignore that
Settings::knownTags.insert(tagName);
}
}
phototonic-3.3.0/Tags.h 0000664 0000000 0000000 00000006022 15271130355 0014754 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#ifndef TAGS_H
#define TAGS_H
class QTabBar;
class QListWidget;
class QListWidgetItem;
#include
enum TagsDisplayMode {
DirectoryTagsDisplay,
SelectionTagsDisplay
};
enum TagIcon {
TagIconDisabled,
TagIconEnabled,
TagIconMultiple,
TagIconNew,
TagIconFilterDisabled,
TagIconFilterEnabled,
TagIconFilterNegate
};
class ImageTags : public QWidget {
Q_OBJECT
public:
ImageTags(QWidget *parent);
QListWidgetItem* addTag(QString tagName, bool tagChecked, TagIcon icon);
void addTagsFor(const QStringList &files);
void removeTagsFor(const QStringList &files);
void populateTagsTree();
void removeTransientTags();
void showTagsFilter();
/// @todo - detangle this
TagsDisplayMode currentDisplayMode; // phototonic.cpp
public slots:
void setSelectedFiles(const QStringList &files);
void showSelectedImagesTags();
protected:
void showEvent(QShowEvent *event) override;
private:
void applyUserAction(QList tagsList);
QStringList getCheckedTags(Qt::CheckState tagState);
void setActiveViewMode(TagsDisplayMode mode);
void setTagIcon(QListWidgetItem *tagItem, TagIcon icon);
void updateToolTip(QListWidgetItem *item);
void sortTags();
QStringList m_selectedFiles;
QStringList m_mandatoryFilterTags;
QStringList m_sufficientFilterTags;
QStringList m_deathRow;
QAction *actionAddTag;
QAction *addToSelectionAction;
QAction *removeFromSelectionAction;
QAction *actionClearTagsFilter;
QAction *negateAction;
QAction *learnTagAction;
QAction *removeTagAction;
QTabBar *tabs;
QMenu *tagsMenu;
QListWidget *tagsTree;
bool m_populated;
bool m_needToSort;
QList m_trackedFiles;
QStringList m_selectedTags;
char m_tagGroup;
private slots:
void addNewTag();
void addTagsToSelection();
void applyTagFiltering(QListWidgetItem *item = nullptr);
void clearTagFilters();
void learnTags();
void removeTags();
void removeTagsFromSelection();
void showMenu(QPoint point);
signals:
void filterChanged(const QStringList &mandatory, const QStringList &sufficient, bool invert);
void tagRequest(const QStringList &tagsAdded, const QStringList &tagsRemoved);
};
#endif // TAGS_H
phototonic-3.3.0/ThumbsViewer.cpp 0000664 0000000 0000000 00000231674 15271130355 0017052 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2013-2014 Ofer Kashayov
* This file is part of Phototonic Image Viewer.
*
* Phototonic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phototonic 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 Phototonic. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include