pax_global_header 0000666 0000000 0000000 00000000064 14761273276 0014531 g ustar 00root root 0000000 0000000 52 comment=34f8b43ce2043e151df3e51d0cb9bff239f72a1b
qimgv-master/ 0000775 0000000 0000000 00000000000 14761273276 0013511 5 ustar 00root root 0000000 0000000 qimgv-master/.github/ 0000775 0000000 0000000 00000000000 14761273276 0015051 5 ustar 00root root 0000000 0000000 qimgv-master/.github/workflows/ 0000775 0000000 0000000 00000000000 14761273276 0017106 5 ustar 00root root 0000000 0000000 qimgv-master/.github/workflows/build-package.yml 0000664 0000000 0000000 00000003312 14761273276 0022320 0 ustar 00root root 0000000 0000000 name: msys2 dev-latest
on: [workflow_dispatch]
#on:
# push:
# branches:
# - dev
jobs:
build:
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
steps:
- uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: git p7zip
- uses: actions/checkout@v4
with:
#ref: dev
fetch-depth: 0
- id: build
name: CI-Build
run: |
export BUILD_NAME="qimgv-x64_$(git describe --tags)"
echo "build_name=${BUILD_NAME}" >> $GITHUB_OUTPUT
echo "build_file_name=${BUILD_NAME}.7z" >> $GITHUB_OUTPUT
./scripts/build-qimgv.sh
pwd
ls -al
echo "running: 7z a qimgv-x64.7z ./${BUILD_NAME}"
7z a qimgv-x64.7z ./${BUILD_NAME}
- uses: actions/upload-artifact@v4
with:
name: qimgv-build
path: qimgv-x64.7z
outputs:
build_name: ${{ steps.build.outputs.build_name }}
build_file_name: ${{ steps.build.outputs.build_file_name }}
upload-release:
runs-on: ubuntu-latest
needs: build
steps:
#- run: echo "${{ needs.build.outputs.build_name }}"
- uses: actions/download-artifact@v4
with:
name: qimgv-build
- name: Rename archive
run: mv qimgv-x64.7z "${{ needs.build.outputs.build_file_name }}"
- uses: softprops/action-gh-release@v2
#if: startsWith(github.ref, 'refs/tags/')
with:
files: ${{ needs.build.outputs.build_file_name }}
prerelease: true
tag_name: latest-dev
name: ${{ needs.build.outputs.build_name }}
body: "Automated build"
qimgv-master/.gitignore 0000664 0000000 0000000 00000000347 14761273276 0015505 0 ustar 00root root 0000000 0000000 .kdev4/
*.txt
!CMakeLists.txt
!msys2-build-deps.txt
!msys2-dll-deps.txt
#build*
.kdev_include_paths
*.xmi
*.kdev*
.dir*
*.orig
build
qrc_resources.cpp
debug/
release/
*.debug
*.depends
*.release
*.user
ui_settingsdialog.h
Makefile
qimgv-master/CMakeLists.txt 0000664 0000000 0000000 00000004046 14761273276 0016255 0 ustar 00root root 0000000 0000000 # qimgv root
cmake_minimum_required(VERSION 3.13)
project(qimgv
VERSION 1.0.2
HOMEPAGE_URL "https://github.com/easymodo/qimgv"
LANGUAGES CXX)
message(STATUS "Build configuration: " ${CMAKE_BUILD_TYPE})
# check for gcc
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.0)
message(FATAL_ERROR "\n!!! THIS PROJECT REQUIRES GCC 9.0 OR LATER !!!\n")
endif()
# AUTOMOC
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# USER OPTIONS
# Usage: cmake -DVIDEO_SUPPORT=ON [...]
option(EXIV2 "For reading/writing exif tags" ON)
option(VIDEO_SUPPORT "Enable video support" ON)
option(OPENCV_SUPPORT "Enable HQ scaling via OpenCV" ON)
option(KDE_SUPPORT "Support blur when using KDE" OFF)
if(UNIX AND NOT APPLE)
set(QT_EXTERN_PATH "" CACHE STRING "Tell compile external QT path, example: (/opt/Qt/6.2.0/gcc_64)")
string(COMPARE EQUAL "${QT_EXTERN_PATH}" "" result)
if (NOT result)
set(CMAKE_INSTALL_RPATH "${QT_EXTERN_PATH}/lib")
endif()
endif()
# FIND PACKAGES
find_package(Qt5 COMPONENTS Widgets QUIET)
if(Qt5_FOUND)
find_package(QT NAMES Qt5 REQUIRED COMPONENTS Core Widgets Svg PrintSupport)
else()
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core Widgets Svg PrintSupport OpenGLWidgets)
endif()
message(STATUS "Qt Version: " ${QT_VERSION})
if(QT_VERSION_MAJOR GREATER_EQUAL 6)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Widgets Svg PrintSupport OpenGLWidgets)
else()
find_package(Qt${QT_VERSION_MAJOR} 5.12 REQUIRED COMPONENTS Core Widgets Svg PrintSupport)
endif()
if(EXIV2)
find_package(PkgConfig REQUIRED)
pkg_check_modules(Exiv2 REQUIRED IMPORTED_TARGET exiv2)
endif()
if(KDE_SUPPORT)
find_package(KF5WindowSystem REQUIRED)
endif()
if(OPENCV_SUPPORT)
find_package(PkgConfig REQUIRED)
find_package(OpenCV REQUIRED core imgproc)
endif()
##############################################################
add_subdirectory(qimgv)
if(VIDEO_SUPPORT)
add_subdirectory(plugins/player_mpv)
endif()
qimgv-master/LICENSE 0000664 0000000 0000000 00000104461 14761273276 0014524 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.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
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:
{project} Copyright (C) {year} {fullname}
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
.
qimgv-master/README.md 0000664 0000000 0000000 00000013635 14761273276 0015000 0 ustar 00root root 0000000 0000000 ## :exclamation: Updates may be slow due to war in Ukraine :sunflower: :sunflower: :sunflower:
qimgv | Current version: 1.0.2
=====
Image viewer. Fast, easy to use. Optional video support.
## Screenshots
Main window & panel | Folder view | Settings window
:-------------------------:|:-------------------------:|:-------------------------:|
[](qimgv/distrib/screenshots/qimgv0.9_1.jpg?raw=true) | [](qimgv/distrib/screenshots/qimgv0.9_2.jpg?raw=true) | [](qimgv/distrib/screenshots/qimgv_3.jpg?raw=true)
## Key features:
- Simple UI
- Fast
- Easy to use
- Fully configurable, including themes, shortcuts
- High quality scaling
- Basic image editing: Crop, Rotate and Resize
- Ability to quickly copy / move images to different folders
- Experimental video playback via libmpv
- Folder view mode
- Ability to run shell scripts
## Default control scheme:
| Action | Shortcut |
| ------------- | ------------- |
| Next image | Right arrow / MouseWheel |
| Previous image | Left arrow / MouseWheel |
| Goto first image | Home |
| Goto last image | End |
| Zoom in | Ctrl+MouseWheel / Crtl+Up |
| Zoom out | Ctrl+MouseWheel / Crtl+Down |
| Zoom (alt. method) | Hold right mouse button & move up / down |
| Fit mode: window | 1 |
| Fit mode: width | 2 |
| Fit mode: 1:1 (no scaling) | 3 |
| Switch fit modes | Space |
| Toggle fullscreen mode | DoubleClick / F / F11 |
| Exit fullscreen mode | Esc |
| Show EXIF panel | I |
| Crop image | X |
| Resize image | R |
| Rotate left | Ctrl+L |
| Rotate Right | Ctrl+R |
| Open containing directory | Ctrl+D |
| Slideshow mode | ~ |
| Shuffle mode | Ctrl+~ |
| Quick copy | C |
| Quick move | M |
| Move to trash | Delete |
| Delete file | Shift+Delete |
| Save | Ctrl+S |
| Save As | Ctrl+Shift+S |
| Folder view | Enter / Backspace |
| Open | Ctrl+O |
| Print / Export PDF | Ctrl+P |
| Settings | P |
| Exit application | Esc / Ctrl+Q / Alt+X / MiddleClick |
... and more.
Note: you can configure every shortcut by going to __Settings > Controls__
# User interface
The idea is to have a uncluttered, simple and easy to use UI. You can see UI elements only when you need them.
There is a pull-down panel with thumbnails, as well as folder view. You can also bring up a context menu via right click.
## Using quick copy / quick move panels
Bring up the panel with C or M shortcut. You will see 9 destination directories, click on the folder icon to change them.
With panel visible, use 1 - 9 keys to copy/move current image to corresponding directory.
When you are done press C or M again to hide the panel.
## Running scripts
You can run custom scripts on a current image.
Open __Settings > Scripts__. Press Add. Here you can choose between a shell command and a shell script.
Example of a command:
`convert %file% %file%_.pdf`
Example of a shell script file (`$1` will be image path):
```
#!/bin/bash
gimp "$1"
```
_Note: The script file must be an executable. Also, "shebang" (`#!/bin/bash`) needs to be present._
When you've created your script go to __Settings > Controls > Add__, then select it and assign a shortcut like for any regular action.
## HiDPI (Linux / MacOS only)
If qimgv appears too small / too big on your display, you can override the scale factor. Example:
```
QT_SCALE_FACTOR="1.5" qimgv /path/to/image.png
```
You can put it in `qimgv.desktop` file to make it permanent. Using values less than `1.0` is not supported.
qimgv should also obey the global scale factor set in KDE's systemsettings.
## High quality scaling
qimgv supports nicer scaling filters when compiled with `opencv` support (ON by default, but might vary depending on your linux distribution). Filter options are available in __Settings > Scaling__. `Bicubic` or `bilinear+sharpen` is recommended.
# Additional image formats
qimgv can open some extra formats via third-party image plugins. All of them are included with windows package.
| Format | Plugin |
| ------- | ------------- |
| JPEG-XL | [github.com/novomesk/qt-jpegxl-image-plugin](https://github.com/novomesk/qt-jpegxl-image-plugin) |
| AVIF | [github.com/novomesk/qt-avif-image-plugin](https://github.com/novomesk/qt-avif-image-plugin) |
| APNG | [github.com/Skycoder42/QtApng](https://github.com/Skycoder42/QtApng) |
| HEIF / HEIC | [github.com/jakar/qt-heif-image-plugin](https://github.com/jakar/qt-heif-image-plugin) |
| RAW | [https://gitlab.com/mardy/qtraw](https://gitlab.com/mardy/qtraw) |
# Installation
## Windows
Windows builds are portable (everything is contained within the install folder). The installer also sets up file associations.
_NOTE: `-video` variants include mpv for video support_
Grab the latest version from the [releases page](https://github.com/easymodo/qimgv/releases)
Alternatively you can install it with Chocolatey:
```
choco install qimgv
```
Or WinGet:
```
winget install --id easymodo.qimgv
```
## GNU+Linux
### Arch Linux / Manjaro / etc.
AUR package:
```
qimgv-git
```
### Ubuntu / Linux Mint / Pop!\_OS / etc.
```
sudo apt install qimgv
```
### Fedora
```
sudo dnf install qimgv
```
### OpenSUSE
```
zypper install qimgv
```
### Gentoo
```
emerge qimgv
```
### Void linux
```
xbps-install -S qimgv
```
### Alpine Linux
```
apk add qimgv
```
## BSD
### FreeBSD
```
pkg install qimgv
```
This list may be incomplete.
## Compiling from source
See [Compiling qimgv from source](https://github.com/easymodo/qimgv/wiki/Compiling-qimgv-from-source) on the wiki
# Donate
If you wish to give me a few bucks, please consider donating to the Ukrainian Army instead:
[https://savelife.in.ua/en/donate-en/#donate-army-card-once](https://savelife.in.ua/en/donate-en/#donate-army-card-once)
[https://u24.gov.ua/](https://u24.gov.ua/)
This directly increases the chances of me being able to work on this in future
qimgv-master/plugins/ 0000775 0000000 0000000 00000000000 14761273276 0015172 5 ustar 00root root 0000000 0000000 qimgv-master/plugins/player_mpv/ 0000775 0000000 0000000 00000000000 14761273276 0017350 5 ustar 00root root 0000000 0000000 qimgv-master/plugins/player_mpv/CMakeLists.txt 0000664 0000000 0000000 00000003165 14761273276 0022115 0 ustar 00root root 0000000 0000000 cmake_minimum_required(VERSION 3.11)
project(player_mpv
DESCRIPTION "video player widget for qimgv (using mpv)"
LANGUAGES CXX)
set(CMAKE_AUTOMOC ON)
# only export CreatePlayerWidget function
ADD_DEFINITIONS(-DQIMGV_PLAYER_MPV_LIBRARY)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Widgets)
if(NOT WIN32)
find_package(PkgConfig REQUIRED)
pkg_check_modules(Mpv REQUIRED IMPORTED_TARGET mpv)
endif()
include(GNUInstallDirs)
add_library(player_mpv MODULE
src/videoplayer.cpp
src/mpvwidget.cpp
src/videoplayermpv.cpp
src/qthelper.hpp)
target_compile_features(player_mpv PRIVATE cxx_std_11)
if(WIN32)
target_link_libraries(player_mpv PRIVATE
Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Widgets Mpv)
else()
target_link_libraries(player_mpv PRIVATE
Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Widgets PkgConfig::Mpv)
endif()
if(QT_VERSION_MAJOR GREATER_EQUAL 6)
target_link_libraries(player_mpv PRIVATE Qt${QT_VERSION_MAJOR}::OpenGLWidgets)
endif()
set_target_properties(player_mpv PROPERTIES
CXX_EXTENSIONS OFF
PREFIX "")
target_include_directories(player_mpv PRIVATE src)
if(WIN32)
target_include_directories(player_mpv PRIVATE
${MPV_DIR}/include)
target_link_directories(player_mpv PRIVATE
${MPV_DIR}/lib/$,x86_64,i686>)
endif()
if(WIN32)
install(TARGETS player_mpv LIBRARY DESTINATION "${CMAKE_INSTALL_BINDIR}/plugins")
else()
install(TARGETS player_mpv LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}/qimgv")
endif()
qimgv-master/plugins/player_mpv/src/ 0000775 0000000 0000000 00000000000 14761273276 0020137 5 ustar 00root root 0000000 0000000 qimgv-master/plugins/player_mpv/src/mpvwidget.cpp 0000664 0000000 0000000 00000013454 14761273276 0022660 0 ustar 00root root 0000000 0000000 #include "mpvwidget.h"
#include
static void wakeup(void *ctx) {
QMetaObject::invokeMethod((MpvWidget*)ctx, "on_mpv_events", Qt::QueuedConnection);
}
static void *get_proc_address(void *ctx, const char *name) {
Q_UNUSED(ctx);
QOpenGLContext *glctx = QOpenGLContext::currentContext();
if (!glctx)
return nullptr;
return reinterpret_cast(glctx->getProcAddress(QByteArray(name)));
}
MpvWidget::MpvWidget(QWidget *parent, Qt::WindowFlags f)
: QOpenGLWidget(parent, f)
{
mpv = mpv_create();
if(!mpv)
throw std::runtime_error("could not create mpv context");
this->setAttribute(Qt::WA_TransparentForMouseEvents, true);
//mpv_set_option_string(mpv, "terminal", "yes");
//mpv_set_option_string(mpv, "msg-level", "all=v");
mpv_set_option_string(mpv, "vo", "libmpv");
if (mpv_initialize(mpv) < 0)
throw std::runtime_error("could not initialize mpv context");
// Request hw decoding, just for testing.
mpv::qt::set_property(mpv, "hwdec", "auto");
//mpv::qt::set_property(mpv, "video-unscaled", "downscale-big");
// Loop video
setRepeat(true);
// Unmute
setMuted(false);
mpv_observe_property(mpv, 0, "duration", MPV_FORMAT_DOUBLE);
mpv_observe_property(mpv, 0, "time-pos", MPV_FORMAT_DOUBLE);
mpv_observe_property(mpv, 0, "pause", MPV_FORMAT_FLAG);
mpv_set_wakeup_callback(mpv, wakeup, this);
}
MpvWidget::~MpvWidget() {
makeCurrent();
if (mpv_gl)
mpv_render_context_free(mpv_gl);
mpv_terminate_destroy(mpv);
}
void MpvWidget::command(const QVariant& params) {
mpv::qt::command(mpv, params);
}
void MpvWidget::setProperty(const QString& name, const QVariant& value) {
mpv::qt::set_property(mpv, name, value);
}
QVariant MpvWidget::getProperty(const QString &name) const {
return mpv::qt::get_property(mpv, name);
}
void MpvWidget::setOption(const QString& name, const QVariant& value) {
mpv::qt::set_property(mpv, name, value);
}
void MpvWidget::initializeGL() {
mpv_opengl_init_params gl_init_params{get_proc_address, nullptr};
mpv_render_param params[]{
{MPV_RENDER_PARAM_API_TYPE, const_cast(MPV_RENDER_API_TYPE_OPENGL)},
{MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params},
{MPV_RENDER_PARAM_INVALID, nullptr}
};
if(mpv_render_context_create(&mpv_gl, mpv, params) < 0)
throw std::runtime_error("failed to initialize mpv GL context");
mpv_render_context_set_update_callback(mpv_gl, MpvWidget::on_update, reinterpret_cast(this));
}
void MpvWidget::paintGL() {
mpv_opengl_fbo mpfbo{static_cast(defaultFramebufferObject()), width(), height(), 0};
int flip_y{1};
mpv_render_param params[] = {
{MPV_RENDER_PARAM_OPENGL_FBO, &mpfbo},
{MPV_RENDER_PARAM_FLIP_Y, &flip_y},
{MPV_RENDER_PARAM_INVALID, nullptr}
};
// See render_gl.h on what OpenGL environment mpv expects, and
// other API details.
mpv_render_context_render(mpv_gl, params);
}
void MpvWidget::on_mpv_events() {
// Process all events, until the event queue is empty.
while (mpv) {
mpv_event *event = mpv_wait_event(mpv, 0);
if (event->event_id == MPV_EVENT_NONE) {
break;
}
handle_mpv_event(event);
}
}
void MpvWidget::handle_mpv_event(mpv_event *event) {
switch (event->event_id) {
case MPV_EVENT_PROPERTY_CHANGE: {
mpv_event_property *prop = reinterpret_cast(event->data);
if(strcmp(prop->name, "time-pos") == 0) {
if (prop->format == MPV_FORMAT_DOUBLE) {
double time = *reinterpret_cast(prop->data);
emit positionChanged(static_cast(time));
}
} else if(strcmp(prop->name, "duration") == 0) {
if(prop->format == MPV_FORMAT_DOUBLE) {
double time = *reinterpret_cast(prop->data);
emit durationChanged(static_cast(time));
} else if(prop->format == MPV_FORMAT_NONE) {
emit playbackFinished();
}
} else if(strcmp(prop->name, "pause") == 0) {
int mode = *reinterpret_cast(prop->data);
emit videoPaused(mode == 1);
}
break;
}
default: ;
// Ignore uninteresting or unknown events.
}
}
// Make Qt invoke mpv_render_context_render() to draw a new/updated video frame.
void MpvWidget::maybeUpdate() {
// If the Qt window is not visible, Qt's update() will just skip rendering.
// This confuses mpv's render API, and may lead to small occasional
// freezes due to video rendering timing out.
// Handle this by manually redrawing.
// Note: Qt doesn't seem to provide a way to query whether update() will
// be skipped, and the following code still fails when e.g. switching
// to a different workspace with a reparenting window manager.
if(window()->isMinimized()) {
makeCurrent();
paintGL();
context()->swapBuffers(context()->surface());
doneCurrent();
} else {
update();
}
}
void MpvWidget::on_update(void *ctx) {
QMetaObject::invokeMethod((MpvWidget*)ctx, "maybeUpdate");
}
void MpvWidget::setMuted(bool mode) {
if(mode)
mpv::qt::set_property(mpv, "mute", "yes");
else
mpv::qt::set_property(mpv, "mute", "no");
}
bool MpvWidget::muted() {
return mpv::qt::get_property_variant(mpv, "mute").toBool();
}
int MpvWidget::volume() {
return mpv::qt::get_property_variant(mpv, "volume").toInt();
}
void MpvWidget::setVolume(int vol) {
qBound(0, vol, 100);
mpv::qt::set_property_variant(mpv, "volume", vol);
}
void MpvWidget::setRepeat(bool mode) {
if(mode)
mpv::qt::set_property(mpv, "loop-file", "inf");
else
mpv::qt::set_property(mpv, "loop-file", "no");
}
qimgv-master/plugins/player_mpv/src/mpvwidget.h 0000664 0000000 0000000 00000003115 14761273276 0022316 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include
#include
#include "qthelper.hpp"
#include
#include
#include
#include
class MpvWidget Q_DECL_FINAL: public QOpenGLWidget {
Q_OBJECT
public:
MpvWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::Widget);
~MpvWidget() override;
void command(const QVariant& params);
void setOption(const QString &name, const QVariant &value);
void setProperty(const QString& name, const QVariant& value);
QVariant getProperty(const QString& name) const;
// Related to this:
// https://github.com/gnome-mpv/gnome-mpv/issues/245
// Let's hope this wont break more than it fixes
int width() const {
return static_cast(QOpenGLWidget::width() * this->devicePixelRatioF());
}
int height() const {
return static_cast(QOpenGLWidget::height() * this->devicePixelRatioF());
}
void setMuted(bool mode);
void setRepeat(bool mode);
bool muted();
int volume();
void setVolume(int vol);
signals:
void durationChanged(int value);
void positionChanged(int value);
void videoPaused(bool);
void playbackFinished();
protected:
void initializeGL() override;
void paintGL() override;
private slots:
void on_mpv_events();
void maybeUpdate();
private:
void handle_mpv_event(mpv_event *event);
static void on_update(void *ctx);
mpv_handle *mpv;
mpv_render_context *mpv_gl;
};
qimgv-master/plugins/player_mpv/src/nogl/ 0000775 0000000 0000000 00000000000 14761273276 0021076 5 ustar 00root root 0000000 0000000 qimgv-master/plugins/player_mpv/src/nogl/mpvwidget.cpp 0000664 0000000 0000000 00000007475 14761273276 0023625 0 ustar 00root root 0000000 0000000 #include "mpvwidget.h"
#include
static void wakeup(void *ctx) {
QMetaObject::invokeMethod((MpvWidget*)ctx, "on_mpv_events", Qt::QueuedConnection);
}
MpvWidget::MpvWidget(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
mpv = mpv_create();
if(!mpv)
throw std::runtime_error("could not create mpv context");
int64_t wid = parent->winId();
mpv_set_option(mpv, "wid", MPV_FORMAT_INT64, &wid);
this->setAttribute(Qt::WA_TransparentForMouseEvents, true);
mpv_set_option_string(mpv, "input-cursor", "no"); // no mouse handling
mpv_set_option_string(mpv, "cursor-autohide", "no");// no cursor-autohide, we handle that
//mpv_set_option_string(mpv, "terminal", "yes");
//mpv_set_option_string(mpv, "msg-level", "all=v");
// Request hw decoding, just for testing.
mpv::qt::set_property(mpv, "hwdec", "auto");
//mpv::qt::set_property(mpv, "video-unscaled", "downscale-big");
// Loop video
setRepeat(true);
// Unmute
setMuted(false);
mpv_observe_property(mpv, 0, "duration", MPV_FORMAT_DOUBLE);
mpv_observe_property(mpv, 0, "time-pos", MPV_FORMAT_DOUBLE);
mpv_observe_property(mpv, 0, "pause", MPV_FORMAT_FLAG);
mpv_set_wakeup_callback(mpv, wakeup, this);
if (mpv_initialize(mpv) < 0)
throw std::runtime_error("could not initialize mpv context");
}
MpvWidget::~MpvWidget() {
mpv_terminate_destroy(mpv);
}
void MpvWidget::command(const QVariant& params) {
mpv::qt::command(mpv, params);
}
void MpvWidget::setProperty(const QString& name, const QVariant& value) {
mpv::qt::set_property(mpv, name, value);
}
QVariant MpvWidget::getProperty(const QString &name) const {
return mpv::qt::get_property(mpv, name);
}
void MpvWidget::setOption(const QString& name, const QVariant& value) {
mpv::qt::set_property(mpv, name, value);
}
void MpvWidget::on_mpv_events() {
// Process all events, until the event queue is empty.
while (mpv) {
mpv_event *event = mpv_wait_event(mpv, 0);
if (event->event_id == MPV_EVENT_NONE) {
break;
}
handle_mpv_event(event);
}
}
void MpvWidget::handle_mpv_event(mpv_event *event) {
switch (event->event_id) {
case MPV_EVENT_PROPERTY_CHANGE: {
mpv_event_property *prop = reinterpret_cast(event->data);
if(strcmp(prop->name, "time-pos") == 0) {
if (prop->format == MPV_FORMAT_DOUBLE) {
double time = *reinterpret_cast(prop->data);
emit positionChanged(static_cast(time));
}
} else if(strcmp(prop->name, "duration") == 0) {
if(prop->format == MPV_FORMAT_DOUBLE) {
double time = *reinterpret_cast(prop->data);
emit durationChanged(static_cast(time));
} else if(prop->format == MPV_FORMAT_NONE) {
emit playbackFinished();
}
} else if(strcmp(prop->name, "pause") == 0) {
int mode = *reinterpret_cast(prop->data);
emit videoPaused(mode == 1);
}
break;
}
default: ;
// Ignore uninteresting or unknown events.
}
}
void MpvWidget::setMuted(bool mode) {
if(mode)
mpv::qt::set_property(mpv, "mute", "yes");
else
mpv::qt::set_property(mpv, "mute", "no");
}
bool MpvWidget::muted() {
return mpv::qt::get_property_variant(mpv, "mute").toBool();
}
int MpvWidget::volume() {
return mpv::qt::get_property_variant(mpv, "volume").toInt();
}
void MpvWidget::setVolume(int vol) {
qBound(0, vol, 100);
mpv::qt::set_property_variant(mpv, "volume", vol);
}
void MpvWidget::setRepeat(bool mode) {
if(mode)
mpv::qt::set_property(mpv, "loop-file", "inf");
else
mpv::qt::set_property(mpv, "loop-file", "no");
}
qimgv-master/plugins/player_mpv/src/nogl/mpvwidget.h 0000664 0000000 0000000 00000001724 14761273276 0023261 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include "qthelper.hpp"
#include
#include
#include
#include
#include
class MpvWidget Q_DECL_FINAL : public QWidget {
Q_OBJECT
public:
MpvWidget(QWidget *parent = nullptr, Qt::WindowFlags f = Qt::Widget);
~MpvWidget() override;
void command(const QVariant& params);
void setOption(const QString &name, const QVariant &value);
void setProperty(const QString& name, const QVariant& value);
QVariant getProperty(const QString& name) const;
void setMuted(bool mode);
void setRepeat(bool mode);
bool muted();
int volume();
void setVolume(int vol);
signals:
void durationChanged(int value);
void positionChanged(int value);
void videoPaused(bool);
void playbackFinished();
private slots:
void on_mpv_events();
private:
void handle_mpv_event(mpv_event *event);
mpv_handle *mpv;
};
qimgv-master/plugins/player_mpv/src/nogl/videoplayermpv.cpp 0000664 0000000 0000000 00000006753 14761273276 0024663 0 ustar 00root root 0000000 0000000 #include "videoplayermpv.h"
#include "mpvwidget.h"
#include
#include
#include
#include
// TODO: window flashes white when opening a video (straight from file manager)
VideoPlayerMpv::VideoPlayerMpv(QWidget *parent) : VideoPlayer(parent) {
setAttribute(Qt::WA_TranslucentBackground, true);
setMouseTracking(true);
m_mpv = new MpvWidget(this);
QVBoxLayout *vl = new QVBoxLayout();
vl->setContentsMargins(0,0,0,0);
vl->addWidget(m_mpv);
setLayout(vl);
setFocusPolicy(Qt::NoFocus);
m_mpv->setFocusPolicy(Qt::NoFocus);
readSettings();
//connect(settings, SIGNAL(settingsChanged()), this, SLOT(readSettings()));
connect(m_mpv, SIGNAL(durationChanged(int)), this, SIGNAL(durationChanged(int)));
connect(m_mpv, SIGNAL(positionChanged(int)), this, SIGNAL(positionChanged(int)));
connect(m_mpv, SIGNAL(videoPaused(bool)), this, SIGNAL(videoPaused(bool)));
connect(m_mpv, SIGNAL(playbackFinished()), this, SIGNAL(playbackFinished()));
}
bool VideoPlayerMpv::showVideo(QString file) {
if(file.isEmpty())
return false;
m_mpv->command(QStringList() << "loadfile" << file);
setPaused(false);
return true;
}
void VideoPlayerMpv::seek(int pos) {
m_mpv->command(QVariantList() << "seek" << pos << "absolute");
//qDebug() << "seek(): " << pos << " sec";
}
void VideoPlayerMpv::seekRelative(int pos) {
m_mpv->command(QVariantList() << "seek" << pos << "relative");
//qDebug() << "seekRelative(): " << pos << " sec";
}
void VideoPlayerMpv::pauseResume() {
const bool paused = m_mpv->getProperty("pause").toBool();
setPaused(!paused);
}
void VideoPlayerMpv::frameStep() {
m_mpv->command(QVariantList() << "frame-step");
}
void VideoPlayerMpv::frameStepBack() {
m_mpv->command(QVariantList() << "frame-back-step");
}
void VideoPlayerMpv::stop() {
m_mpv->command(QVariantList() << "stop");
}
void VideoPlayerMpv::setPaused(bool mode) {
m_mpv->setProperty("pause", mode);
}
void VideoPlayerMpv::setMuted(bool mode) {
m_mpv->setMuted(mode);
}
bool VideoPlayerMpv::muted() {
return m_mpv->muted();
}
void VideoPlayerMpv::volumeUp() {
m_mpv->setVolume(m_mpv->volume() + 5);
}
void VideoPlayerMpv::volumeDown() {
m_mpv->setVolume(m_mpv->volume() - 5);
}
void VideoPlayerMpv::setVolume(int vol) {
m_mpv->setVolume(vol);
}
int VideoPlayerMpv::volume() {
return m_mpv->volume();
}
void VideoPlayerMpv::setVideoUnscaled(bool mode) {
if(mode)
m_mpv->setOption("video-unscaled", "downscale-big");
else
m_mpv->setOption("video-unscaled", "no");
}
void VideoPlayerMpv::paintEvent(QPaintEvent *event) {
Q_UNUSED(event)
}
void VideoPlayerMpv::readSettings() {
//setMuted(!settings->playVideoSounds());
//setVideoUnscaled(!settings->expandImage());
}
void VideoPlayerMpv::mousePressEvent(QMouseEvent *event) {
// different platforms, double-click the mouse to judge inconsistencies
QWidget::mousePressEvent(event);
event->ignore();
}
void VideoPlayerMpv::mouseMoveEvent(QMouseEvent *event) {
QWidget::mouseMoveEvent(event);
event->ignore();
}
void VideoPlayerMpv::mouseReleaseEvent(QMouseEvent *event) {
QWidget::mouseReleaseEvent(event);
event->ignore();
}
void VideoPlayerMpv::show() {
QWidget::show();
}
void VideoPlayerMpv::hide() {
QWidget::hide();
}
void VideoPlayerMpv::setLoopPlayback(bool mode) {
m_mpv->setRepeat(mode);
}
VideoPlayer *CreatePlayerWidget() {
return new VideoPlayerMpv();
}
qimgv-master/plugins/player_mpv/src/nogl/videoplayermpv.h 0000664 0000000 0000000 00000002231 14761273276 0024313 0 ustar 00root root 0000000 0000000 #pragma once
#include "videoplayer.h"
#include
#if defined QIMGV_PLAYER_MPV_LIBRARY
#define TEST_COMMON_DLLSPEC Q_DECL_EXPORT
#else
#define TEST_COMMON_DLLSPEC Q_DECL_IMPORT
#endif
class MpvWidget;
class VideoPlayerMpv : public VideoPlayer {
Q_OBJECT
public:
explicit VideoPlayerMpv(QWidget *parent = nullptr);
bool showVideo(QString file);
void setVideoUnscaled(bool mode);
int volume();
public slots:
void seek(int pos);
void seekRelative(int pos);
void pauseResume();
void frameStep();
void frameStepBack();
void stop();
void setPaused(bool mode);
void setMuted(bool);
bool muted();
void volumeUp();
void volumeDown();
void setVolume(int);
void show();
void hide();
void setLoopPlayback(bool mode);
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
signals:
void playbackFinished();
private slots:
void readSettings();
private:
MpvWidget *m_mpv;
};
extern "C" TEST_COMMON_DLLSPEC VideoPlayer *CreatePlayerWidget();
qimgv-master/plugins/player_mpv/src/qthelper.hpp 0000664 0000000 0000000 00000024717 14761273276 0022507 0 ustar 00root root 0000000 0000000 #ifndef LIBMPV_QTHELPER_H_
#define LIBMPV_QTHELPER_H_
#include
#include
#include
#include
#include
#include
#include
#include
namespace mpv {
namespace qt {
// Wrapper around mpv_handle. Does refcounting under the hood.
class Handle
{
struct container {
container(mpv_handle *h) : mpv(h) {}
~container() { mpv_terminate_destroy(mpv); }
mpv_handle *mpv;
};
QSharedPointer sptr;
public:
// Construct a new Handle from a raw mpv_handle with refcount 1. If the
// last Handle goes out of scope, the mpv_handle will be destroyed with
// mpv_terminate_destroy().
// Never destroy the mpv_handle manually when using this wrapper. You
// will create dangling pointers. Just let the wrapper take care of
// destroying the mpv_handle.
// Never create multiple wrappers from the same raw mpv_handle; copy the
// wrapper instead (that's what it's for).
static Handle FromRawHandle(mpv_handle *handle) {
Handle h;
h.sptr = QSharedPointer(new container(handle));
return h;
}
// Return the raw handle; for use with the libmpv C API.
operator mpv_handle*() const { return sptr ? (*sptr).mpv : 0; }
};
static inline QVariant node_to_variant(const mpv_node *node)
{
switch (node->format) {
case MPV_FORMAT_STRING:
return QVariant(QString::fromUtf8(node->u.string));
case MPV_FORMAT_FLAG:
return QVariant(static_cast(node->u.flag));
case MPV_FORMAT_INT64:
return QVariant(static_cast(node->u.int64));
case MPV_FORMAT_DOUBLE:
return QVariant(node->u.double_);
case MPV_FORMAT_NODE_ARRAY: {
mpv_node_list *list = node->u.list;
QVariantList qlist;
for (int n = 0; n < list->num; n++)
qlist.append(node_to_variant(&list->values[n]));
return QVariant(qlist);
}
case MPV_FORMAT_NODE_MAP: {
mpv_node_list *list = node->u.list;
QVariantMap qmap;
for (int n = 0; n < list->num; n++) {
qmap.insert(QString::fromUtf8(list->keys[n]),
node_to_variant(&list->values[n]));
}
return QVariant(qmap);
}
default: // MPV_FORMAT_NONE, unknown values (e.g. future extensions)
return QVariant();
}
}
struct node_builder {
node_builder(const QVariant& v) {
set(&node_, v);
}
~node_builder() {
free_node(&node_);
}
mpv_node *node() { return &node_; }
private:
Q_DISABLE_COPY(node_builder)
mpv_node node_;
mpv_node_list *create_list(mpv_node *dst, bool is_map, int num) {
dst->format = is_map ? MPV_FORMAT_NODE_MAP : MPV_FORMAT_NODE_ARRAY;
mpv_node_list *list = new mpv_node_list();
dst->u.list = list;
if (!list)
goto err;
list->values = new mpv_node[num]();
if (!list->values)
goto err;
if (is_map) {
list->keys = new char*[num]();
if (!list->keys)
goto err;
}
return list;
err:
free_node(dst);
return NULL;
}
char *dup_qstring(const QString &s) {
QByteArray b = s.toUtf8();
char *r = new char[b.size() + 1];
if (r)
std::memcpy(r, b.data(), b.size() + 1);
return r;
}
bool test_type(const QVariant &v, QMetaType::Type t) {
// The Qt docs say: "Although this function is declared as returning
// "QVariant::Type(obsolete), the return value should be interpreted
// as QMetaType::Type."
// So a cast really seems to be needed to avoid warnings (urgh).
return static_cast(v.type()) == static_cast(t);
}
void set(mpv_node *dst, const QVariant &src) {
if (test_type(src, QMetaType::QString)) {
dst->format = MPV_FORMAT_STRING;
dst->u.string = dup_qstring(src.toString());
if (!dst->u.string)
goto fail;
} else if (test_type(src, QMetaType::Bool)) {
dst->format = MPV_FORMAT_FLAG;
dst->u.flag = src.toBool() ? 1 : 0;
} else if (test_type(src, QMetaType::Int) ||
test_type(src, QMetaType::LongLong) ||
test_type(src, QMetaType::UInt) ||
test_type(src, QMetaType::ULongLong))
{
dst->format = MPV_FORMAT_INT64;
dst->u.int64 = src.toLongLong();
} else if (test_type(src, QMetaType::Double)) {
dst->format = MPV_FORMAT_DOUBLE;
dst->u.double_ = src.toDouble();
} else if (src.canConvert()) {
QVariantList qlist = src.toList();
mpv_node_list *list = create_list(dst, false, qlist.size());
if (!list)
goto fail;
list->num = qlist.size();
for (int n = 0; n < qlist.size(); n++)
set(&list->values[n], qlist[n]);
} else if (src.canConvert()) {
QVariantMap qmap = src.toMap();
mpv_node_list *list = create_list(dst, true, qmap.size());
if (!list)
goto fail;
list->num = qmap.size();
for (int n = 0; n < qmap.size(); n++) {
list->keys[n] = dup_qstring(qmap.keys()[n]);
if (!list->keys[n]) {
free_node(dst);
goto fail;
}
set(&list->values[n], qmap.values()[n]);
}
} else {
goto fail;
}
return;
fail:
dst->format = MPV_FORMAT_NONE;
}
void free_node(mpv_node *dst) {
switch (dst->format) {
case MPV_FORMAT_STRING:
delete[] dst->u.string;
break;
case MPV_FORMAT_NODE_ARRAY:
case MPV_FORMAT_NODE_MAP: {
mpv_node_list *list = dst->u.list;
if (list) {
for (int n = 0; n < list->num; n++) {
if (list->keys)
delete[] list->keys[n];
if (list->values)
free_node(&list->values[n]);
}
delete[] list->keys;
delete[] list->values;
}
delete list;
break;
}
default: ;
}
dst->format = MPV_FORMAT_NONE;
}
};
/**
* RAII wrapper that calls mpv_free_node_contents() on the pointer.
*/
struct node_autofree {
mpv_node *ptr;
node_autofree(mpv_node *a_ptr) : ptr(a_ptr) {}
~node_autofree() { mpv_free_node_contents(ptr); }
};
/**
* Return the given property as mpv_node converted to QVariant, or QVariant()
* on error.
*
* @deprecated use get_property() instead
*
* @param name the property name
*/
static inline QVariant get_property_variant(mpv_handle *ctx, const QString &name)
{
mpv_node node;
if (mpv_get_property(ctx, name.toUtf8().data(), MPV_FORMAT_NODE, &node) < 0)
return QVariant();
node_autofree f(&node);
return node_to_variant(&node);
}
/**
* Set the given property as mpv_node converted from the QVariant argument.
* @deprecated use set_property() instead
*/
static inline int set_property_variant(mpv_handle *ctx, const QString &name,
const QVariant &v)
{
node_builder node(v);
return mpv_set_property(ctx, name.toUtf8().data(), MPV_FORMAT_NODE, node.node());
}
/**
* Set the given option as mpv_node converted from the QVariant argument.
*
* @deprecated use set_property() instead
*/
static inline int set_option_variant(mpv_handle *ctx, const QString &name,
const QVariant &v)
{
node_builder node(v);
return mpv_set_option(ctx, name.toUtf8().data(), MPV_FORMAT_NODE, node.node());
}
/**
* mpv_command_node() equivalent. Returns QVariant() on error (and
* unfortunately, the same on success).
*
* @deprecated use command() instead
*/
static inline QVariant command_variant(mpv_handle *ctx, const QVariant &args)
{
node_builder node(args);
mpv_node res;
if (mpv_command_node(ctx, node.node(), &res) < 0)
return QVariant();
node_autofree f(&res);
return node_to_variant(&res);
}
/**
* This is used to return error codes wrapped in QVariant for functions which
* return QVariant.
*
* You can use get_error() or is_error() to extract the error status from a
* QVariant value.
*/
struct ErrorReturn
{
/**
* enum mpv_error value (or a value outside of it if ABI was extended)
*/
int error;
ErrorReturn() : error(0) {}
explicit ErrorReturn(int err) : error(err) {}
};
/**
* Return the mpv error code packed into a QVariant, or 0 (success) if it's not
* an error value.
*
* @return error code (<0) or success (>=0)
*/
static inline int get_error(const QVariant &v)
{
if (!v.canConvert())
return 0;
return v.value().error;
}
/**
* Return whether the QVariant carries a mpv error code.
*/
static inline bool is_error(const QVariant &v)
{
return get_error(v) < 0;
}
/**
* Return the given property as mpv_node converted to QVariant, or QVariant()
* on error.
*
* @param name the property name
* @return the property value, or an ErrorReturn with the error code
*/
static inline QVariant get_property(mpv_handle *ctx, const QString &name)
{
mpv_node node;
int err = mpv_get_property(ctx, name.toUtf8().data(), MPV_FORMAT_NODE, &node);
if (err < 0)
return QVariant::fromValue(ErrorReturn(err));
node_autofree f(&node);
return node_to_variant(&node);
}
/**
* Set the given property as mpv_node converted from the QVariant argument.
*
* @return mpv error code (<0 on error, >= 0 on success)
*/
static inline int set_property(mpv_handle *ctx, const QString &name,
const QVariant &v)
{
node_builder node(v);
return mpv_set_property(ctx, name.toUtf8().data(), MPV_FORMAT_NODE, node.node());
}
/**
* mpv_command_node() equivalent.
*
* @param args command arguments, with args[0] being the command name as string
* @return the property value, or an ErrorReturn with the error code
*/
static inline QVariant command(mpv_handle *ctx, const QVariant &args)
{
node_builder node(args);
mpv_node res;
int err = mpv_command_node(ctx, node.node(), &res);
if (err < 0)
return QVariant::fromValue(ErrorReturn(err));
node_autofree f(&res);
return node_to_variant(&res);
}
}
}
Q_DECLARE_METATYPE(mpv::qt::ErrorReturn)
#endif
qimgv-master/plugins/player_mpv/src/videoplayer.cpp 0000664 0000000 0000000 00000000341 14761273276 0023164 0 ustar 00root root 0000000 0000000 #include "videoplayer.h"
VideoPlayer::VideoPlayer(QWidget *parent) : QWidget(parent) {
setFocusPolicy(Qt::NoFocus);
}
void VideoPlayer::show() {
QWidget::show();
}
void VideoPlayer::hide() {
QWidget::hide();
}
qimgv-master/plugins/player_mpv/src/videoplayer.h 0000664 0000000 0000000 00000001701 14761273276 0022632 0 ustar 00root root 0000000 0000000 #pragma once
#include
class VideoPlayer : public QWidget {
Q_OBJECT
public:
explicit VideoPlayer(QWidget *parent = nullptr);
virtual bool showVideo(QString file) = 0;
virtual void seek(int pos) = 0;
virtual void seekRelative(int pos) = 0;
virtual void pauseResume() = 0;
virtual void frameStep() = 0;
virtual void frameStepBack() = 0;
virtual void stop() = 0;
virtual void setPaused(bool mode) = 0;
virtual void setMuted(bool) = 0;
virtual bool muted() = 0;
virtual void volumeUp() = 0;
virtual void volumeDown() = 0;
virtual void setVolume(int) = 0;
virtual int volume() = 0;
virtual void setVideoUnscaled(bool mode) = 0;
virtual void setLoopPlayback(bool mode) = 0;
signals:
void durationChanged(int value);
void positionChanged(int value);
void videoPaused(bool);
void playbackFinished();
public slots:
virtual void show();
virtual void hide();
};
qimgv-master/plugins/player_mpv/src/videoplayermpv.cpp 0000664 0000000 0000000 00000007114 14761273276 0023714 0 ustar 00root root 0000000 0000000 #include "videoplayermpv.h"
#include "mpvwidget.h"
#include
#include
#include
#include
// TODO: window flashes white when opening a video (straight from file manager)
VideoPlayerMpv::VideoPlayerMpv(QWidget *parent) : VideoPlayer(parent) {
setAttribute(Qt::WA_TranslucentBackground, true);
setMouseTracking(true);
m_mpv = new MpvWidget(this);
QVBoxLayout *vl = new QVBoxLayout();
vl->setContentsMargins(0,0,0,0);
vl->addWidget(m_mpv);
setLayout(vl);
setFocusPolicy(Qt::NoFocus);
m_mpv->setFocusPolicy(Qt::NoFocus);
readSettings();
//connect(settings, SIGNAL(settingsChanged()), this, SLOT(readSettings()));
connect(m_mpv, SIGNAL(durationChanged(int)), this, SIGNAL(durationChanged(int)));
connect(m_mpv, SIGNAL(positionChanged(int)), this, SIGNAL(positionChanged(int)));
connect(m_mpv, SIGNAL(videoPaused(bool)), this, SIGNAL(videoPaused(bool)));
connect(m_mpv, SIGNAL(playbackFinished()), this, SIGNAL(playbackFinished()));
}
bool VideoPlayerMpv::showVideo(QString file) {
if(file.isEmpty())
return false;
m_mpv->command(QStringList() << "loadfile" << file);
setPaused(false);
return true;
}
void VideoPlayerMpv::seek(int pos) {
m_mpv->command(QVariantList() << "seek" << pos << "absolute");
//qDebug() << "seek(): " << pos << " sec";
}
void VideoPlayerMpv::seekRelative(int pos) {
m_mpv->command(QVariantList() << "seek" << pos << "relative");
//qDebug() << "seekRelative(): " << pos << " sec";
}
void VideoPlayerMpv::pauseResume() {
const bool paused = m_mpv->getProperty("pause").toBool();
setPaused(!paused);
}
void VideoPlayerMpv::frameStep() {
m_mpv->command(QVariantList() << "frame-step");
}
void VideoPlayerMpv::frameStepBack() {
m_mpv->command(QVariantList() << "frame-back-step");
}
void VideoPlayerMpv::stop() {
m_mpv->command(QVariantList() << "stop");
}
void VideoPlayerMpv::setPaused(bool mode) {
m_mpv->setProperty("pause", mode);
}
void VideoPlayerMpv::setMuted(bool mode) {
m_mpv->setMuted(mode);
}
bool VideoPlayerMpv::muted() {
return m_mpv->muted();
}
void VideoPlayerMpv::volumeUp() {
m_mpv->setVolume(m_mpv->volume() + 5);
}
void VideoPlayerMpv::volumeDown() {
m_mpv->setVolume(m_mpv->volume() - 5);
}
void VideoPlayerMpv::setVolume(int vol) {
m_mpv->setVolume(vol);
}
int VideoPlayerMpv::volume() {
return m_mpv->volume();
}
void VideoPlayerMpv::setVideoUnscaled(bool mode) {
if(mode)
m_mpv->setOption("video-unscaled", "downscale-big");
else
m_mpv->setOption("video-unscaled", "no");
}
void VideoPlayerMpv::paintEvent(QPaintEvent *event) {
Q_UNUSED(event)
}
void VideoPlayerMpv::readSettings() {
//setMuted(!settings->playVideoSounds());
//setVideoUnscaled(!settings->expandImage());
}
void VideoPlayerMpv::mousePressEvent(QMouseEvent *event) {
if(event->button() == Qt::LeftButton && event->type() != QEvent::MouseButtonDblClick) {
event->accept();
this->pauseResume();
} else {
QWidget::mousePressEvent(event);
event->ignore();
}
}
void VideoPlayerMpv::mouseMoveEvent(QMouseEvent *event) {
QWidget::mouseMoveEvent(event);
event->ignore();
}
void VideoPlayerMpv::mouseReleaseEvent(QMouseEvent *event) {
QWidget::mouseReleaseEvent(event);
event->ignore();
}
void VideoPlayerMpv::show() {
QWidget::show();
}
void VideoPlayerMpv::hide() {
QWidget::hide();
}
void VideoPlayerMpv::setLoopPlayback(bool mode) {
m_mpv->setRepeat(mode);
}
VideoPlayer *CreatePlayerWidget() {
return new VideoPlayerMpv();
}
qimgv-master/plugins/player_mpv/src/videoplayermpv.h 0000664 0000000 0000000 00000002231 14761273276 0023354 0 ustar 00root root 0000000 0000000 #pragma once
#include "videoplayer.h"
#include
#if defined QIMGV_PLAYER_MPV_LIBRARY
#define TEST_COMMON_DLLSPEC Q_DECL_EXPORT
#else
#define TEST_COMMON_DLLSPEC Q_DECL_IMPORT
#endif
class MpvWidget;
class VideoPlayerMpv : public VideoPlayer {
Q_OBJECT
public:
explicit VideoPlayerMpv(QWidget *parent = nullptr);
bool showVideo(QString file);
void setVideoUnscaled(bool mode);
int volume();
public slots:
void seek(int pos);
void seekRelative(int pos);
void pauseResume();
void frameStep();
void frameStepBack();
void stop();
void setPaused(bool mode);
void setMuted(bool);
bool muted();
void volumeUp();
void volumeDown();
void setVolume(int);
void show();
void hide();
void setLoopPlayback(bool mode);
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
signals:
void playbackFinished();
private slots:
void readSettings();
private:
MpvWidget *m_mpv;
};
extern "C" TEST_COMMON_DLLSPEC VideoPlayer *CreatePlayerWidget();
qimgv-master/qimgv/ 0000775 0000000 0000000 00000000000 14761273276 0014634 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/3rdparty/ 0000775 0000000 0000000 00000000000 14761273276 0016404 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/3rdparty/QtOpenCV/ 0000775 0000000 0000000 00000000000 14761273276 0020043 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/3rdparty/QtOpenCV/CMakeLists.txt 0000664 0000000 0000000 00000000066 14761273276 0022605 0 ustar 00root root 0000000 0000000 target_sources(qimgv PRIVATE
cvmatandqimage.cpp
)
qimgv-master/qimgv/3rdparty/QtOpenCV/cvmatandqimage.cpp 0000664 0000000 0000000 00000036145 14761273276 0023541 0 ustar 00root root 0000000 0000000 /****************************************************************************
** Copyright (c) 2012-2015 Debao Zhang
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#include "cvmatandqimage.h"
#include
#include
#include
#include
#include
namespace QtOcv {
namespace {
/*ARGB <==> BGRA
*/
cv::Mat argb2bgra(const cv::Mat &mat)
{
Q_ASSERT(mat.channels()==4);
cv::Mat newMat(mat.rows, mat.cols, mat.type());
int from_to[] = {0,3, 1,2, 2,1, 3,0};
cv::mixChannels(&mat, 1, &newMat, 1, from_to, 4);
return newMat;
}
cv::Mat adjustChannelsOrder(const cv::Mat &srcMat, MatColorOrder srcOrder, MatColorOrder targetOrder)
{
Q_ASSERT(srcMat.channels()==4);
if (srcOrder == targetOrder)
return srcMat.clone();
cv::Mat desMat;
if ((srcOrder == MCO_ARGB && targetOrder == MCO_BGRA)
||(srcOrder == MCO_BGRA && targetOrder == MCO_ARGB)) {
//ARGB <==> BGRA
desMat = argb2bgra(srcMat);
} else if (srcOrder == MCO_ARGB && targetOrder == MCO_RGBA) {
//ARGB ==> RGBA
desMat = cv::Mat(srcMat.rows, srcMat.cols, srcMat.type());
int from_to[] = {0,3, 1,0, 2,1, 3,2};
cv::mixChannels(&srcMat, 1, &desMat, 1, from_to, 4);
} else if (srcOrder == MCO_RGBA && targetOrder == MCO_ARGB) {
//RGBA ==> ARGB
desMat = cv::Mat(srcMat.rows, srcMat.cols, srcMat.type());
int from_to[] = {0,1, 1,2, 2,3, 3,0};
cv::mixChannels(&srcMat, 1, &desMat, 1, from_to, 4);
} else {
//BGRA <==> RBGA
cv::cvtColor(srcMat, desMat, cv::COLOR_BGRA2RGBA);
}
return desMat;
}
QImage::Format findClosestFormat(QImage::Format formatHint)
{
QImage::Format format;
switch (formatHint) {
case QImage::Format_Indexed8:
case QImage::Format_RGB32:
case QImage::Format_ARGB32:
case QImage::Format_ARGB32_Premultiplied:
#if QT_VERSION >= 0x040400
case QImage::Format_RGB888:
#endif
#if QT_VERSION >= 0x050200
case QImage::Format_RGBX8888:
case QImage::Format_RGBA8888:
case QImage::Format_RGBA8888_Premultiplied:
#endif
#if QT_VERSION >= 0x050500
case QImage::Format_Alpha8:
case QImage::Format_Grayscale8:
#endif
format = formatHint;
break;
case QImage::Format_Mono:
case QImage::Format_MonoLSB:
format = QImage::Format_Indexed8;
break;
case QImage::Format_RGB16:
format = QImage::Format_RGB32;
break;
#if QT_VERSION > 0x040400
case QImage::Format_RGB444:
case QImage::Format_RGB555:
case QImage::Format_RGB666:
format = QImage::Format_RGB888;
break;
case QImage::Format_ARGB4444_Premultiplied:
case QImage::Format_ARGB6666_Premultiplied:
case QImage::Format_ARGB8555_Premultiplied:
case QImage::Format_ARGB8565_Premultiplied:
format = QImage::Format_ARGB32_Premultiplied;
break;
#endif
default:
format = QImage::Format_ARGB32;
break;
}
return format;
}
MatColorOrder getColorOrderOfRGB32Format()
{
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
return MCO_BGRA;
#else
return MCO_ARGB;
#endif
}
} //namespace
/* Convert QImage to cv::Mat
*/
cv::Mat image2Mat(const QImage &img, int requiredMatType, MatColorOrder requriedOrder)
{
int targetDepth = CV_MAT_DEPTH(requiredMatType);
int targetChannels = CV_MAT_CN(requiredMatType);
Q_ASSERT(targetChannels==CV_CN_MAX || targetChannels==1 || targetChannels==3 || targetChannels==4);
Q_ASSERT(targetDepth==CV_8U || targetDepth==CV_16U || targetDepth==CV_32F);
if (img.isNull())
return cv::Mat();
//Find the closest image format that can be used in image2Mat_shared()
QImage::Format format = findClosestFormat(img.format());
QImage image = (format==img.format()) ? img : img.convertToFormat(format);
MatColorOrder srcOrder;
cv::Mat mat0 = image2Mat_shared(image, &srcOrder);
//Adjust mat channells if needed.
cv::Mat mat_adjustCn;
const float maxAlpha = targetDepth==CV_8U ? 255 : (targetDepth==CV_16U ? 65535 : 1.0);
if (targetChannels == CV_CN_MAX)
targetChannels = mat0.channels();
switch(targetChannels) {
case 1:
if (mat0.channels() == 3) {
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_RGB2GRAY);
} else if (mat0.channels() == 4) {
if (srcOrder == MCO_BGRA)
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_BGRA2GRAY);
else if (srcOrder == MCO_RGBA)
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_RGBA2GRAY);
else//MCO_ARGB
cv::cvtColor(argb2bgra(mat0), mat_adjustCn, cv::COLOR_BGRA2GRAY);
}
break;
case 3:
if (mat0.channels() == 1) {
cv::cvtColor(mat0, mat_adjustCn, requriedOrder == MCO_BGR ? cv::COLOR_GRAY2BGR : cv::COLOR_GRAY2RGB);
} else if (mat0.channels() == 3) {
if (requriedOrder != srcOrder)
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_RGB2BGR);
} else if (mat0.channels() == 4) {
if (srcOrder == MCO_ARGB) {
mat_adjustCn = cv::Mat(mat0.rows, mat0.cols, CV_MAKE_TYPE(mat0.type(), 3));
int ARGB2RGB[] = {1,0, 2,1, 3,2};
int ARGB2BGR[] = {1,2, 2,1, 3,0};
cv::mixChannels(&mat0, 1, &mat_adjustCn, 1, requriedOrder == MCO_BGR ? ARGB2BGR : ARGB2RGB, 3);
} else if (srcOrder == MCO_BGRA) {
cv::cvtColor(mat0, mat_adjustCn, requriedOrder == MCO_BGR ? cv::COLOR_BGRA2BGR : cv::COLOR_BGRA2RGB);
} else {//RGBA
cv::cvtColor(mat0, mat_adjustCn, requriedOrder == MCO_BGR ? cv::COLOR_RGBA2BGR : cv::COLOR_RGBA2RGB);
}
}
break;
case 4:
if (mat0.channels() == 1) {
if (requriedOrder == MCO_ARGB) {
cv::Mat alphaMat(mat0.rows, mat0.cols, CV_MAKE_TYPE(mat0.type(), 1), cv::Scalar(maxAlpha));
mat_adjustCn = cv::Mat(mat0.rows, mat0.cols, CV_MAKE_TYPE(mat0.type(), 4));
cv::Mat in[] = {alphaMat, mat0};
int from_to[] = {0,0, 1,1, 1,2, 1,3};
cv::mixChannels(in, 2, &mat_adjustCn, 1, from_to, 4);
} else if (requriedOrder == MCO_RGBA) {
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_GRAY2RGBA);
} else {//MCO_BGRA
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_GRAY2BGRA);
}
} else if (mat0.channels() == 3) {
if (requriedOrder == MCO_ARGB) {
cv::Mat alphaMat(mat0.rows, mat0.cols, CV_MAKE_TYPE(mat0.type(), 1), cv::Scalar(maxAlpha));
mat_adjustCn = cv::Mat(mat0.rows, mat0.cols, CV_MAKE_TYPE(mat0.type(), 4));
cv::Mat in[] = {alphaMat, mat0};
int from_to[] = {0,0, 1,1, 2,2, 3,3};
cv::mixChannels(in, 2, &mat_adjustCn, 1, from_to, 4);
} else if (requriedOrder == MCO_RGBA) {
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_RGB2RGBA);
} else {//MCO_BGRA
cv::cvtColor(mat0, mat_adjustCn, cv::COLOR_RGB2BGRA);
}
} else if (mat0.channels() == 4) {
if (srcOrder != requriedOrder)
mat_adjustCn = adjustChannelsOrder(mat0, srcOrder, requriedOrder);
}
break;
default:
break;
}
//Adjust depth if needed.
if (targetDepth == CV_8U)
return mat_adjustCn.empty() ? mat0.clone() : mat_adjustCn;
if (mat_adjustCn.empty())
mat_adjustCn = mat0;
cv::Mat mat_adjustDepth;
mat_adjustCn.convertTo(mat_adjustDepth, CV_MAKE_TYPE(targetDepth, mat_adjustCn.channels()), targetDepth == CV_16U ? 255.0 : 1/255.0);
return mat_adjustDepth;
}
/* Convert cv::Mat to QImage
*/
QImage mat2Image(const cv::Mat &mat, MatColorOrder order, QImage::Format formatHint)
{
Q_ASSERT(mat.channels()==1 || mat.channels()==3 || mat.channels()==4);
Q_ASSERT(mat.depth()==CV_8U || mat.depth()==CV_16U || mat.depth()==CV_32F);
if (mat.empty())
return QImage();
//Adjust mat channels if needed, and find proper QImage format.
QImage::Format format;
cv::Mat mat_adjustCn;
if (mat.channels() == 1) {
format = formatHint;
if (formatHint != QImage::Format_Indexed8
#if QT_VERSION >= 0x050500
&& formatHint != QImage::Format_Alpha8
&& formatHint != QImage::Format_Grayscale8
#endif
) {
format = QImage::Format_Indexed8;
}
} else if (mat.channels() == 3) {
#if QT_VERSION >= 0x040400
format = QImage::Format_RGB888;
if (order == MCO_BGR)
cv::cvtColor(mat, mat_adjustCn, cv::COLOR_BGR2RGB);
#else
format = QImage::Format_RGB32;
cv::Mat mat_tmp;
cv::cvtColor(mat, mat_tmp, order == MCO_BGR ? CV_BGR2BGRA : CV_RGB2BGRA);
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
mat_adjustCn = mat_tmp;
#else
mat_adjustCn = argb2bgra(mat_tmp);
#endif
#endif
} else if (mat.channels() == 4) {
//Find best format if the formatHint can not be applied.
format = findClosestFormat(formatHint);
if (format != QImage::Format_RGB32
&& format != QImage::Format_ARGB32
&& format != QImage::Format_ARGB32_Premultiplied
#if QT_VERSION >= 0x050200
&& format != QImage::Format_RGBX8888
&& format != QImage::Format_RGBA8888
&& format != QImage::Format_RGBA8888_Premultiplied
#endif
) {
#if QT_VERSION >= 0x050200
format = order == MCO_RGBA ? QImage::Format_RGBA8888 : QImage::Format_ARGB32;
#else
format = QImage::Format_ARGB32;
#endif
}
//Channel order requried by the target QImage
MatColorOrder requiredOrder = getColorOrderOfRGB32Format();
#if QT_VERSION >= 0x050200
if (formatHint == QImage::Format_RGBX8888
|| formatHint == QImage::Format_RGBA8888
|| formatHint == QImage::Format_RGBA8888_Premultiplied) {
requiredOrder = MCO_RGBA;
}
#endif
if (order != requiredOrder)
mat_adjustCn = adjustChannelsOrder(mat, order, requiredOrder);
}
if (mat_adjustCn.empty())
mat_adjustCn = mat;
//Adjust mat depth if needed.
cv::Mat mat_adjustDepth = mat_adjustCn;
if (mat.depth() != CV_8U)
mat_adjustCn.convertTo(mat_adjustDepth, CV_8UC(mat_adjustCn.channels()), mat.depth() == CV_16U ? 1/255.0 : 255.0);
//Should we convert the image to the format specified by formatHint?
QImage image = mat2Image_shared(mat_adjustDepth, format);
if (format == formatHint || formatHint == QImage::Format_Invalid)
return image.copy();
else
return image.convertToFormat(formatHint);
}
/* Convert QImage to cv::Mat without data copy
*/
cv::Mat image2Mat_shared(const QImage &img, MatColorOrder *order)
{
if (img.isNull())
return cv::Mat();
switch (img.format()) {
case QImage::Format_Indexed8:
break;
#if QT_VERSION >= 0x040400
case QImage::Format_RGB888:
if (order)
*order = MCO_RGB;
break;
#endif
case QImage::Format_RGB32:
case QImage::Format_ARGB32:
case QImage::Format_ARGB32_Premultiplied:
if (order)
*order = getColorOrderOfRGB32Format();
break;
#if QT_VERSION >= 0x050200
case QImage::Format_RGBX8888:
case QImage::Format_RGBA8888:
case QImage::Format_RGBA8888_Premultiplied:
if (order)
*order = MCO_RGBA;
break;
#endif
#if QT_VERSION >= 0x050500
case QImage::Format_Alpha8:
case QImage::Format_Grayscale8:
break;
#endif
default:
return cv::Mat();
}
return cv::Mat(img.height(), img.width(), CV_8UC(img.depth()/8), (uchar*)img.bits(), img.bytesPerLine());
}
/* Convert cv::Mat to QImage without data copy
*/
QImage mat2Image_shared(const cv::Mat &mat, QImage::Format formatHint)
{
Q_ASSERT(mat.type() == CV_8UC1 || mat.type() == CV_8UC3 || mat.type() == CV_8UC4);
if (mat.empty())
return QImage();
//Adjust formatHint if needed.
if (mat.type() == CV_8UC1) {
if (formatHint != QImage::Format_Indexed8
#if QT_VERSION >= 0x050500
&& formatHint != QImage::Format_Alpha8
&& formatHint != QImage::Format_Grayscale8
#endif
) {
formatHint = QImage::Format_Indexed8;
}
#if QT_VERSION >= 0x040400
} else if (mat.type() == CV_8UC3) {
formatHint = QImage::Format_RGB888;
#endif
} else if (mat.type() == CV_8UC4) {
if (formatHint != QImage::Format_RGB32
&& formatHint != QImage::Format_ARGB32
&& formatHint != QImage::Format_ARGB32_Premultiplied
#if QT_VERSION >= 0x050200
&& formatHint != QImage::Format_RGBX8888
&& formatHint != QImage::Format_RGBA8888
&& formatHint != QImage::Format_RGBA8888_Premultiplied
#endif
) {
formatHint = QImage::Format_ARGB32;
}
}
QImage img(mat.data, mat.cols, mat.rows, mat.step, formatHint);
//Should we add directly support for user-customed-colorTable?
if (formatHint == QImage::Format_Indexed8) {
QVector colorTable;
for (int i=0; i<256; ++i)
colorTable.append(qRgb(i,i,i));
img.setColorTable(colorTable);
}
return img;
}
// todo: 64, mono
bool isSupported(QImage::Format format) {
if(format == QImage::Format_RGB888 ||
//format == QImage::Format_Indexed8 || // result is grayscale which may be wrong
//format == QImage::Format_Alpha8 ||
format == QImage::Format_Grayscale8 ||
format == QImage::Format_RGB32 ||
format == QImage::Format_ARGB32 ||
format == QImage::Format_ARGB32_Premultiplied
// TODO: RGBA8888 has swapped channels. other xxx8888 probably too
/*format == QImage::Format_RGBX8888 ||
format == QImage::Format_RGBA8888 ||
format == QImage::Format_RGBA8888_Premultiplied*/)
{
return true;
}
return false;
}
} //namespace QtOcv
qimgv-master/qimgv/3rdparty/QtOpenCV/cvmatandqimage.h 0000664 0000000 0000000 00000007064 14761273276 0023204 0 ustar 00root root 0000000 0000000 /****************************************************************************
** Copyright (c) 2012-2015 Debao Zhang
** All right reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be
** included in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
****************************************************************************/
#ifndef CVMATANDQIMAGE_H
#define CVMATANDQIMAGE_H
#include
// cmake automatically search the include directory
// some platforms, we maybe use opencv 3.x stable
#include
namespace QtOcv {
enum MatColorOrder {
MCO_BGR,
MCO_RGB,
MCO_BGRA = MCO_BGR,
MCO_RGBA = MCO_RGB,
MCO_ARGB
};
/* Convert QImage to/from cv::Mat
*
* - cv::Mat
* - Supported channels
* - 1 channel
* - 3 channels (B G R), (R G B)
* - 4 channels (B G R A), (R G B A), (A R G B)
* - Supported depth
* - CV_8U [0, 255]
* - CV_16U [0, 65535]
* - CV_32F [0, 1.0]
*
* - QImage
* - All of the formats of QImage are supported.
*/
cv::Mat image2Mat(const QImage &img, int requiredMatType = CV_8UC(0), MatColorOrder requiredOrder=MCO_BGR);
QImage mat2Image(const cv::Mat &mat, MatColorOrder order=MCO_BGR, QImage::Format formatHint = QImage::Format_Invalid);
/* Convert QImage to/from cv::Mat without data copy
*
* - Supported QImage formats and cv::Mat types are:
* - QImage::Format_Indexed8 <==> CV_8UC1
* - QImage::Format_Alpha8 <==> CV_8UC1
* - QImage::Format_Grayscale8 <==> CV_8UC1
* - QImage::Format_RGB888 <==> CV_8UC3 (R G B)
* - QImage::Format_RGB32 <==> CV_8UC4 (A R G B or B G R A)
* - QImage::Format_ARGB32 <==> CV_8UC4 (A R G B or B G R A)
* - QImage::Format_ARGB32_Premultiplied <==> CV_8UC4 (A R G B or B G R A)
* - QImage::Format_RGBX8888 <==> CV_8UC4 (R G B A)
* - QImage::Format_RGBA8888 <==> CV_8UC4 (R G B A)
* - QImage::Format_RGBA8888_Premultiplied <==> CV_8UC4 (R G B A)
*
* - For QImage::Format_RGB32 ,QImage::Format_ARGB32
* and QImage::Format_ARGB32_Premultiplied, the
* color channel order of cv::Mat will be (B G R A) in little
* endian system or (A R G B) in big endian system.
*
* - User must make sure that the color channels order is the same as
* the color channels order requried by QImage.
*/
cv::Mat image2Mat_shared(const QImage &img, MatColorOrder *order=0);
QImage mat2Image_shared(const cv::Mat &mat, QImage::Format formatHint = QImage::Format_Invalid);
bool isSupported(QImage::Format format);
} //namespace QtOcv
#endif // CVMATANDQIMAGE_H
qimgv-master/qimgv/CMakeLists.txt 0000664 0000000 0000000 00000013156 14761273276 0017402 0 ustar 00root root 0000000 0000000 include(GNUInstallDirs)
set(CMAKE_VERBOSE_MAKEFILE ON)
if(APPLE)
set(APPLE_ICON_NAME "qimgv.icns")
set(APPLE_ICON_PATH "distrib/${APPLE_ICON_NAME}")
endif()
# TRANSLATIONS
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS LinguistTools)
# Example of creating a new translation file.
# 1. cd into qimgv directory and run:
# lupdate -recursive . -ts res/translations/qimgv_en_US.ts [replace "en_US" with your locale]
# 2. Add your .ts filename into TS_FILES list below
# 3. Translate it with Qt Linguist
set(TS_FILES
"zh_CN.ts"
"uk_UA.ts"
"es_ES.ts"
"de_DE.ts"
"fr_FR.ts"
)
list(TRANSFORM TS_FILES PREPEND ${CMAKE_CURRENT_SOURCE_DIR}/res/translations/)
set_source_files_properties(${TS_FILES} PROPERTIES OUTPUT_LOCATION ${PROJECT_BINARY_DIR}/qimgv/translations)
# 1. Create 'qimgv_lupdate' target to update .ts files (needs to be called manually)
# 2. Compile .ts > .qm
if(${QT_VERSION_MAJOR} EQUAL 5)
add_custom_target(qimgv_lupdate COMMAND ${Qt5_LUPDATE_EXECUTABLE} -recursive
${CMAKE_CURRENT_SOURCE_DIR} -ts ${TS_FILES})
qt5_add_translation(QM_FILES ${TS_FILES})
endif()
# ADD EXECUTABLE
add_executable(qimgv
appversion.cpp
core.cpp
main.cpp
settings.cpp
themestore.cpp
sharedresources.cpp
shortcutbuilder.cpp
proxystyle.cpp
macosapplication.cpp
resources.qrc
qimgv.rc
${APPLE_ICON_PATH}
${QM_FILES}
)
# update .ts, compile .qm (qt6 case)
if(${QT_VERSION_MAJOR} EQUAL 6)
qt_add_lupdate(qimgv TS_FILES ${TS_FILES})
qt_add_lrelease(qimgv TS_FILES ${TS_FILES})
endif()
# ADD SOURCES
add_subdirectory(components)
add_subdirectory(sourcecontainers)
add_subdirectory(gui)
add_subdirectory(utils)
if(OPENCV_SUPPORT)
add_subdirectory(3rdparty/QtOpenCV)
endif()
# C++ STANDARD
target_compile_features(qimgv PRIVATE cxx_std_17)
set_target_properties(qimgv PROPERTIES CXX_EXTENSIONS OFF)
# LINK STUFF
target_link_libraries(qimgv PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Svg Qt${QT_VERSION_MAJOR}::PrintSupport)
if(QT_VERSION_MAJOR GREATER_EQUAL 6)
target_link_libraries(qimgv PRIVATE Qt${QT_VERSION_MAJOR}::OpenGLWidgets)
endif()
# OPTION DEFINITIONS, LINKING
if(EXIV2)
target_link_libraries(qimgv PRIVATE PkgConfig::Exiv2)
target_compile_definitions(qimgv PRIVATE USE_EXIV2)
endif()
if(KDE_SUPPORT)
target_link_libraries(qimgv PRIVATE KF5::WindowSystem)
target_compile_definitions(qimgv PRIVATE USE_KDE_BLUR)
endif()
if(VIDEO_SUPPORT)
target_compile_definitions(qimgv PRIVATE USE_MPV)
if(WIN32)
ADD_DEFINITIONS(-D_QIMGV_PLUGIN_DIR="plugins")
ADD_DEFINITIONS(-D_QIMGV_PLAYER_PLUGIN="player_mpv.dll")
else()
ADD_DEFINITIONS(-D_QIMGV_PLUGIN_DIR="${QIMGV_PLUGIN_DIR}")
ADD_DEFINITIONS(-D_QIMGV_PLAYER_PLUGIN="player_mpv.so")
endif()
endif()
if(OPENCV_SUPPORT)
target_link_libraries(qimgv PRIVATE ${OpenCV_LIBS})
target_compile_definitions(qimgv PRIVATE USE_OPENCV)
endif()
# generate proper GUI program on specified platform
if(WIN32) # Check if we are on Windows
if(MSVC) # Check if we are using the Visual Studio compiler
set_target_properties(qimgv PROPERTIES WIN32_EXECUTABLE ON)
target_link_options(qimgv PRIVATE "/ENTRY:mainCRTStartup")
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
target_link_options(qimgv PRIVATE "-mwindows")
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
set(CMAKE_CXX_FLAGS "$ENV{CMAKE_CXX_FLAGS} -Wno-shift-negative-value")
set(CMAKE_EXE_LINKER_FLAGS "$ENV{CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld")
target_link_options(qimgv PRIVATE "-mwindows")
else()
message(SEND_ERROR "You are using an unsupported Windows compiler! (Not MSVC or GCC)")
endif(MSVC)
elseif(APPLE)
set_target_properties(qimgv PROPERTIES
MACOSX_BUNDLE YES
MACOSX_BUNDLE_BUNDLE_NAME "qimgv"
MACOSX_BUNDLE_BUNDLE_VERSION "1.0.2"
MACOSX_BUNDLE_SHORT_VERSION_STRING "1.0.2"
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/distrib/MyBundleInfo.plist.in
MACOSX_BUNDLE_ICON_FILE ${APPLE_ICON_NAME}
)
set_source_files_properties(${APPLE_ICON_PATH} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
elseif(NOT UNIX)
message(SEND_ERROR "You are on an unsupported platform! (Not Win32, Mac OS X or Unix)")
endif()
## INSTALLATION
install(TARGETS qimgv DESTINATION bin)
# .desktop
install(FILES distrib/qimgv.desktop
DESTINATION ${CMAKE_INSTALL_FULL_DATAROOTDIR}/applications)
# icons
foreach(icon IN ITEMS 16x16 22x22 24x24 32x32 36x36 48x48 64x64 128x128 256x256)
install(FILES distrib/hicolor/${icon}/apps/qimgv.png DESTINATION
${CMAKE_INSTALL_FULL_DATAROOTDIR}/icons/hicolor/${icon}/apps)
endforeach()
install(FILES distrib/hicolor/scalable/apps/qimgv.svg
DESTINATION ${CMAKE_INSTALL_FULL_DATAROOTDIR}/icons/hicolor/scalable/apps)
# AppData manifest
install(FILES distrib/qimgv.appdata.xml DESTINATION ${CMAKE_INSTALL_FULL_DATAROOTDIR}/metainfo)
# Install internationalization language files
if(WIN32)
install(DIRECTORY "${PROJECT_BINARY_DIR}/qimgv/translations" DESTINATION "${CMAKE_INSTALL_BINDIR}")
else()
ADD_DEFINITIONS(-DTRANSLATIONS_PATH="${CMAKE_INSTALL_FULL_DATAROOTDIR}/qimgv/translations")
install(DIRECTORY "${PROJECT_BINARY_DIR}/qimgv/translations" DESTINATION "${CMAKE_INSTALL_FULL_DATAROOTDIR}/qimgv")
endif()
# uninstall target
if(NOT TARGET uninstall)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)
endif()
qimgv-master/qimgv/appversion.cpp 0000664 0000000 0000000 00000000073 14761273276 0017526 0 ustar 00root root 0000000 0000000 #include "appversion.h"
QVersionNumber appVersion(1,0,3);
qimgv-master/qimgv/appversion.h 0000664 0000000 0000000 00000000113 14761273276 0017166 0 ustar 00root root 0000000 0000000 #pragma once
#include
extern QVersionNumber appVersion;
qimgv-master/qimgv/cmake_uninstall.cmake.in 0000664 0000000 0000000 00000001524 14761273276 0021416 0 ustar 00root root 0000000 0000000 if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt")
endif()
file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")
foreach(file ${files})
message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
exec_program(
"@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval
)
if(NOT "${rm_retval}" STREQUAL 0)
message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
endif()
else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
endif()
endforeach()
qimgv-master/qimgv/components/ 0000775 0000000 0000000 00000000000 14761273276 0017021 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/CMakeLists.txt 0000664 0000000 0000000 00000002413 14761273276 0021561 0 ustar 00root root 0000000 0000000 ## SOURCES FOR QIMGV COMPONENTS
target_sources(qimgv PRIVATE
directorymodel.cpp
directorypresenter.cpp
scriptmanager/scriptmanager.cpp
actionmanager/actionmanager.cpp
cache/cache.cpp
cache/cacheitem.cpp
cache/thumbnailcache.cpp
loader/loader.cpp
loader/loaderrunnable.cpp
scaler/scaler.cpp
scaler/scalerrunnable.cpp
thumbnailer/thumbnailer.cpp
thumbnailer/thumbnailerrunnable.cpp
directorymanager/directorymanager.cpp
directorymanager/watchers/directorywatcher.cpp
directorymanager/watchers/dummywatcher.cpp
directorymanager/watchers/watcherevent.cpp
directorymanager/watchers/watcherworker.cpp
)
if(APPLE)
#target_sources(qimgv PRIVATE
# directorymanager/watchers/linux/linuxfsevent.cpp
# directorymanager/watchers/linux/linuxwatcher.cpp
# directorymanager/watchers/linux/linuxworker.cpp)
elseif(UNIX)
target_sources(qimgv PRIVATE
directorymanager/watchers/linux/linuxfsevent.cpp
directorymanager/watchers/linux/linuxwatcher.cpp
directorymanager/watchers/linux/linuxworker.cpp)
elseif(WIN32)
target_sources(qimgv PRIVATE
directorymanager/watchers/windows/windowswatcher.cpp
directorymanager/watchers/windows/windowsworker.cpp)
endif()
qimgv-master/qimgv/components/actionmanager/ 0000775 0000000 0000000 00000000000 14761273276 0021631 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/actionmanager/actionmanager.cpp 0000664 0000000 0000000 00000031131 14761273276 0025144 0 ustar 00root root 0000000 0000000 #include "actionmanager.h"
ActionManager *actionManager = nullptr;
ActionManager::ActionManager(QObject *parent) : QObject(parent) {
}
//------------------------------------------------------------------------------
ActionManager::~ActionManager() {
delete actionManager;
}
//------------------------------------------------------------------------------
ActionManager *ActionManager::getInstance() {
if(!actionManager) {
actionManager = new ActionManager();
initDefaults();
initShortcuts();
}
return actionManager;
}
//------------------------------------------------------------------------------
void ActionManager::initDefaults() {
actionManager->defaults.insert("Right", "nextImage");
actionManager->defaults.insert("Left", "prevImage");
actionManager->defaults.insert("XButton2", "nextImage");
actionManager->defaults.insert("XButton1", "prevImage");
actionManager->defaults.insert("WheelDown", "nextImage");
actionManager->defaults.insert("WheelUp", "prevImage");
actionManager->defaults.insert("F", "toggleFullscreen");
actionManager->defaults.insert("F11", "toggleFullscreen");
actionManager->defaults.insert("LMB_DoubleClick", "toggleFullscreen");
actionManager->defaults.insert("MiddleButton", "exit");
actionManager->defaults.insert("Space", "toggleFitMode");
actionManager->defaults.insert("1", "fitWindow");
actionManager->defaults.insert("2", "fitWidth");
actionManager->defaults.insert("3", "fitNormal");
actionManager->defaults.insert("R", "resize");
actionManager->defaults.insert("H", "flipH");
actionManager->defaults.insert("V", "flipV");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+R", "rotateRight");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+L", "rotateLeft");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+WheelUp", "zoomInCursor");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+WheelDown", "zoomOutCursor");
actionManager->defaults.insert("=", "zoomIn"); // [=+] key on the number row
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+=", "zoomIn");
actionManager->defaults.insert("+", "zoomIn");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "++", "zoomIn");
actionManager->defaults.insert("-", "zoomOut");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+-", "zoomOut");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Down", "zoomOut");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Up", "zoomIn");
actionManager->defaults.insert("Up", "scrollUp");
actionManager->defaults.insert("Down", "scrollDown");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+O", "open");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+S", "save");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+" + InputMap::keyNameShift() + "+S", "saveAs");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+W", "setWallpaper");
actionManager->defaults.insert("X", "crop");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+P", "print");
actionManager->defaults.insert(InputMap::keyNameAlt() + "+X", "exit");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Q", "exit");
actionManager->defaults.insert("Esc", "closeFullScreenOrExit");
actionManager->defaults.insert("Del", "moveToTrash");
actionManager->defaults.insert(InputMap::keyNameShift() + "+Del", "removeFile");
actionManager->defaults.insert("C", "copyFile");
actionManager->defaults.insert("M", "moveFile");
actionManager->defaults.insert("Home", "jumpToFirst");
actionManager->defaults.insert("End", "jumpToLast");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Right", "seekVideoForward");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Left", "seekVideoBackward");
actionManager->defaults.insert(",", "frameStepBack");
actionManager->defaults.insert(".", "frameStep");
actionManager->defaults.insert("Enter", "folderView");
actionManager->defaults.insert("Backspace", "folderView");
actionManager->defaults.insert("F5", "reloadImage");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+C", "copyFileClipboard");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+" + InputMap::keyNameShift() + "+C", "copyPathClipboard");
actionManager->defaults.insert("F2", "renameFile");
actionManager->defaults.insert("RMB", "contextMenu");
actionManager->defaults.insert("Menu", "contextMenu");
actionManager->defaults.insert("I", "toggleImageInfo");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+`", "toggleShuffle");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+D", "showInDirectory");
actionManager->defaults.insert("`", "toggleSlideshow");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Z", "discardEdits");
actionManager->defaults.insert(InputMap::keyNameShift() + "+Right", "nextDirectory");
actionManager->defaults.insert(InputMap::keyNameShift() + "+Left", "prevDirectory");
actionManager->defaults.insert(InputMap::keyNameShift() + "+F", "toggleFullscreenInfoBar");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+V", "pasteFile");
#ifdef __APPLE__
actionManager->defaults.insert(InputMap::keyNameAlt() + "+Up", "zoomIn");
actionManager->defaults.insert(InputMap::keyNameAlt() + "+Down", "zoomOut");
actionManager->defaults.insert(InputMap::keyNameCtrl() + "+Comma", "openSettings");
#else
actionManager->defaults.insert("P", "openSettings");
#endif
//actionManager->defaults.insert("Backspace", "goUp"); // todo: shortcut scopes?
}
//------------------------------------------------------------------------------
void ActionManager::initShortcuts() {
actionManager->readShortcuts();
if(actionManager->shortcuts.isEmpty()) {
actionManager->resetDefaults();
}
}
//------------------------------------------------------------------------------
void ActionManager::addShortcut(const QString &keys, const QString &action) {
ActionType type = validateAction(action);
if(type != ActionType::ACTION_INVALID) {
actionManager->shortcuts.insert(keys, action);
}
}
//------------------------------------------------------------------------------
void ActionManager::removeShortcut(const QString &keys) {
actionManager->shortcuts.remove(keys);
}
//------------------------------------------------------------------------------
QStringList ActionManager::actionList() {
return appActions->getList();
}
//------------------------------------------------------------------------------
const QMap &ActionManager::allShortcuts() {
return actionManager->shortcuts;
}
//------------------------------------------------------------------------------
void ActionManager::removeAllShortcuts() {
shortcuts.clear();
}
//------------------------------------------------------------------------------
// Removes all shortcuts for specified action. Slow (reverse map lookup).
void ActionManager::removeAllShortcuts(QString actionName) {
if(validateAction(actionName) == ActionType::ACTION_INVALID)
return;
for (auto i = shortcuts.begin(); i != shortcuts.end();) {
if(i.value() == actionName)
i = shortcuts.erase(i);
else
++i;
}
}
//------------------------------------------------------------------------------
QString ActionManager::keyForNativeScancode(quint32 scanCode) {
if(inputMap->keys().contains(scanCode)) {
return inputMap->keys()[scanCode];
}
return "";
}
//------------------------------------------------------------------------------
void ActionManager::resetDefaults() {
actionManager->shortcuts = actionManager->defaults;
}
//------------------------------------------------------------------------------
void ActionManager::resetDefaults(QString action) {
actionManager->removeAllShortcuts(action);
QMapIterator i(defaults);
while(i.hasNext()) {
i.next();
if(i.value() == action) {
shortcuts.insert(i.key(), i.value());
qDebug() << "[ActionManager] new action " << i.value() << " - assigning as [" << i.key() << "]";
}
}
}
//------------------------------------------------------------------------------
void ActionManager::adjustFromVersion(QVersionNumber lastVer) {
// swap Ctrl-P & P
if(lastVer < QVersionNumber(0,9,2)) {
actionManager->resetDefaults("print");
actionManager->resetDefaults("openSettings");
}
// swap WheelUp/WheelDown. derp
if(lastVer < QVersionNumber(1,0,1)) {
qDebug() << "[actionManager]: swapping WheelUp/WheelDown";
QMapIterator i(shortcuts);
QMap swapped;
while(i.hasNext()) {
i.next();
QString key = i.key();
if(key.contains("WheelUp"))
key.replace("WheelUp", "WheelDown");
else if(key.contains("WheelDown"))
key.replace("WheelDown", "WheelUp");
swapped.insert(key, i.value());
}
shortcuts = swapped;
}
// add new default actions
QMapIterator i(defaults);
while(i.hasNext()) {
i.next();
if(appActions->getMap().value(i.value()) > lastVer) {
if(!shortcuts.contains(i.key())) {
shortcuts.insert(i.key(), i.value());
qDebug() << "[ActionManager] new action " << i.value() << " - assigning as [" << i.key() << "]";
} else if(i.value() != actionForShortcut(i.key())) {
qDebug() << "[ActionManager] new action " << i.value() << " - shortcut [" << i.key() << "] already assigned to another action " << actionForShortcut(i.key());
}
}
}
// apply
saveShortcuts();
}
//------------------------------------------------------------------------------
void ActionManager::saveShortcuts() {
settings->saveShortcuts(actionManager->shortcuts);
}
//------------------------------------------------------------------------------
QString ActionManager::actionForShortcut(const QString &keys) {
return actionManager->shortcuts[keys];
}
// returns first shortcut that is found
const QString ActionManager::shortcutForAction(QString action) {
return shortcuts.key(action, "");
}
const QList ActionManager::shortcutsForAction(QString action) {
return shortcuts.keys(action);
}
//------------------------------------------------------------------------------
bool ActionManager::invokeAction(const QString &actionName) {
ActionType type = validateAction(actionName);
if(type == ActionType::ACTION_NORMAL) {
QMetaObject::invokeMethod(this, actionName.toLatin1().constData(), Qt::DirectConnection);
return true;
} else if(type == ActionType::ACTION_SCRIPT) {
QString scriptName = actionName;
scriptName.remove(0, 2); // remove the "s:" prefix
emit runScript(scriptName);
return true;
}
return false;
}
//------------------------------------------------------------------------------
bool ActionManager::invokeActionForShortcut(const QString &shortcut) {
if(!shortcut.isEmpty() && shortcuts.contains(shortcut)) {
return invokeAction(actionManager->shortcuts[shortcut]);
}
return false;
}
//------------------------------------------------------------------------------
void ActionManager::validateShortcuts() {
for (auto i = shortcuts.begin(); i != shortcuts.end();) {
if(validateAction(i.value()) == ActionType::ACTION_INVALID)
i = shortcuts.erase(i);
else
++i;
}
}
//------------------------------------------------------------------------------
inline
ActionType ActionManager::validateAction(const QString &actionName) {
if(appActions->getMap().contains(actionName))
return ActionType::ACTION_NORMAL;
if(actionName.startsWith("s:")) {
QString scriptName = actionName;
scriptName.remove(0, 2);
if(scriptManager->scriptExists(scriptName))
return ActionType::ACTION_SCRIPT;
}
return ActionType::ACTION_INVALID;
}
//------------------------------------------------------------------------------
void ActionManager::readShortcuts() {
settings->readShortcuts(shortcuts);
actionManager->validateShortcuts();
}
//------------------------------------------------------------------------------
bool ActionManager::processEvent(QInputEvent *event) {
return actionManager->invokeActionForShortcut(ShortcutBuilder::fromEvent(event));
}
//------------------------------------------------------------------------------
qimgv-master/qimgv/components/actionmanager/actionmanager.h 0000664 0000000 0000000 00000006456 14761273276 0024625 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include
#include
#include
#include "utils/actions.h"
#include "shortcutbuilder.h"
#include "components/scriptmanager/scriptmanager.h"
#include "settings.h"
enum ActionType {
ACTION_INVALID,
ACTION_NORMAL,
ACTION_SCRIPT
};
class ActionManager : public QObject {
Q_OBJECT
public:
static ActionManager* getInstance();
~ActionManager();
bool processEvent(QInputEvent*);
void addShortcut(const QString &keys, const QString &action);
void resetDefaults();
void resetDefaults(QString action);
QString actionForShortcut(const QString &keys);
const QString shortcutForAction(QString action);
const QList shortcutsForAction(QString action);
QStringList actionList();
const QMap& allShortcuts();
void removeShortcut(const QString &keys);
void removeAllShortcuts();
void removeAllShortcuts(QString actionName);
QString keyForNativeScancode(quint32 scanCode);
void adjustFromVersion(QVersionNumber lastVer);
void saveShortcuts();
public slots:
bool invokeAction(const QString &actionName);
private:
explicit ActionManager(QObject *parent = nullptr);
QMap defaults, shortcuts; //
static void initDefaults();
static void initActions();
static void initShortcuts();
QString modifierKeys(QEvent *event);
bool invokeActionForShortcut(const QString &action);
void validateShortcuts();
void readShortcuts();
ActionType validateAction(const QString &actionName);
signals:
void open();
void save();
void saveAs();
void openSettings();
void crop();
void setWallpaper();
void nextImage();
void prevImage();
void fitWindow();
void fitWidth();
void fitNormal();
void flipH();
void flipV();
void toggleFitMode();
void toggleFullscreen();
void scrollUp();
void scrollDown();
void scrollLeft();
void scrollRight();
void zoomIn();
void zoomOut();
void zoomInCursor();
void zoomOutCursor();
void resize();
void rotateLeft();
void rotateRight();
void exit();
void removeFile();
void copyFile();
void moveFile();
void closeFullScreenOrExit();
void jumpToFirst();
void jumpToLast();
void folderView();
void documentView();
void runScript(const QString&);
void pauseVideo();
void seekVideoForward();
void seekVideoBackward();
void frameStep();
void frameStepBack();
void toggleFolderView();
void moveToTrash();
void reloadImage();
void copyFileClipboard();
void copyPathClipboard();
void renameFile();
void contextMenu();
void toggleTransparencyGrid();
void sortByName();
void sortByTime();
void sortBySize();
void toggleImageInfo();
void toggleShuffle();
void toggleScalingFilter();
void showInDirectory();
void toggleMute();
void volumeUp();
void volumeDown();
void toggleSlideshow();
void discardEdits();
void goUp();
void nextDirectory();
void prevDirectory();
void lockZoom();
void lockView();
void print();
void toggleFullscreenInfoBar();
void pasteFile();
};
extern ActionManager *actionManager;
qimgv-master/qimgv/components/cache/ 0000775 0000000 0000000 00000000000 14761273276 0020064 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/cache/cache.cpp 0000664 0000000 0000000 00000003064 14761273276 0021636 0 ustar 00root root 0000000 0000000 #include "cache.h"
Cache::Cache() {
}
bool Cache::contains(QString path) const {
return items.contains(path);
}
bool Cache::insert(std::shared_ptr img) {
if(img) {
if(items.contains(img->filePath())) {
return false;
} else {
items.insert(img->filePath(), new CacheItem(img));
return true;
}
}
// TODO: what state returns here ??
return true;
}
void Cache::remove(QString path) {
if(items.contains(path)) {
items[path]->lock();
auto *item = items.take(path);
delete item;
}
}
void Cache::clear() {
for(auto path : items.keys()) {
items[path]->lock();
auto item = items.take(path);
delete item;
}
}
std::shared_ptr Cache::get(QString path) {
if(items.contains(path)) {
CacheItem *item = items.value(path);
return item->getContents();
}
return nullptr;
}
bool Cache::reserve(QString path) {
if(items.contains(path)) {
items[path]->lock();
return true;
}
return false;
}
bool Cache::release(QString path) {
if(items.contains(path)) {
items[path]->unlock();
return true;
}
return false;
}
// removes all items except the ones in list
void Cache::trimTo(QStringList pathList) {
for(auto path : items.keys()) {
if(!pathList.contains(path)) {
items[path]->lock();
auto *item = items.take(path);
delete item;
}
}
}
const QList Cache::keys() const {
return items.keys();
}
qimgv-master/qimgv/components/cache/cache.h 0000664 0000000 0000000 00000001150 14761273276 0021275 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include "sourcecontainers/image.h"
#include "components/cache/cacheitem.h"
#include "utils/imagefactory.h"
class Cache {
public:
explicit Cache();
bool contains(QString path) const;
void remove(QString path);
void clear();
bool insert(std::shared_ptr img);
void trimTo(QStringList list);
std::shared_ptr get(QString path);
bool release(QString path);
bool reserve(QString path);
const QList keys() const;
private:
QMap items;
};
qimgv-master/qimgv/components/cache/cacheitem.cpp 0000664 0000000 0000000 00000000734 14761273276 0022516 0 ustar 00root root 0000000 0000000 #include "cacheitem.h"
CacheItem::CacheItem() {
sem = new QSemaphore(1);
}
CacheItem::CacheItem(std::shared_ptr _contents) {
contents = _contents;
sem = new QSemaphore(1);
}
CacheItem::~CacheItem() {
delete sem;
}
std::shared_ptr CacheItem::getContents() {
return contents;
}
void CacheItem::lock() {
sem->acquire(1);
}
void CacheItem::unlock() {
sem->release(1);
}
int CacheItem::lockStatus() {
return sem->available();
}
qimgv-master/qimgv/components/cache/cacheitem.h 0000664 0000000 0000000 00000000545 14761273276 0022163 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include "sourcecontainers/image.h"
class CacheItem {
public:
CacheItem();
CacheItem(std::shared_ptr _contents);
~CacheItem();
std::shared_ptr getContents();
void lock();
void unlock();
int lockStatus();
private:
std::shared_ptr contents;
QSemaphore *sem;
};
qimgv-master/qimgv/components/cache/thumbnailcache.cpp 0000664 0000000 0000000 00000001674 14761273276 0023547 0 ustar 00root root 0000000 0000000 #include "thumbnailcache.h"
ThumbnailCache::ThumbnailCache() {
cacheDirPath = settings->thumbnailCacheDir();
}
QString ThumbnailCache::thumbnailPath(QString id) {
return QString(cacheDirPath + id + ".png");
}
bool ThumbnailCache::exists(QString id) {
QString filePath = thumbnailPath(id);
QFileInfo file(filePath);
return file.exists() && file.isReadable();
}
void ThumbnailCache::saveThumbnail(QImage *image, QString id) {
if(image) {
QString filePath = thumbnailPath(id);
image->save(filePath, "PNG", 15);
}
}
QImage *ThumbnailCache::readThumbnail(QString id) {
QString filePath = thumbnailPath(id);
QFileInfo file(filePath);
if(file.exists() && file.isReadable()) {
QImage *thumb = new QImage();
if(thumb->load(filePath)) {
return thumb;
} else {
delete thumb;
return nullptr;
}
} else {
return nullptr;
}
}
qimgv-master/qimgv/components/cache/thumbnailcache.h 0000664 0000000 0000000 00000001030 14761273276 0023176 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include "settings.h"
#include "sourcecontainers/thumbnail.h"
class ThumbnailCache : public QObject
{
Q_OBJECT
public:
explicit ThumbnailCache();
void saveThumbnail(QImage *image, QString id);
QImage* readThumbnail(QString id);
QString thumbnailPath(QString id);
bool exists(QString id);
signals:
public slots:
private:
// we are still bottlenecked by disk access anyway
QMutex mutex;
QString cacheDirPath;
};
qimgv-master/qimgv/components/directorymanager/ 0000775 0000000 0000000 00000000000 14761273276 0022360 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/directorymanager/directorymanager.cpp 0000664 0000000 0000000 00000050043 14761273276 0026425 0 ustar 00root root 0000000 0000000 #include "directorymanager.h"
namespace fs = std::filesystem;
DirectoryManager::DirectoryManager() :
watcher(nullptr),
mSortingMode(SORT_NAME)
{
regex.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
collator.setNumericMode(true);
readSettings();
setSortingMode(settings->sortingMode());
connect(settings, &Settings::settingsChanged, this, &DirectoryManager::readSettings);
}
template< typename T, typename Pred >
typename std::vector::iterator
insert_sorted(std::vector & vec, T const& item, Pred pred) {
return vec.insert(std::upper_bound(vec.begin(), vec.end(), item, pred), item);
}
bool DirectoryManager::path_entry_compare(const FSEntry &e1, const FSEntry &e2) const {
return collator.compare(e1.path, e2.path) < 0;
};
bool DirectoryManager::path_entry_compare_reverse(const FSEntry &e1, const FSEntry &e2) const {
return collator.compare(e1.path, e2.path) > 0;
};
bool DirectoryManager::name_entry_compare(const FSEntry &e1, const FSEntry &e2) const {
return collator.compare(e1.name, e2.name) < 0;
};
bool DirectoryManager::name_entry_compare_reverse(const FSEntry &e1, const FSEntry &e2) const {
return collator.compare(e1.name, e2.name) > 0;
};
bool DirectoryManager::date_entry_compare(const FSEntry& e1, const FSEntry& e2) const {
return e1.modifyTime < e2.modifyTime;
}
bool DirectoryManager::date_entry_compare_reverse(const FSEntry& e1, const FSEntry& e2) const {
return e1.modifyTime > e2.modifyTime;
}
bool DirectoryManager::size_entry_compare(const FSEntry& e1, const FSEntry& e2) const {
return e1.size < e2.size;
}
bool DirectoryManager::size_entry_compare_reverse(const FSEntry& e1, const FSEntry& e2) const {
return e1.size > e2.size;
}
CompareFunction DirectoryManager::compareFunction() {
CompareFunction cmpFn = &DirectoryManager::path_entry_compare;
if(mSortingMode == SortingMode::SORT_NAME_DESC)
cmpFn = &DirectoryManager::path_entry_compare_reverse;
if(mSortingMode == SortingMode::SORT_TIME)
cmpFn = &DirectoryManager::date_entry_compare;
if(mSortingMode == SortingMode::SORT_TIME_DESC)
cmpFn = &DirectoryManager::date_entry_compare_reverse;
if(mSortingMode == SortingMode::SORT_SIZE)
cmpFn = &DirectoryManager::size_entry_compare;
if(mSortingMode == SortingMode::SORT_SIZE_DESC)
cmpFn = &DirectoryManager::size_entry_compare_reverse;
return cmpFn;
}
void DirectoryManager::startFileWatcher(QString directoryPath) {
if(directoryPath == "")
return;
if(!watcher)
watcher = DirectoryWatcher::newInstance();
connect(watcher, &DirectoryWatcher::fileCreated, this, &DirectoryManager::onFileAddedExternal, Qt::UniqueConnection);
connect(watcher, &DirectoryWatcher::fileDeleted, this, &DirectoryManager::onFileRemovedExternal, Qt::UniqueConnection);
connect(watcher, &DirectoryWatcher::fileModified, this, &DirectoryManager::onFileModifiedExternal, Qt::UniqueConnection);
connect(watcher, &DirectoryWatcher::fileRenamed, this, &DirectoryManager::onFileRenamedExternal, Qt::UniqueConnection);
watcher->setWatchPath(directoryPath);
watcher->observe();
}
void DirectoryManager::stopFileWatcher() {
if(!watcher)
return;
watcher->stopObserving();
disconnect(watcher, &DirectoryWatcher::fileCreated, this, &DirectoryManager::onFileAddedExternal);
disconnect(watcher, &DirectoryWatcher::fileDeleted, this, &DirectoryManager::onFileRemovedExternal);
disconnect(watcher, &DirectoryWatcher::fileModified, this, &DirectoryManager::onFileModifiedExternal);
disconnect(watcher, &DirectoryWatcher::fileRenamed, this, &DirectoryManager::onFileRenamedExternal);
}
// ##############################################################
// ####################### PUBLIC METHODS #######################
// ##############################################################
void DirectoryManager::readSettings() {
regex.setPattern(settings->supportedFormatsRegex());
}
bool DirectoryManager::setDirectory(QString dirPath) {
if(dirPath.isEmpty()) {
return false;
}
if(!std::filesystem::exists(toStdString(dirPath))) {
qDebug() << "[DirectoryManager] Error - path does not exist.";
return false;
}
if(!std::filesystem::is_directory(toStdString(dirPath))) {
qDebug() << "[DirectoryManager] Error - path is not a directory.";
return false;
}
QDir dir(dirPath);
if(!dir.isReadable()) {
qDebug() << "[DirectoryManager] Error - cannot read directory.";
return false;
}
mListSource = SOURCE_DIRECTORY;
mDirectoryPath = dirPath;
loadEntryList(dirPath, false);
sortEntryLists();
emit loaded(dirPath);
startFileWatcher(dirPath);
return true;
}
bool DirectoryManager::setDirectoryRecursive(QString dirPath) {
if(dirPath.isEmpty()) {
return false;
}
if(!std::filesystem::exists(toStdString(dirPath))) {
qDebug() << "[DirectoryManager] Error - path does not exist.";
return false;
}
if(!std::filesystem::is_directory(toStdString(dirPath))) {
qDebug() << "[DirectoryManager] Error - path is not a directory.";
return false;
}
stopFileWatcher();
mListSource = SOURCE_DIRECTORY_RECURSIVE;
mDirectoryPath = dirPath;
loadEntryList(dirPath, true);
sortEntryLists();
emit loaded(dirPath);
return true;
}
QString DirectoryManager::directoryPath() const {
if(mListSource == SOURCE_DIRECTORY || mListSource == SOURCE_DIRECTORY_RECURSIVE)
return mDirectoryPath;
else
return "";
}
int DirectoryManager::indexOfFile(QString filePath) const {
auto item = find_if(fileEntryVec.begin(), fileEntryVec.end(), [filePath](const FSEntry& e) {
return e.path == filePath;
});
if(item != fileEntryVec.end())
return distance(fileEntryVec.begin(), item);
return -1;
}
int DirectoryManager::indexOfDir(QString dirPath) const {
auto item = find_if(dirEntryVec.begin(), dirEntryVec.end(), [dirPath](const FSEntry& e) {
return e.path == dirPath;
});
if(item != dirEntryVec.end())
return distance(dirEntryVec.begin(), item);
return -1;
}
QString DirectoryManager::filePathAt(int index) const {
return checkFileRange(index) ? fileEntryVec.at(index).path : "";
}
QString DirectoryManager::fileNameAt(int index) const {
return checkFileRange(index) ? fileEntryVec.at(index).name : "";
}
QString DirectoryManager::dirPathAt(int index) const {
return checkDirRange(index) ? dirEntryVec.at(index).path : "";
}
QString DirectoryManager::dirNameAt(int index) const {
return checkDirRange(index) ? dirEntryVec.at(index).name : "";
}
QString DirectoryManager::firstFile() const {
QString filePath = "";
if(fileEntryVec.size())
filePath = fileEntryVec.front().path;
return filePath;
}
QString DirectoryManager::lastFile() const {
QString filePath = "";
if(fileEntryVec.size())
filePath = fileEntryVec.back().path;
return filePath;
}
QString DirectoryManager::prevOfFile(QString filePath) const {
QString prevFilePath = "";
int currentIndex = indexOfFile(filePath);
if(currentIndex > 0)
prevFilePath = fileEntryVec.at(currentIndex - 1).path;
return prevFilePath;
}
QString DirectoryManager::nextOfFile(QString filePath) const {
QString nextFilePath = "";
int currentIndex = indexOfFile(filePath);
if(currentIndex >= 0 && currentIndex < fileEntryVec.size() - 1)
nextFilePath = fileEntryVec.at(currentIndex + 1).path;
return nextFilePath;
}
QString DirectoryManager::prevOfDir(QString dirPath) const {
QString prevDirectoryPath = "";
int currentIndex = indexOfDir(dirPath);
if(currentIndex > 0)
prevDirectoryPath = dirEntryVec.at(currentIndex - 1).path;
return prevDirectoryPath;
}
QString DirectoryManager::nextOfDir(QString dirPath) const {
QString nextDirectoryPath = "";
int currentIndex = indexOfDir(dirPath);
if(currentIndex >= 0 && currentIndex < dirEntryVec.size() - 1)
nextDirectoryPath = dirEntryVec.at(currentIndex + 1).path;
return nextDirectoryPath;
}
bool DirectoryManager::checkFileRange(int index) const {
return index >= 0 && index < (int)fileEntryVec.size();
}
bool DirectoryManager::checkDirRange(int index) const {
return index >= 0 && index < (int)dirEntryVec.size();
}
unsigned long DirectoryManager::totalCount() const {
return fileCount() + dirCount();
}
unsigned long DirectoryManager::fileCount() const {
return fileEntryVec.size();
}
unsigned long DirectoryManager::dirCount() const {
return dirEntryVec.size();
}
const FSEntry &DirectoryManager::fileEntryAt(int index) const {
if(checkFileRange(index))
return fileEntryVec.at(index);
else
return defaultEntry;
}
QDateTime DirectoryManager::lastModified(QString filePath) const {
QFileInfo info;
if(containsFile(filePath))
info.setFile(filePath);
return info.lastModified();
}
// TODO: what about symlinks?
inline
bool DirectoryManager::isSupportedFile(QString path) const {
return ( isFile(path) && regex.match(path).hasMatch() );
}
bool DirectoryManager::isFile(QString path) const {
if(!std::filesystem::exists(toStdString(path)))
return false;
if(!std::filesystem::is_regular_file(toStdString(path)))
return false;
return true;
}
bool DirectoryManager::isDir(QString path) const {
if(!std::filesystem::exists(toStdString(path)))
return false;
if(!std::filesystem::is_directory(toStdString(path)))
return false;
return true;
}
bool DirectoryManager::isEmpty() const {
return fileEntryVec.empty();
}
bool DirectoryManager::containsFile(QString filePath) const {
return (std::find(fileEntryVec.begin(), fileEntryVec.end(), filePath) != fileEntryVec.end());
}
bool DirectoryManager::containsDir(QString dirPath) const {
return (std::find(dirEntryVec.begin(), dirEntryVec.end(), dirPath) != dirEntryVec.end());
}
// ##############################################################
// ###################### PRIVATE METHODS #######################
// ##############################################################
void DirectoryManager::loadEntryList(QString directoryPath, bool recursive) {
dirEntryVec.clear();
fileEntryVec.clear();
if(recursive) { // load files only
addEntriesFromDirectoryRecursive(fileEntryVec, directoryPath);
} else { // load dirs & files
addEntriesFromDirectory(fileEntryVec, directoryPath);
}
}
// both directories & files
void DirectoryManager::addEntriesFromDirectory(std::vector &entryVec, QString directoryPath) {
QRegularExpressionMatch match;
for(const auto & entry : fs::directory_iterator(toStdString(directoryPath))) {
QString name = QString::fromStdString(entry.path().filename().generic_string());
#ifndef Q_OS_WIN32
// ignore hidden files
if(!settings->showHiddenFiles() && name.startsWith("."))
continue;
#else
DWORD attributes = GetFileAttributes(entry.path().generic_string().c_str());
if(!settings->showHiddenFiles() && attributes & FILE_ATTRIBUTE_HIDDEN)
continue;
#endif
QString path = QString::fromStdString(entry.path().generic_string());
match = regex.match(name);
if(entry.is_directory()) { // this can still throw std::bad_alloc ..
FSEntry newEntry;
try {
newEntry.name = name;
newEntry.path = path;
newEntry.isDirectory = true;
//newEntry.size = entry.file_size();
//newEntry.modifyTime = entry.last_write_time();
} catch (const std::filesystem::filesystem_error &err) {
qDebug() << "[DirectoryManager]" << err.what();
continue;
}
dirEntryVec.emplace_back(newEntry);
} else if (match.hasMatch()) {
FSEntry newEntry;
try {
newEntry.name = name;
newEntry.path = path;
newEntry.isDirectory = false;
newEntry.size = entry.file_size();
newEntry.modifyTime = entry.last_write_time();
} catch (const std::filesystem::filesystem_error &err) {
qDebug() << "[DirectoryManager]" << err.what();
continue;
}
entryVec.emplace_back(newEntry);
}
}
}
void DirectoryManager::addEntriesFromDirectoryRecursive(std::vector &entryVec, QString directoryPath) {
QRegularExpressionMatch match;
for(const auto & entry : fs::recursive_directory_iterator(toStdString(directoryPath))) {
QString name = QString::fromStdString(entry.path().filename().generic_string());
QString path = QString::fromStdString(entry.path().generic_string());
match = regex.match(name);
if(!entry.is_directory() && match.hasMatch()) {
FSEntry newEntry;
try {
newEntry.name = name;
newEntry.path = path;
newEntry.isDirectory = false;
newEntry.size = entry.file_size();
newEntry.modifyTime = entry.last_write_time();
} catch (const std::filesystem::filesystem_error &err) {
qDebug() << "[DirectoryManager]" << err.what();
continue;
}
entryVec.emplace_back(newEntry);
}
}
}
void DirectoryManager::sortEntryLists() {
if(settings->sortFolders())
std::sort(dirEntryVec.begin(), dirEntryVec.end(), std::bind(compareFunction(), this, std::placeholders::_1, std::placeholders::_2));
else
std::sort(dirEntryVec.begin(), dirEntryVec.end(), std::bind(&DirectoryManager::path_entry_compare, this, std::placeholders::_1, std::placeholders::_2));
std::sort(fileEntryVec.begin(), fileEntryVec.end(), std::bind(compareFunction(), this, std::placeholders::_1, std::placeholders::_2));
}
void DirectoryManager::setSortingMode(SortingMode mode) {
if(mode != mSortingMode) {
mSortingMode = mode;
if(fileEntryVec.size() > 1 || dirEntryVec.size() > 1) {
sortEntryLists();
emit sortingChanged();
}
}
}
SortingMode DirectoryManager::sortingMode() const {
return mSortingMode;
}
// Entry management
bool DirectoryManager::insertFileEntry(const QString &filePath) {
if(!isSupportedFile(filePath))
return false;
return forceInsertFileEntry(filePath);
}
// skips filename regex check
bool DirectoryManager::forceInsertFileEntry(const QString &filePath) {
if(!this->isFile(filePath) || containsFile(filePath))
return false;
std::filesystem::directory_entry stdEntry(toStdString(filePath));
QString fileName = QString::fromStdString(stdEntry.path().filename().generic_string()); // isn't it beautiful
FSEntry FSEntry(filePath, fileName, stdEntry.file_size(), stdEntry.last_write_time(), stdEntry.is_directory());
insert_sorted(fileEntryVec, FSEntry, std::bind(compareFunction(), this, std::placeholders::_1, std::placeholders::_2));
if(!directoryPath().isEmpty()) {
qDebug() << "fileIns" << filePath << directoryPath();
emit fileAdded(filePath);
}
return true;
}
void DirectoryManager::removeFileEntry(const QString &filePath) {
if(!containsFile(filePath))
return;
int index = indexOfFile(filePath);
fileEntryVec.erase(fileEntryVec.begin() + index);
qDebug() << "fileRem" << filePath;
emit fileRemoved(filePath, index);
}
void DirectoryManager::updateFileEntry(const QString &filePath) {
if(!containsFile(filePath))
return;
FSEntry newEntry(filePath);
int index = indexOfFile(filePath);
if(fileEntryVec.at(index).modifyTime != newEntry.modifyTime)
fileEntryVec.at(index) = newEntry;
qDebug() << "fileMod" << filePath;
emit fileModified(filePath);
}
void DirectoryManager::renameFileEntry(const QString &oldFilePath, const QString &newFileName) {
QFileInfo fi(oldFilePath);
QString newFilePath = fi.absolutePath() + "/" + newFileName;
if(!containsFile(oldFilePath)) {
if(containsFile(newFilePath))
updateFileEntry(newFilePath);
else
insertFileEntry(newFilePath);
return;
}
if(!isSupportedFile(newFilePath)) {
removeFileEntry(oldFilePath);
return;
}
if(containsFile(newFilePath)) {
int replaceIndex = indexOfFile(newFilePath);
fileEntryVec.erase(fileEntryVec.begin() + replaceIndex);
emit fileRemoved(newFilePath, replaceIndex);
}
// remove the old one
int oldIndex = indexOfFile(oldFilePath);
fileEntryVec.erase(fileEntryVec.begin() + oldIndex);
// insert
std::filesystem::directory_entry stdEntry(toStdString(newFilePath));
FSEntry FSEntry(newFilePath, newFileName, stdEntry.file_size(), stdEntry.last_write_time(), stdEntry.is_directory());
insert_sorted(fileEntryVec, FSEntry, std::bind(compareFunction(), this, std::placeholders::_1, std::placeholders::_2));
qDebug() << "fileRen" << oldFilePath << newFilePath;
emit fileRenamed(oldFilePath, oldIndex, newFilePath, indexOfFile(newFilePath));
}
// ---- dir entries
bool DirectoryManager::insertDirEntry(const QString &dirPath) {
if(containsDir(dirPath))
return false;
std::filesystem::directory_entry stdEntry(toStdString(dirPath));
QString dirName = QString::fromStdString(stdEntry.path().filename().generic_string()); // isn't it beautiful
FSEntry FSEntry;
FSEntry.name = dirName;
FSEntry.path = dirPath;
FSEntry.isDirectory = true;
insert_sorted(dirEntryVec, FSEntry, std::bind(compareFunction(), this, std::placeholders::_1, std::placeholders::_2));
qDebug() << "dirIns" << dirPath;
emit dirAdded(dirPath);
return true;
}
void DirectoryManager::removeDirEntry(const QString &dirPath) {
if(!containsDir(dirPath))
return;
int index = indexOfDir(dirPath);
dirEntryVec.erase(dirEntryVec.begin() + index);
qDebug() << "dirRem" << dirPath;
emit dirRemoved(dirPath, index);
}
void DirectoryManager::renameDirEntry(const QString &oldDirPath, const QString &newDirName) {
if(!containsDir(oldDirPath))
return;
QFileInfo fi(oldDirPath);
QString newDirPath = fi.absolutePath() + "/" + newDirName;
// remove the old one
int oldIndex = indexOfDir(oldDirPath);
dirEntryVec.erase(dirEntryVec.begin() + oldIndex);
// insert
std::filesystem::directory_entry stdEntry(toStdString(newDirPath));
FSEntry FSEntry;
FSEntry.name = newDirName;
FSEntry.path = newDirPath;
FSEntry.isDirectory = true;
insert_sorted(dirEntryVec, FSEntry, std::bind(compareFunction(), this, std::placeholders::_1, std::placeholders::_2));
qDebug() << "dirRen" << oldDirPath << newDirPath;
emit dirRenamed(oldDirPath, oldIndex, newDirPath, indexOfDir(newDirPath));
}
FileListSource DirectoryManager::source() const {
return mListSource;
}
QStringList DirectoryManager::fileList() const {
QStringList list;
for(auto const& value : fileEntryVec)
list << value.path;
return list;
}
bool DirectoryManager::fileWatcherActive() {
if(!watcher)
return false;
return watcher->isObserving();
}
//----------------------------------------------------------------------------
// fs watcher events ( onFile___External() )
// these take file NAMES, not paths
void DirectoryManager::onFileRemovedExternal(QString fileName) {
QString fullPath = watcher->watchPath() + "/" + fileName;
removeDirEntry(fullPath);
removeFileEntry(fullPath);
}
void DirectoryManager::onFileAddedExternal(QString fileName) {
QString fullPath = watcher->watchPath() + "/" + fileName;
if(isDir(fullPath))
insertDirEntry(fullPath);
else
insertFileEntry(fullPath);
}
void DirectoryManager::onFileRenamedExternal(QString oldName, QString newName) {
QString oldPath = watcher->watchPath() + "/" + oldName;
QString newPath = watcher->watchPath() + "/" + newName;
if(isDir(newPath))
renameDirEntry(oldPath, newName);
else
renameFileEntry(oldPath, newName);
}
void DirectoryManager::onFileModifiedExternal(QString fileName) {
updateFileEntry(watcher->watchPath() + "/" + fileName);
}
qimgv-master/qimgv/components/directorymanager/directorymanager.h 0000664 0000000 0000000 00000011226 14761273276 0026072 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "settings.h"
#include "watchers/directorywatcher.h"
#include "utils/stuff.h"
#include "sourcecontainers/fsentry.h"
#ifdef Q_OS_WIN32
#include "windows.h"
#endif
enum FileListSource { // rename? wip
SOURCE_DIRECTORY,
SOURCE_DIRECTORY_RECURSIVE,
SOURCE_LIST
};
class DirectoryManager;
typedef bool (DirectoryManager::*CompareFunction)(const FSEntry &e1, const FSEntry &e2) const;
//TODO: rename? EntrySomething?
class DirectoryManager : public QObject {
Q_OBJECT
public:
DirectoryManager();
// ignored if the same dir is already opened
bool setDirectory(QString);
bool setDirectoryRecursive(QString);
QString directoryPath() const;
int indexOfFile(QString filePath) const;
int indexOfDir(QString dirPath) const;
QString filePathAt(int index) const;
unsigned long fileCount() const;
unsigned long dirCount() const;
inline bool isSupportedFile(QString filePath) const;
bool isEmpty() const;
bool containsFile(QString filePath) const;
QString fileNameAt(int index) const;
QString prevOfFile(QString filePath) const;
QString nextOfFile(QString filePath) const;
QString prevOfDir(QString filePath) const;
QString nextOfDir(QString filePath) const;
void sortEntryLists();
QDateTime lastModified(QString filePath) const;
QString firstFile() const;
QString lastFile() const;
void setSortingMode(SortingMode mode);
SortingMode sortingMode() const;
bool isFile(QString path) const;
bool isDir(QString path) const;
unsigned long totalCount() const;
bool containsDir(QString dirPath) const;
const FSEntry &fileEntryAt(int index) const;
QString dirPathAt(int index) const;
QString dirNameAt(int index) const;
bool fileWatcherActive();
bool insertFileEntry(const QString &filePath);
bool forceInsertFileEntry(const QString &filePath);
void removeFileEntry(const QString &filePath);
void updateFileEntry(const QString &filePath);
void renameFileEntry(const QString &oldFilePath, const QString &newName);
bool insertDirEntry(const QString &dirPath);
//bool forceInsertDirEntry(const QString &dirPath);
void removeDirEntry(const QString &dirPath);
//void updateDirEntry(const QString &dirPath);
void renameDirEntry(const QString &oldDirPath, const QString &newName);
FileListSource source() const;
QStringList fileList() const;
private:
QRegularExpression regex;
QCollator collator;
std::vector fileEntryVec, dirEntryVec;
const FSEntry defaultEntry;
QString mDirectoryPath;
DirectoryWatcher* watcher;
void readSettings();
SortingMode mSortingMode;
FileListSource mListSource;
void loadEntryList(QString directoryPath, bool recursive);
bool path_entry_compare(const FSEntry &e1, const FSEntry &e2) const;
bool path_entry_compare_reverse(const FSEntry &e1, const FSEntry &e2) const;
bool name_entry_compare(const FSEntry &e1, const FSEntry &e2) const;
bool name_entry_compare_reverse(const FSEntry &e1, const FSEntry &e2) const;
bool date_entry_compare(const FSEntry &e1, const FSEntry &e2) const;
bool date_entry_compare_reverse(const FSEntry &e1, const FSEntry &e2) const;
CompareFunction compareFunction();
bool size_entry_compare(const FSEntry &e1, const FSEntry &e2) const;
bool size_entry_compare_reverse(const FSEntry &e1, const FSEntry &e2) const;
void startFileWatcher(QString directoryPath);
void stopFileWatcher();
void addEntriesFromDirectory(std::vector &entryVec, QString directoryPath);
void addEntriesFromDirectoryRecursive(std::vector &entryVec, QString directoryPath);
bool checkFileRange(int index) const;
bool checkDirRange(int index) const;
private slots:
void onFileAddedExternal(QString fileName);
void onFileRemovedExternal(QString fileName);
void onFileModifiedExternal(QString fileName);
void onFileRenamedExternal(QString oldFileName, QString newFileName);
signals:
void loaded(const QString &path);
void sortingChanged();
void fileRemoved(QString filePath, int);
void fileModified(QString filePath);
void fileAdded(QString filePath);
void fileRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo);
void dirRemoved(QString dirPath, int);
void dirAdded(QString dirPath);
void dirRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo);
};
qimgv-master/qimgv/components/directorymanager/watchers/ 0000775 0000000 0000000 00000000000 14761273276 0024200 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/directorymanager/watchers/directorywatcher.cpp 0000664 0000000 0000000 00000003544 14761273276 0030274 0 ustar 00root root 0000000 0000000 #include "directorywatcher_p.h"
#if defined(__linux__) || defined(__FreeBSD__)
#include "linux/linuxwatcher.h"
#elif _WIN32
#include "windows/windowswatcher.h"
#elif __unix__
// TODO: implement this
#include "dummywatcher.h"
#elif __APPLE__
// TODO: implement this
#include "dummywatcher.h"
#else
// TODO: implement this
#include "dummywatcher.h"
#endif
#define TAG "[DirectoryWatcher]"
DirectoryWatcherPrivate::DirectoryWatcherPrivate(DirectoryWatcher* qq, WatcherWorker* w) :
q_ptr(qq),
worker(w),
workerThread(new QThread())
{
}
DirectoryWatcher::~DirectoryWatcher() {
delete d_ptr;
d_ptr = nullptr;
}
// Move this function to some creational class
DirectoryWatcher *DirectoryWatcher::newInstance()
{
DirectoryWatcher* watcher;
#if defined(__linux__) || defined(__FreeBSD__)
watcher = new LinuxWatcher();
#elif _WIN32
watcher = new WindowsWatcher();
#elif __unix__
watcher = new DummyWatcher();
#elif __APPLE__
watcher = new DummyWatcher();
#else
watcher = new DummyWatcher();
#endif
return watcher;
}
void DirectoryWatcher::setWatchPath(const QString& path) {
Q_D(DirectoryWatcher);
d->currentDirectory = path;
}
QString DirectoryWatcher::watchPath() const {
Q_D(const DirectoryWatcher);
return d->currentDirectory;
}
void DirectoryWatcher::observe()
{
Q_D(DirectoryWatcher);
if(!isObserving()) {
// Reuse worker instance
d->worker->setRunning(true);
d->workerThread->start();
}
//qDebug() << TAG << "Observing path:" << d->currentDirectory;
}
void DirectoryWatcher::stopObserving()
{
Q_D(DirectoryWatcher);
d->worker->setRunning(false);
}
bool DirectoryWatcher::isObserving()
{
Q_D(DirectoryWatcher);
return d->workerThread->isRunning();
}
DirectoryWatcher::DirectoryWatcher(DirectoryWatcherPrivate* ptr) {
d_ptr = ptr;
}
qimgv-master/qimgv/components/directorymanager/watchers/directorywatcher.h 0000664 0000000 0000000 00000001463 14761273276 0027737 0 ustar 00root root 0000000 0000000 #pragma once
#include
class DirectoryWatcherPrivate;
class DirectoryWatcher : public QObject {
Q_OBJECT
public:
static DirectoryWatcher* newInstance();
virtual ~DirectoryWatcher();
virtual void setWatchPath(const QString& watchPath);
virtual QString watchPath() const;
bool isObserving();
public Q_SLOTS:
void observe();
void stopObserving();
signals:
void fileCreated(const QString& filePath);
void fileDeleted(const QString& filePath);
void fileRenamed(const QString& old, const QString& now);
void fileModified(const QString& filePath);
void observingStarted();
void observingStopped();
protected:
DirectoryWatcher(DirectoryWatcherPrivate *ptr);
DirectoryWatcherPrivate* d_ptr;
private:
Q_DECLARE_PRIVATE(DirectoryWatcher)
};
qimgv-master/qimgv/components/directorymanager/watchers/directorywatcher_p.h 0000664 0000000 0000000 00000001305 14761273276 0030251 0 ustar 00root root 0000000 0000000 #ifndef DIRECTORYWATCHER_P_H
#define DIRECTORYWATCHER_P_H
#include "directorywatcher.h"
#include "watcherevent.h"
#include "watcherworker.h"
#include
#include
#include
#include
#include
#include
class DirectoryWatcherPrivate : public QObject {
Q_OBJECT
public:
explicit DirectoryWatcherPrivate(DirectoryWatcher* qq, WatcherWorker *w);
DirectoryWatcher* q_ptr;
QVector> directoryEvents;
QScopedPointer worker;
QScopedPointer workerThread;
QString currentDirectory;
private:
Q_DECLARE_PUBLIC(DirectoryWatcher)
};
#endif // DIRECTORYWATCHER_P_H
qimgv-master/qimgv/components/directorymanager/watchers/dummywatcher.cpp 0000664 0000000 0000000 00000001244 14761273276 0027416 0 ustar 00root root 0000000 0000000 #include "dummywatcher.h"
#include "directorywatcher_p.h"
#include
#define TAG "[DummyWatcher]"
#define MESSAGE "Directory watcher isn't yet implemented for your operating system"
class DummyWatcherWorker : public WatcherWorker {
public:
DummyWatcherWorker() {}
virtual void run() override {
qDebug() << TAG << MESSAGE;
}
};
class DummyWatcherPrivate : public DirectoryWatcherPrivate {
public:
DummyWatcherPrivate(DirectoryWatcher* watcher) : DirectoryWatcherPrivate(watcher, new DummyWatcherWorker()) {}
};
DummyWatcher::DummyWatcher() : DirectoryWatcher(new DummyWatcherPrivate(this))
{
qDebug() << TAG << MESSAGE;
}
qimgv-master/qimgv/components/directorymanager/watchers/dummywatcher.h 0000664 0000000 0000000 00000000173 14761273276 0027063 0 ustar 00root root 0000000 0000000 #pragma once
#include "directorywatcher.h"
class DummyWatcher : public DirectoryWatcher
{
public:
DummyWatcher();
};
qimgv-master/qimgv/components/directorymanager/watchers/linux/ 0000775 0000000 0000000 00000000000 14761273276 0025337 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxfsevent.cpp 0000664 0000000 0000000 00000000724 14761273276 0030600 0 ustar 00root root 0000000 0000000 #include
#include "linuxfsevent.h"
LinuxFsEvent::LinuxFsEvent(char *data, uint dataSize) :
mData(data),
mDataSize(dataSize)
{
}
LinuxFsEvent::~LinuxFsEvent() {
delete[] mData;
}
uint LinuxFsEvent::dataSize() const {
return mDataSize;
}
void LinuxFsEvent::setDataSize(uint bufferSize) {
mDataSize = bufferSize;
}
char *LinuxFsEvent::data() const {
return mData;
}
void LinuxFsEvent::setData(char *buffer) {
mData = buffer;
}
qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxfsevent.h 0000664 0000000 0000000 00000000475 14761273276 0030250 0 ustar 00root root 0000000 0000000 #pragma once
#include
class LinuxFsEvent : public QObject
{
public:
LinuxFsEvent(char* data, uint dataSize);
~LinuxFsEvent();
uint dataSize() const;
void setDataSize(uint dataSize);
char *data() const;
void setData(char *data);
private:
char* mData;
uint mDataSize;
};
qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxwatcher.cpp 0000664 0000000 0000000 00000015207 14761273276 0030565 0 ustar 00root root 0000000 0000000 #include
#include
#include "linuxwatcher_p.h"
#include "linuxworker.h"
#define TAG "[LinuxDirectoryWatcher]"
#define INOTIFY_EVENT_MASK IN_CREATE | IN_MODIFY | IN_DELETE | IN_MOVE
/**
* Time to wait for rename event. If event take time longer
* than specified then event will be considered as remove event
*/
// TODO: this may break event order.
// Implement a proper queue.
#define EVENT_MOVE_TIMEOUT 150 // ms
#define EVENT_MODIFY_TIMEOUT 150 // ms
LinuxWatcherPrivate::LinuxWatcherPrivate(LinuxWatcher* qq) :
DirectoryWatcherPrivate(qq, new LinuxWorker()),
watcher(-1),
watchObject(-1)
{
watcher = inotify_init();
}
int LinuxWatcherPrivate::indexOfWatcherEvent(uint cookie) const {
for (int i = 0; i < watcherEvents.size(); ++i) {
auto event = watcherEvents.at(i);
if (event->cookie() == cookie) {
return i;
}
}
return -1;
}
int LinuxWatcherPrivate::indexOfWatcherEvent(const QString& name) const {
for (int i = 0; i < watcherEvents.size(); ++i) {
auto event = watcherEvents.at(i);
if (event->name() == name) {
return i;
}
}
return -1;
}
void LinuxWatcherPrivate::dispatchFilesystemEvent(LinuxFsEvent* e) {
Q_Q(LinuxWatcher);
uint dataOffset = 0;
QScopedPointer event(e);
while (dataOffset < event->dataSize()) {
inotify_event* notify_event = (inotify_event*) (event->data() + dataOffset);
dataOffset += sizeof(inotify_event) + notify_event->len;
int mask = notify_event->mask;
QString name = notify_event->name;
uint cookie = notify_event->cookie;
bool isDirEvent = mask & IN_ISDIR;
// Skip events for directories and files that isn't in filter range
/*if((isDirEvent) && !(mask & IN_MOVED_TO) ) {
continue;
}*/
if (mask & IN_MODIFY) {
handleModifyEvent(name);
} else if (mask & IN_CREATE) {
handleCreateEvent(name);
} else if (mask & IN_DELETE) {
handleDeleteEvent(name);
} else if (mask & IN_MOVED_FROM) {
handleMovedFromEvent(name, cookie);
} else if (mask & IN_MOVED_TO) {
handleMovedToEvent(name, cookie);
}
}
}
void LinuxWatcherPrivate::handleModifyEvent(const QString &name) {
// Find the same event in the list by file name
int eventIndex = indexOfWatcherEvent(name);
if (eventIndex == -1) {
// This is this first modify event for the current file
int timerId = startTimer(EVENT_MODIFY_TIMEOUT);
auto event = new WatcherEvent(name, timerId, WatcherEvent::Modify);
watcherEvents.append(QSharedPointer(event));
} else {
auto event = watcherEvents.at(eventIndex);
// Restart timer again
killTimer(event->timerId());
int timerId = startTimer(EVENT_MODIFY_TIMEOUT);
event->setTimerId(timerId);
}
}
void LinuxWatcherPrivate::handleDeleteEvent(const QString &name) {
Q_Q(LinuxWatcher);
emit q->fileDeleted(name);
}
void LinuxWatcherPrivate::handleCreateEvent(const QString &name) {
Q_Q(LinuxWatcher);
emit q->fileCreated(name);
}
void LinuxWatcherPrivate::handleMovedFromEvent(const QString &name, uint cookie) {
int timerId = startTimer(EVENT_MOVE_TIMEOUT);
// Save timer id to find out later which event timer is running
auto event = new WatcherEvent(name, cookie, timerId, WatcherEvent::MovedFrom);
watcherEvents.append(QSharedPointer(event));
}
void LinuxWatcherPrivate::handleMovedToEvent(const QString &name, uint cookie) {
Q_Q(LinuxWatcher);
// Check if file waiting to be renamed
int eventIndex = indexOfWatcherEvent(cookie);
if (eventIndex == -1) {
// No one event waiting for rename so this is a new file
emit q->fileCreated(name);
} else {
// Waiting for rename event is found
auto watcherEvent = watcherEvents.takeAt(eventIndex);
// Kill associated timer
killTimer(watcherEvent->timerId());
emit q->fileRenamed(watcherEvent->name(), name);
}
}
void LinuxWatcherPrivate::timerEvent(QTimerEvent *timerEvent) {
Q_Q(LinuxWatcher);
// Loop through waiting move events
int lastIndex = watcherEvents.size() - 1;
for (int i = lastIndex; i >= 0; --i) {
auto watcherEvent = watcherEvents.at(i);
if (watcherEvent->timerId() == timerEvent->timerId()) {
int type = watcherEvent->type();
if (type == WatcherEvent::MovedFrom) {
// Rename event didn't happen so treat this event as remove event
emit q->fileDeleted(watcherEvent->name());
} else if (type == WatcherEvent::Modify) {
emit q->fileModified(watcherEvent->name());
}
watcherEvents.removeAt(i);
break;
}
}
// Stop timer anyway
killTimer(timerEvent->timerId());
}
LinuxWatcher::LinuxWatcher() : DirectoryWatcher(new LinuxWatcherPrivate(this)) {
Q_D(LinuxWatcher);
connect(d->workerThread.data(), &QThread::started, d->worker.data(), &WatcherWorker::run);
d->worker.data()->moveToThread(d->workerThread.data());
auto linuxWorker = static_cast(d->worker.data());
linuxWorker->setDescriptor(d->watcher);
connect(linuxWorker, &LinuxWorker::fileEvent,
d, &LinuxWatcherPrivate::dispatchFilesystemEvent);
// Here's no need to destroy thread and worker. They're will be removed automatically
connect(linuxWorker, &LinuxWorker::finished, d->workerThread.data(), &QThread::quit);
connect(linuxWorker, &LinuxWorker::started, this, &LinuxWatcher::observingStarted);
connect(linuxWorker, &LinuxWorker::finished, this, &LinuxWatcher::observingStopped);
}
LinuxWatcher::~LinuxWatcher() {
Q_D(LinuxWatcher);
int removeStatusCode = inotify_rm_watch(d->watcher, d->watchObject);
if (removeStatusCode != 0) {
qDebug() << TAG << "Cannot remove inotify watcher instance:" << strerror(errno);
}
}
void LinuxWatcher::setWatchPath(const QString& path) {
Q_D(LinuxWatcher);
DirectoryWatcher::setWatchPath(path);
// Subscribe for specified filesystem events
if (d->watchObject != -1) {
int status = inotify_rm_watch(d->watcher, d->watchObject);
if (status == -1) {
qDebug() << TAG << "Error:" << strerror(errno);
}
}
// Add new path to be watched by inotify
d->watchObject = inotify_add_watch(d->watcher, path.toStdString().data(), INOTIFY_EVENT_MASK);
if (d->watchObject == -1) {
qDebug() << TAG << "Error:" << strerror(errno);
}
}
qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxwatcher.h 0000664 0000000 0000000 00000000454 14761273276 0030230 0 ustar 00root root 0000000 0000000 #pragma once
#include "../directorywatcher.h"
class LinuxWatcherPrivate;
class LinuxWatcher : public DirectoryWatcher {
Q_OBJECT
public:
explicit LinuxWatcher();
virtual ~LinuxWatcher();
virtual void setWatchPath(const QString& p);
private:
Q_DECLARE_PRIVATE(LinuxWatcher)
};
qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxwatcher_p.h 0000664 0000000 0000000 00000002044 14761273276 0030544 0 ustar 00root root 0000000 0000000 #ifndef LINUXDIRECTORYWATCHER_P_H
#define LINUXDIRECTORYWATCHER_P_H
#include "../linux/linuxwatcher.h"
#include "../directorywatcher_p.h"
#include
#include
#include
class LinuxFsEvent;
class LinuxWatcherPrivate : public DirectoryWatcherPrivate {
Q_OBJECT
public:
explicit LinuxWatcherPrivate(LinuxWatcher* qq = 0);
int indexOfWatcherEvent(uint cookie) const;
int indexOfWatcherEvent(const QString& name) const;
void handleModifyEvent(const QString& name);
void handleDeleteEvent(const QString& name);
void handleCreateEvent(const QString& name);
void handleMovedFromEvent(const QString& name, uint cookie);
void handleMovedToEvent(const QString& name, uint cookie);
int watcher;
int watchObject;
QVector> watcherEvents;
protected:
virtual void timerEvent(QTimerEvent* timerEvent) override;
private slots:
void dispatchFilesystemEvent(LinuxFsEvent *e);
private:
Q_DECLARE_PUBLIC(LinuxWatcher)
};
#endif // LINUXDIRECTORYWATCHER_P_H
qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxworker.cpp 0000664 0000000 0000000 00000003014 14761273276 0030432 0 ustar 00root root 0000000 0000000 #include
#include
#include
#include
#include
#include "linuxworker.h"
#define TAG "[LinuxWatcherWorker]"
#define TIMEOUT 300 // ms
LinuxWorker::LinuxWorker() :
fd(-1)
{
}
void LinuxWorker::setDescriptor(int desc) {
fd = desc;
}
void LinuxWorker::run() {
emit started();
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
isRunning.store(true);
#else
isRunning.storeRelaxed(true);
#endif
if (fd == -1) {
qDebug() << TAG << "File descriptor isn't set! Stopping";
emit finished();
return;
}
while (isRunning) {
int errorCode = 0;
uint bytesAvailable = 0;
// File descriptor event struct for polling service
pollfd pollDescriptor = { fd, POLLIN, 0 };
// Freeze thread till next event
errorCode = poll(&pollDescriptor, 1, TIMEOUT);
handleErrorCode(errorCode);
// Check how many bytes available
errorCode = ioctl(fd, FIONREAD, &bytesAvailable);
handleErrorCode(errorCode);
if (bytesAvailable == 0) {
continue;
}
char* eventData = new char[bytesAvailable];
errorCode = read(fd, eventData, bytesAvailable);
handleErrorCode(errorCode);
emit fileEvent(new LinuxFsEvent(eventData, bytesAvailable));
}
emit finished();
}
void LinuxWorker::handleErrorCode(int code) {
if (code == -1) {
qDebug() << TAG << strerror(errno);
emit error(strerror(errno));
}
}
qimgv-master/qimgv/components/directorymanager/watchers/linux/linuxworker.h 0000664 0000000 0000000 00000000517 14761273276 0030104 0 ustar 00root root 0000000 0000000 #pragma once
#include "linuxfsevent.h"
#include "../watcherworker.h"
class LinuxWorker : public WatcherWorker
{
Q_OBJECT
public:
LinuxWorker();
void setDescriptor(int desc);
void handleErrorCode(int code);
virtual void run() override;
signals:
void fileEvent(LinuxFsEvent* event);
private:
int fd;
};
qimgv-master/qimgv/components/directorymanager/watchers/watcherevent.cpp 0000664 0000000 0000000 00000001642 14761273276 0027406 0 ustar 00root root 0000000 0000000 #include
#include "watcherevent.h"
WatcherEvent::WatcherEvent(const QString &name, int timerId, WatcherEvent::Type type) :
mName(name),
mTimerId(timerId),
mType(type)
{
}
WatcherEvent::WatcherEvent(const QString& name, uint cookie, int timerId, Type type) :
mName(name),
mCookie(cookie),
mTimerId(timerId),
mType(type)
{
}
WatcherEvent::~WatcherEvent() {
}
QString WatcherEvent::name() const {
return mName;
}
void WatcherEvent::setName(const QString &name) {
mName = name;
}
WatcherEvent::Type WatcherEvent::type() const {
return mType;
}
void WatcherEvent::setType(WatcherEvent::Type type) {
mType = type;
}
int WatcherEvent::timerId() const {
return mTimerId;
}
void WatcherEvent::setTimerId(int timerId) {
mTimerId = timerId;
}
uint WatcherEvent::cookie() const {
return mCookie;
}
void WatcherEvent::setCookie(uint cookie) {
mCookie = cookie;
}
qimgv-master/qimgv/components/directorymanager/watchers/watcherevent.h 0000664 0000000 0000000 00000001210 14761273276 0027042 0 ustar 00root root 0000000 0000000 #pragma once
#include
class WatcherEvent {
public:
enum Type {
None,
MovedFrom,
MovedTo,
Modify
};
WatcherEvent(const QString &name,int timerId, Type type = None);
WatcherEvent(const QString& name, uint cookie, int timerId, Type type = None);
~WatcherEvent();
QString name() const;
void setName(const QString& name);
uint cookie() const;
void setCookie(uint cookie);
int timerId() const;
void setTimerId(int timerId);
Type type() const;
void setType(Type type);
private:
QString mName;
uint mCookie;
int mTimerId;
Type mType;
};
qimgv-master/qimgv/components/directorymanager/watchers/watcherworker.cpp 0000664 0000000 0000000 00000000260 14761273276 0027571 0 ustar 00root root 0000000 0000000 #include "watcherworker.h"
#include
WatcherWorker::WatcherWorker()
{
}
void WatcherWorker::setRunning(bool running) {
isRunning.fetchAndStoreRelaxed(running);
}
qimgv-master/qimgv/components/directorymanager/watchers/watcherworker.h 0000664 0000000 0000000 00000000516 14761273276 0027242 0 ustar 00root root 0000000 0000000 #pragma once
#include
class WatcherWorker : public QObject
{
Q_OBJECT
public:
WatcherWorker();
virtual void run() = 0;
public Q_SLOTS:
void setRunning(bool running);
Q_SIGNALS:
void error(const QString& errorMessage);
void started();
void finished();
protected:
QAtomicInt isRunning;
};
qimgv-master/qimgv/components/directorymanager/watchers/windows/ 0000775 0000000 0000000 00000000000 14761273276 0025672 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/directorymanager/watchers/windows/windowswatcher.cpp 0000664 0000000 0000000 00000010400 14761273276 0031441 0 ustar 00root root 0000000 0000000 #include "windowswatcher_p.h"
#include "windowsworker.h"
QString lastError() {
char buffer[1024];
DWORD lastError = GetLastError();
int res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
nullptr,
lastError,
LANG_SYSTEM_DEFAULT,
buffer,
sizeof(buffer),
nullptr);
QString line = QString(__FILE__) + "::" + QString::number(__LINE__) + ": ";
return res == 0 ? QString::number(GetLastError()) : line + buffer;
}
WindowsWatcherPrivate::WindowsWatcherPrivate(WindowsWatcher* qq)
: DirectoryWatcherPrivate(qq, new WindowsWorker())
{
auto windowsWorker = static_cast(worker.data());
qRegisterMetaType("PFILE_NOTIFY_INFORMATION");
connect(windowsWorker, SIGNAL(notifyEvent(PFILE_NOTIFY_INFORMATION)),
this, SLOT(dispatchNotify(PFILE_NOTIFY_INFORMATION)));
}
HANDLE WindowsWatcherPrivate::requestDirectoryHandle(const QString& path)
{
HANDLE hDirectory;
do {
hDirectory = CreateFileW(
path.toStdWString().c_str(),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
if (hDirectory == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_SHARING_VIOLATION)
{
qDebug() << "ERROR_SHARING_VIOLATION waiting for 1 sec";
QThread::sleep(1);
}
else
{
qDebug() << lastError();
return INVALID_HANDLE_VALUE;
}
}
} while (hDirectory == INVALID_HANDLE_VALUE);
return hDirectory;
}
void WindowsWatcherPrivate::dispatchNotify(PFILE_NOTIFY_INFORMATION notify) {
Q_Q(WindowsWatcher);
int len = notify->FileNameLength / sizeof(WCHAR);
QString name = QString::fromWCharArray(static_cast(notify->FileName), len);
switch (notify->Action)
{
case FILE_ACTION_ADDED:
emit q->fileCreated(name);
break;
case FILE_ACTION_MODIFIED:
emit q->fileModified(name);
// ??
/*WatcherEvent* event;
if (findEventIndexByName(name) != -1)
return;
event = new WatcherEvent(name, WatcherEvent::MODIFIED);
event->mTimerId = startTimer(500);
directoryEvents.push_back(event);
*/
break;
case FILE_ACTION_REMOVED:
emit q->fileDeleted(name);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
emit q->fileRenamed(oldFileName, name);
break;
case FILE_ACTION_RENAMED_OLD_NAME:
oldFileName = name;
break;
default:
qDebug() << "Some error, notify->Action" << notify->Action;
}
}
WindowsWatcher::WindowsWatcher()
: DirectoryWatcher(new WindowsWatcherPrivate(this))
{
Q_D(WindowsWatcher);
connect(d->workerThread.data(), &QThread::started, d->worker.data(), &WatcherWorker::run);
d->worker.data()->moveToThread(d->workerThread.data());
auto windowsWorker = static_cast(d->worker.data());
connect(windowsWorker, &WindowsWorker::finished, d->workerThread.data(), &QThread::quit);
connect(windowsWorker, &WindowsWorker::started, this, &WindowsWatcher::observingStarted);
connect(windowsWorker, &WindowsWorker::finished, this, &WindowsWatcher::observingStopped);
}
WindowsWatcher::WindowsWatcher(const QString& path)
: DirectoryWatcher(new WindowsWatcherPrivate(this))
{
Q_D(WindowsWatcher);
setWatchPath(path);
}
void WindowsWatcher::setWatchPath(const QString &path) {
Q_D(WindowsWatcher);
DirectoryWatcher::setWatchPath(path);
HANDLE hDirectory = d->requestDirectoryHandle(path);
if (hDirectory == INVALID_HANDLE_VALUE)
{
qDebug() << "requestDirectoryHandle: INVALID_HANDLE_VALUE";
return;
}
auto windowsWorker = static_cast(d->worker.data());
windowsWorker->setDirectoryHandle(hDirectory);
}
qimgv-master/qimgv/components/directorymanager/watchers/windows/windowswatcher.h 0000664 0000000 0000000 00000000615 14761273276 0031115 0 ustar 00root root 0000000 0000000 #ifndef WINDOWSWATCHER_H
#define WINDOWSWATCHER_H
#include "../directorywatcher.h"
class WindowsWatcherPrivate;
class WindowsWatcher : public DirectoryWatcher {
Q_OBJECT
public:
explicit WindowsWatcher();
explicit WindowsWatcher(const QString &path);
virtual void setWatchPath(const QString& path);
private:
Q_DECLARE_PRIVATE(WindowsWatcher)
};
#endif // WINDOWSWATCHER_H
qimgv-master/qimgv/components/directorymanager/watchers/windows/windowswatcher_p.h 0000664 0000000 0000000 00000001115 14761273276 0031430 0 ustar 00root root 0000000 0000000 #ifndef WINDOWSWATCHER_P_H
#define WINDOWSWATCHER_P_H
#include "../windows/windowswatcher.h"
#include "../directorywatcher_p.h"
#include
#include
#include
QString lastError();
class WindowsWatcherPrivate : public DirectoryWatcherPrivate {
Q_OBJECT
public:
explicit WindowsWatcherPrivate(WindowsWatcher* qq = 0);
HANDLE requestDirectoryHandle(const QString& path);
QString oldFileName;
public slots:
void dispatchNotify(PFILE_NOTIFY_INFORMATION notify);
private:
Q_DECLARE_PUBLIC(WindowsWatcher)
};
#endif // WINDOWSWATCHER_P_H
qimgv-master/qimgv/components/directorymanager/watchers/windows/windowsworker.cpp 0000664 0000000 0000000 00000004252 14761273276 0031325 0 ustar 00root root 0000000 0000000 #include "windowsworker.h"
WindowsWorker::WindowsWorker() : WatcherWorker() {
}
void WindowsWorker::setDirectoryHandle(HANDLE hDir) {
//qDebug() << "setHandle" << this->hDir << " -> " << hDir;
freeHandle();
this->hDir = hDir;
}
void WindowsWorker::freeHandle() {
CancelIoEx(this->hDir, NULL);
CloseHandle(this->hDir);
}
void WindowsWorker::run() {
isRunning = true;
DWORD error = 0;
bool bPending = false;
DWORD dwBytes = 0;
OVERLAPPED ovl = {0};
std::vector buffer(1024*64);
ovl.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
if(!ovl.hEvent) {
qDebug() << "[WindowsWorker] CreateEvent failed?";
}
::ResetEvent(ovl.hEvent); // is this needed?
while(isRunning) {
//qDebug() << "_1";
bPending = ReadDirectoryChangesW(hDir,
&buffer[0],
buffer.size(),
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
&dwBytes,
&ovl,
nullptr);
//qDebug() << "_2";
if(!bPending) {
error = GetLastError();
if(error == ERROR_IO_INCOMPLETE) {
qDebug() << "ERROR_IO_INCOMPLETE";
continue;
}
}
//qDebug() << "_3";
bool WAIT = false;
if(GetOverlappedResult(hDir, &ovl, &dwBytes, WAIT)) {
bPending = false;
if(dwBytes != 0) {
FILE_NOTIFY_INFORMATION *fni = reinterpret_cast(&buffer[0]);
do {
if(fni->Action != 0) {
emit notifyEvent(fni);
}
if(fni->NextEntryOffset == 0)
break;
fni = reinterpret_cast(reinterpret_cast(fni) + fni->NextEntryOffset);
} while (true);
}
}
Sleep(POLL_RATE_MS);
}
}
qimgv-master/qimgv/components/directorymanager/watchers/windows/windowsworker.h 0000664 0000000 0000000 00000001075 14761273276 0030772 0 ustar 00root root 0000000 0000000 #ifndef WINDOWSWATCHERWORKER_H
#define WINDOWSWATCHERWORKER_H
#include
#include "../watcherworker.h"
#include
class WindowsWorker : public WatcherWorker {
Q_OBJECT
public:
WindowsWorker();
void setDirectoryHandle(HANDLE hDir);
virtual void run() override;
signals:
void notifyEvent(PFILE_NOTIFY_INFORMATION);
private:
HANDLE hDir;
WCHAR buffer[1024];
DWORD bytesReturned;
uint POLL_RATE_MS = 1000;
void processEvent(FILE_NOTIFY_INFORMATION *fni);
void freeHandle();
};
#endif // WINDOWSWATCHERWORKER_H
qimgv-master/qimgv/components/directorymodel.cpp 0000664 0000000 0000000 00000023620 14761273276 0022555 0 ustar 00root root 0000000 0000000 #include "directorymodel.h"
DirectoryModel::DirectoryModel(QObject *parent) :
QObject(parent),
fileListSource(SOURCE_DIRECTORY)
{
scaler = new Scaler(&cache);
connect(&dirManager, &DirectoryManager::fileRemoved, this, &DirectoryModel::onFileRemoved);
connect(&dirManager, &DirectoryManager::fileAdded, this, &DirectoryModel::onFileAdded);
connect(&dirManager, &DirectoryManager::fileRenamed, this, &DirectoryModel::onFileRenamed);
connect(&dirManager, &DirectoryManager::fileModified, this, &DirectoryModel::onFileModified);
connect(&dirManager, &DirectoryManager::dirRemoved, this, &DirectoryModel::dirRemoved);
connect(&dirManager, &DirectoryManager::dirAdded, this, &DirectoryModel::dirAdded);
connect(&dirManager, &DirectoryManager::dirRenamed, this, &DirectoryModel::dirRenamed);
connect(&dirManager, &DirectoryManager::loaded, this, &DirectoryModel::loaded);
connect(&dirManager, &DirectoryManager::sortingChanged, this, &DirectoryModel::onSortingChanged);
connect(&loader, &Loader::loadFinished, this, &DirectoryModel::onImageReady);
connect(&loader, &Loader::loadFailed, this, &DirectoryModel::loadFailed);
}
DirectoryModel::~DirectoryModel() {
loader.clearTasks();
delete scaler;
}
int DirectoryModel::totalCount() const {
return dirManager.totalCount();
}
int DirectoryModel::fileCount() const {
return dirManager.fileCount();
}
int DirectoryModel::dirCount() const {
return dirManager.dirCount();
}
int DirectoryModel::indexOfFile(QString filePath) const {
return dirManager.indexOfFile(filePath);
}
int DirectoryModel::indexOfDir(QString filePath) const {
return dirManager.indexOfDir(filePath);
}
SortingMode DirectoryModel::sortingMode() const {
return dirManager.sortingMode();
}
const FSEntry &DirectoryModel::fileEntryAt(int index) const {
return dirManager.fileEntryAt(index);
}
QString DirectoryModel::fileNameAt(int index) const {
return dirManager.fileNameAt(index);
}
QString DirectoryModel::filePathAt(int index) const {
return dirManager.filePathAt(index);
}
QString DirectoryModel::dirNameAt(int index) const {
return dirManager.dirNameAt(index);
}
QString DirectoryModel::dirPathAt(int index) const {
return dirManager.dirPathAt(index);
}
bool DirectoryModel::autoRefresh() {
return dirManager.fileWatcherActive();
}
FileListSource DirectoryModel::source() {
return dirManager.source();
}
QString DirectoryModel::directoryPath() const {
return dirManager.directoryPath();
}
bool DirectoryModel::containsFile(QString filePath) const {
return dirManager.containsFile(filePath);
}
bool DirectoryModel::containsDir(QString dirPath) const {
return dirManager.containsDir(dirPath);
}
bool DirectoryModel::isEmpty() const {
return dirManager.isEmpty();
}
QString DirectoryModel::firstFile() const {
return dirManager.firstFile();
}
QString DirectoryModel::lastFile() const {
return dirManager.lastFile();
}
QString DirectoryModel::nextOf(QString filePath) const {
return dirManager.nextOfFile(filePath);
}
QString DirectoryModel::prevOf(QString filePath) const {
return dirManager.prevOfFile(filePath);
}
QDateTime DirectoryModel::lastModified(QString filePath) const {
return dirManager.lastModified(filePath);
}
// -----------------------------------------------------------------------------
bool DirectoryModel::forceInsert(QString filePath) {
return dirManager.forceInsertFileEntry(filePath);
}
void DirectoryModel::setSortingMode(SortingMode mode) {
dirManager.setSortingMode(mode);
}
void DirectoryModel::removeFile(const QString &filePath, bool trash, FileOpResult &result) {
if(trash)
FileOperations::moveToTrash(filePath, result);
else
FileOperations::removeFile(filePath, result);
if(result != FileOpResult::SUCCESS)
return;
dirManager.removeFileEntry(filePath);
return;
}
void DirectoryModel::renameEntry(const QString &oldPath, const QString &newName, bool force, FileOpResult &result) {
bool isDir = dirManager.isDir(oldPath);
FileOperations::rename(oldPath, newName, force, result);
// chew through watcher events so they wont be processed out of order
qApp->processEvents();
if(result != FileOpResult::SUCCESS)
return;
if(isDir)
dirManager.renameDirEntry(oldPath, newName);
else
dirManager.renameFileEntry(oldPath, newName);
}
void DirectoryModel::removeDir(const QString &dirPath, bool trash, bool recursive, FileOpResult &result) {
if(trash) {
FileOperations::moveToTrash(dirPath, result);
} else {
FileOperations::removeDir(dirPath, recursive, result);
}
if(result != FileOpResult::SUCCESS)
return;
dirManager.removeDirEntry(dirPath);
return;
}
void DirectoryModel::copyFileTo(const QString &srcFile, const QString &destDirPath, bool force, FileOpResult &result) {
FileOperations::copyFileTo(srcFile, destDirPath, force, result);
}
void DirectoryModel::moveFileTo(const QString &srcFile, const QString &destDirPath, bool force, FileOpResult &result) {
FileOperations::moveFileTo(srcFile, destDirPath, force, result);
// chew through watcher events so they wont be processed out of order
qApp->processEvents();
if(result == FileOpResult::SUCCESS) {
if(destDirPath != this->directoryPath())
dirManager.removeFileEntry(srcFile);
}
}
// -----------------------------------------------------------------------------
bool DirectoryModel::setDirectory(QString path) {
cache.clear();
return dirManager.setDirectory(path);
}
void DirectoryModel::unload(int index) {
QString filePath = this->filePathAt(index);
cache.remove(filePath);
}
void DirectoryModel::unload(QString filePath) {
cache.remove(filePath);
}
void DirectoryModel::unloadExcept(QString filePath, bool keepNearby) {
QList list;
list << filePath;
if(keepNearby) {
list << prevOf(filePath);
list << nextOf(filePath);
}
cache.trimTo(list);
}
bool DirectoryModel::loaderBusy() const {
return loader.isBusy();
}
void DirectoryModel::onImageReady(std::shared_ptr img, const QString &path) {
if(!img) {
emit loadFailed(path);
return;
}
cache.remove(path);
cache.insert(img);
emit imageReady(img, path);
}
bool DirectoryModel::saveFile(const QString &filePath) {
return saveFile(filePath, filePath);
}
bool DirectoryModel::saveFile(const QString &filePath, const QString &destPath) {
if(!containsFile(filePath) || !cache.contains(filePath))
return false;
auto img = cache.get(filePath);
if(img->save(destPath)) {
if(filePath == destPath) { // replace
dirManager.updateFileEntry(destPath);
emit fileModified(destPath);
} else { // manually add if we are saving to the same dir
QFileInfo fiSrc(filePath);
QFileInfo fiDest(destPath);
// handle same dir
if(fiSrc.absolutePath() == fiDest.absolutePath()) {
// overwrite
if(!dirManager.containsFile(destPath) && dirManager.insertFileEntry(destPath))
emit fileModified(destPath);
}
}
return true;
}
return false;
}
// dirManager events
void DirectoryModel::onSortingChanged() {
emit sortingChanged(sortingMode());
}
void DirectoryModel::onFileAdded(QString filePath) {
emit fileAdded(filePath);
}
void DirectoryModel::onFileModified(QString filePath) {
QDateTime modTime = lastModified(filePath);
if(modTime.isValid()) {
auto img = cache.get(filePath);
if(img) {
// check if file on disk is different
if(modTime != img->lastModified())
reload(filePath);
}
emit fileModified(filePath);
}
}
void DirectoryModel::onFileRemoved(QString filePath, int index) {
unload(filePath);
emit fileRemoved(filePath, index);
}
void DirectoryModel::onFileRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo) {
unload(fromPath);
emit fileRenamed(fromPath, indexFrom, toPath, indexTo);
}
bool DirectoryModel::isLoaded(int index) const {
return cache.contains(filePathAt(index));
}
bool DirectoryModel::isLoaded(QString filePath) const {
return cache.contains(filePath);
}
std::shared_ptr DirectoryModel::getImageAt(int index) {
return getImage(filePathAt(index));
}
// returns cached image
// if image is not cached, loads it in the main thread
// for async access use loadAsync(), then catch onImageReady()
std::shared_ptr DirectoryModel::getImage(QString filePath) {
std::shared_ptr img = cache.get(filePath);
if(!img)
img = loader.load(filePath);
return img;
}
void DirectoryModel::updateImage(QString filePath, std::shared_ptr img) {
if(containsFile(filePath) /*& cache.contains(filePath)*/) {
if(!cache.contains(filePath)) {
cache.insert(img);
} else {
cache.insert(img);
emit imageUpdated(filePath);
}
}
}
void DirectoryModel::load(QString filePath, bool asyncHint) {
if(!containsFile(filePath) || loader.isLoading(filePath))
return;
if(!cache.contains(filePath)) {
if(asyncHint) {
loader.loadAsyncPriority(filePath);
} else {
auto img = loader.load(filePath);
if(img) {
cache.insert(img);
emit imageReady(img, filePath);
} else {
emit loadFailed(filePath);
}
}
} else {
emit imageReady(cache.get(filePath), filePath);
}
}
void DirectoryModel::reload(QString filePath) {
if(cache.contains(filePath)) {
cache.remove(filePath);
dirManager.updateFileEntry(filePath);
load(filePath, false);
}
}
void DirectoryModel::preload(QString filePath) {
if(containsFile(filePath) && !cache.contains(filePath))
loader.loadAsync(filePath);
}
qimgv-master/qimgv/components/directorymodel.h 0000664 0000000 0000000 00000006743 14761273276 0022231 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include "cache/cache.h"
#include "directorymanager/directorymanager.h"
#include "scaler/scaler.h"
#include "loader/loader.h"
#include "utils/fileoperations.h"
class DirectoryModel : public QObject {
Q_OBJECT
public:
explicit DirectoryModel(QObject *parent = nullptr);
~DirectoryModel();
Scaler *scaler;
void load(QString filePath, bool asyncHint);
void preload(QString filePath);
int fileCount() const;
int dirCount() const;
int indexOfFile(QString filePath) const;
int indexOfDir(QString filePath) const;
QString fileNameAt(int index) const;
bool containsFile(QString filePath) const;
bool isEmpty() const;
QString nextOf(QString filePath) const;
QString prevOf(QString filePath) const;
QString firstFile() const;
QString lastFile() const;
QDateTime lastModified(QString filePath) const;
bool forceInsert(QString filePath);
void copyFileTo(const QString &srcFile, const QString &destDirPath, bool force, FileOpResult &result);
void moveFileTo(const QString &srcFile, const QString &destDirPath, bool force, FileOpResult &result);
void renameEntry(const QString &oldFilePath, const QString &newName, bool force, FileOpResult &result);
void removeFile(const QString &filePath, bool trash, FileOpResult &result);
void removeDir(const QString &dirPath, bool trash, bool recursive, FileOpResult &result);
bool setDirectory(QString);
void unload(int index);
bool loaderBusy() const;
std::shared_ptr getImageAt(int index);
std::shared_ptr getImage(QString filePath);
void updateImage(QString filePath, std::shared_ptr img);
void setSortingMode(SortingMode mode);
SortingMode sortingMode() const;
QString directoryPath() const;
void unload(QString filePath);
bool isLoaded(int index) const;
bool isLoaded(QString filePath) const;
void reload(QString filePath);
QString filePathAt(int index) const;
void unloadExcept(QString filePath, bool keepNearby);
const FSEntry &fileEntryAt(int index) const;
int totalCount() const;
QString dirNameAt(int index) const;
QString dirPathAt(int index) const;
bool autoRefresh();
bool saveFile(const QString &filePath);
bool saveFile(const QString &filePath, const QString &destPath);
bool containsDir(QString dirPath) const;
FileListSource source();
signals:
void fileRemoved(QString filePath, int index);
void fileRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo);
void fileAdded(QString filePath);
void fileModified(QString filePath);
void dirRemoved(QString dirPath, int index);
void dirRenamed(QString dirPath, int indexFrom, QString toPath, int indexTo);
void dirAdded(QString dirPath);
void loaded(QString filePath);
void loadFailed(const QString &path);
void sortingChanged(SortingMode);
void indexChanged(int oldIndex, int index);
void imageReady(std::shared_ptr img, const QString&);
void imageUpdated(QString filePath);
private:
DirectoryManager dirManager;
Loader loader;
Cache cache;
FileListSource fileListSource;
private slots:
void onImageReady(std::shared_ptr img, const QString &path);
void onSortingChanged();
void onFileAdded(QString filePath);
void onFileRemoved(QString filePath, int index);
void onFileRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo);
void onFileModified(QString filePath);
};
qimgv-master/qimgv/components/directorypresenter.cpp 0000664 0000000 0000000 00000024740 14761273276 0023470 0 ustar 00root root 0000000 0000000 #include "directorypresenter.h"
DirectoryPresenter::DirectoryPresenter(QObject *parent) : QObject(parent), mShowDirs(false) {
connect(&thumbnailer, &Thumbnailer::thumbnailReady, this, &DirectoryPresenter::onThumbnailReady);
}
void DirectoryPresenter::unsetModel() {
disconnect(model.get(), &DirectoryModel::fileRemoved, this, &DirectoryPresenter::onFileRemoved);
disconnect(model.get(), &DirectoryModel::fileAdded, this, &DirectoryPresenter::onFileAdded);
disconnect(model.get(), &DirectoryModel::fileRenamed, this, &DirectoryPresenter::onFileRenamed);
disconnect(model.get(), &DirectoryModel::fileModified, this, &DirectoryPresenter::onFileModified);
disconnect(model.get(), &DirectoryModel::dirRemoved, this, &DirectoryPresenter::onDirRemoved);
disconnect(model.get(), &DirectoryModel::dirAdded, this, &DirectoryPresenter::onDirAdded);
disconnect(model.get(), &DirectoryModel::dirRenamed, this, &DirectoryPresenter::onDirRenamed);
model = nullptr;
// also empty view?
}
void DirectoryPresenter::setView(std::shared_ptr _view) {
if(view)
return;
view = _view;
if(model)
view->populate(mShowDirs ? model->totalCount() : model->fileCount());
connect(dynamic_cast(view.get()), SIGNAL(itemActivated(int)),
this, SLOT(onItemActivated(int)));
connect(dynamic_cast(view.get()), SIGNAL(thumbnailsRequested(QList, int, bool, bool)),
this, SLOT(generateThumbnails(QList, int, bool, bool)));
connect(dynamic_cast(view.get()), SIGNAL(draggedOut()),
this, SLOT(onDraggedOut()));
connect(dynamic_cast(view.get()), SIGNAL(draggedOver(int)),
this, SLOT(onDraggedOver(int)));
connect(dynamic_cast(view.get()), SIGNAL(droppedInto(const QMimeData*,QObject*,int)),
this, SLOT(onDroppedInto(const QMimeData*,QObject*,int)));
}
void DirectoryPresenter::setModel(std::shared_ptr newModel) {
if(model)
unsetModel();
if(!newModel)
return;
model = newModel;
populateView();
// filesystem changes
connect(model.get(), &DirectoryModel::fileRemoved, this, &DirectoryPresenter::onFileRemoved);
connect(model.get(), &DirectoryModel::fileAdded, this, &DirectoryPresenter::onFileAdded);
connect(model.get(), &DirectoryModel::fileRenamed, this, &DirectoryPresenter::onFileRenamed);
connect(model.get(), &DirectoryModel::fileModified, this, &DirectoryPresenter::onFileModified);
connect(model.get(), &DirectoryModel::dirRemoved, this, &DirectoryPresenter::onDirRemoved);
connect(model.get(), &DirectoryModel::dirAdded, this, &DirectoryPresenter::onDirAdded);
connect(model.get(), &DirectoryModel::dirRenamed, this, &DirectoryPresenter::onDirRenamed);
}
void DirectoryPresenter::reloadModel() {
populateView();
}
void DirectoryPresenter::populateView() {
if(!model || !view)
return;
view->populate(mShowDirs ? model->totalCount() : model->fileCount());
selectAndFocus(0);
}
void DirectoryPresenter::disconnectView() {
// todo
}
//------------------------------------------------------------------------------
void DirectoryPresenter::onFileRemoved(QString filePath, int index) {
Q_UNUSED(filePath)
if(!view)
return;
view->removeItem(mShowDirs ? index + model->dirCount() : index);
}
void DirectoryPresenter::onFileRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo) {
Q_UNUSED(fromPath)
Q_UNUSED(toPath)
if(!view)
return;
if(mShowDirs) {
indexFrom += model->dirCount();
indexTo += model->dirCount();
}
auto oldSelection = view->selection();
view->removeItem(indexFrom);
view->insertItem(indexTo);
// re-select if needed
if(oldSelection.contains(indexFrom)) {
if(oldSelection.count() == 1) {
view->select(indexTo);
view->focusOn(indexTo);
} else if(oldSelection.count() > 1) {
view->select(view->selection() << indexTo);
}
}
}
void DirectoryPresenter::onFileAdded(QString filePath) {
if(!view)
return;
int index = model->indexOfFile(filePath);
view->insertItem(mShowDirs ? model->dirCount() + index : index);
}
void DirectoryPresenter::onFileModified(QString filePath) {
if(!view)
return;
int index = model->indexOfFile(filePath);
view->reloadItem(mShowDirs ? model->dirCount() + index : index);
}
void DirectoryPresenter::onDirRemoved(QString dirPath, int index) {
Q_UNUSED(dirPath)
if(!view || !mShowDirs)
return;
view->removeItem(index);
}
void DirectoryPresenter::onDirRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo) {
Q_UNUSED(fromPath)
Q_UNUSED(toPath)
if(!view || !mShowDirs)
return;
auto oldSelection = view->selection();
view->removeItem(indexFrom);
view->insertItem(indexTo);
// re-select if needed
if(oldSelection.contains(indexFrom)) {
if(oldSelection.count() == 1) {
view->select(indexTo);
view->focusOn(indexTo);
} else if(oldSelection.count() > 1) {
view->select(view->selection() << indexTo);
}
}
}
void DirectoryPresenter::onDirAdded(QString dirPath) {
if(!view || !mShowDirs)
return;
int index = model->indexOfDir(dirPath);
view->insertItem(index);
}
bool DirectoryPresenter::showDirs() {
return mShowDirs;
}
void DirectoryPresenter::setShowDirs(bool mode) {
if(mode == mShowDirs)
return;
mShowDirs = mode;
populateView();
}
QList DirectoryPresenter::selectedPaths() const {
QList paths;
if(!view)
return paths;
if(mShowDirs) {
for(auto i : view->selection()) {
if(i < model->dirCount())
paths << model->dirPathAt(i);
else
paths << model->filePathAt(i - model->dirCount());
}
} else {
for(auto i : view->selection()) {
paths << model->filePathAt(i);
}
}
return paths;
}
void DirectoryPresenter::generateThumbnails(QList indexes, int size, bool crop, bool force) {
if(!view || !model)
return;
thumbnailer.clearTasks();
if(!mShowDirs) {
for(int i : indexes)
thumbnailer.getThumbnailAsync(model->filePathAt(i), size, crop, force);
return;
}
for(int i : indexes) {
if(i < model->dirCount()) {
// tmp ------------------------------------------------------------
// gen thumb for a directory
// TODO: optimize & move dir icon loading to shared res; then overlay
// the mini-thumbs on top (similar to dolphin)
QSvgRenderer svgRenderer;
svgRenderer.load(QString(":/res/icons/common/other/folder32-scalable.svg"));
int factor = (size * 0.90f) / svgRenderer.defaultSize().width();
QPixmap *pixmap = new QPixmap(svgRenderer.defaultSize() * factor);
pixmap->fill(Qt::transparent);
QPainter pixPainter(pixmap);
svgRenderer.render(&pixPainter);
pixPainter.end();
ImageLib::recolor(*pixmap, settings->colorScheme().icons);
std::shared_ptr thumb(new Thumbnail(model->dirNameAt(i),
"Folder",
size,
std::shared_ptr(pixmap)));
// ^----------------------------------------------------------------
view->setThumbnail(i, thumb);
} else {
QString path = model->filePathAt(i - model->dirCount());
thumbnailer.getThumbnailAsync(path, size, crop, force);
}
}
}
void DirectoryPresenter::onThumbnailReady(std::shared_ptr thumb, QString filePath) {
if(!view || !model)
return;
int index = model->indexOfFile(filePath);
if(index == -1)
return;
view->setThumbnail(mShowDirs ? model->dirCount() + index : index, thumb);
}
void DirectoryPresenter::onItemActivated(int absoluteIndex) {
if(!model)
return;
if(!mShowDirs) {
emit fileActivated(model->filePathAt(absoluteIndex));
return;
}
if(absoluteIndex < model->dirCount())
emit dirActivated(model->dirPathAt(absoluteIndex));
else
emit fileActivated(model->filePathAt(absoluteIndex - model->dirCount()));
}
void DirectoryPresenter::onDraggedOut() {
emit draggedOut(selectedPaths());
}
void DirectoryPresenter::onDraggedOver(int index) {
if(!model || view->selection().contains(index))
return;
if(showDirs() && index < model->dirCount())
view->setDragHover(index);
}
void DirectoryPresenter::onDroppedInto(const QMimeData *data, QObject *source, int targetIndex) {
if(!data->hasUrls() || model->source() != SOURCE_DIRECTORY)
return;
// ignore drops into selected / current folder when we are the source of dropEvent
if(source && (view->selection().contains(targetIndex) || targetIndex == -1) )
return;
// ignore drops into a file
// todo: drop into a current dir when target is a file
if(showDirs() && targetIndex >= model->dirCount())
return;
// convert urls to qstrings
QStringList pathList;
QList urlList = data->urls();
for(int i = 0; i < urlList.size(); ++i)
pathList.append(urlList.at(i).toLocalFile());
// get target dir path
QString destDir;
if(showDirs() && targetIndex < model->dirCount())
destDir = model->dirPathAt(targetIndex);
if(destDir.isEmpty()) // fallback to the current dir
destDir = model->directoryPath();
pathList.removeAll(destDir); // remove target dir from source list
// pass to core
emit droppedInto(pathList, destDir);
}
void DirectoryPresenter::selectAndFocus(QString path) {
if(!model || !view || path.isEmpty())
return;
if(model->containsDir(path) && showDirs()) {
int dirIndex = model->indexOfDir(path);
view->select(dirIndex);
view->focusOn(dirIndex);
} else if(model->containsFile(path)) {
int fileIndex = showDirs() ? model->indexOfFile(path) + model->dirCount() : model->indexOfFile(path);
view->select(fileIndex);
view->focusOn(fileIndex);
}
}
void DirectoryPresenter::selectAndFocus(int absoluteIndex) {
if(!model || !view)
return;
view->select(absoluteIndex);
view->focusOn(absoluteIndex);
}
qimgv-master/qimgv/components/directorypresenter.h 0000664 0000000 0000000 00000003476 14761273276 0023140 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include "gui/idirectoryview.h"
#include "components/thumbnailer/thumbnailer.h"
#include "directorymodel.h"
#include "sharedresources.h"
#include
//tmp
#include
class DirectoryPresenter : public QObject {
Q_OBJECT
public:
explicit DirectoryPresenter(QObject *parent = nullptr);
void setView(std::shared_ptr);
void setModel(std::shared_ptr newModel);
void unsetModel();
void selectAndFocus(int index);
void selectAndFocus(QString path);
void onFileRemoved(QString filePath, int index);
void onFileRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo);
void onFileAdded(QString filePath);
void onFileModified(QString filePath);
void onDirRemoved(QString dirPath, int index);
void onDirRenamed(QString fromPath, int indexFrom, QString toPath, int indexTo);
void onDirAdded(QString dirPath);
bool showDirs();
void setShowDirs(bool mode);
QList selectedPaths() const;
signals:
void dirActivated(QString dirPath);
void fileActivated(QString filePath);
void draggedOut(QList);
void droppedInto(QList, QString);
public slots:
void disconnectView();
void reloadModel();
private slots:
void generateThumbnails(QList, int, bool, bool);
void onThumbnailReady(std::shared_ptr thumb, QString filePath);
void populateView();
void onItemActivated(int absoluteIndex);
void onDraggedOut();
void onDraggedOver(int index);
void onDroppedInto(const QMimeData *data, QObject *source, int targetIndex);
private:
std::shared_ptr view = nullptr;
std::shared_ptr model = nullptr;
Thumbnailer thumbnailer;
bool mShowDirs;
};
qimgv-master/qimgv/components/loader/ 0000775 0000000 0000000 00000000000 14761273276 0020267 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/loader/loader.cpp 0000664 0000000 0000000 00000002647 14761273276 0022252 0 ustar 00root root 0000000 0000000 #include "loader.h"
Loader::Loader() {
pool = new QThreadPool(this);
pool->setMaxThreadCount(2);
}
void Loader::clearTasks() {
clearPool();
pool->waitForDone();
}
bool Loader::isBusy() const {
return (tasks.count() != 0);
}
bool Loader::isLoading(QString path) {
return tasks.contains(path);
}
std::shared_ptr Loader::load(QString path) {
return ImageFactory::createImage(path);
}
// clears all buffered tasks before loading
void Loader::loadAsyncPriority(QString path) {
clearPool();
doLoadAsync(path, 1);
}
void Loader::loadAsync(QString path) {
doLoadAsync(path, 0);
}
void Loader::doLoadAsync(QString path, int priority) {
if(tasks.contains(path)) {
return;
}
auto runnable = new LoaderRunnable(path);
runnable->setAutoDelete(false);
tasks.insert(path, runnable);
connect(runnable, &LoaderRunnable::finished, this, &Loader::onLoadFinished, Qt::UniqueConnection);
pool->start(runnable, priority);
}
void Loader::onLoadFinished(std::shared_ptr image, const QString &path) {
auto task = tasks.take(path);
delete task;
if(!image)
emit loadFailed(path);
else
emit loadFinished(image, path);
}
void Loader::clearPool() {
QHashIterator i(tasks);
while (i.hasNext()) {
i.next();
if(pool->tryTake(i.value())) {
delete tasks.take(i.key());
}
}
}
qimgv-master/qimgv/components/loader/loader.h 0000664 0000000 0000000 00000001354 14761273276 0021711 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include "components/cache/thumbnailcache.h"
#include "loaderrunnable.h"
class Loader : public QObject {
Q_OBJECT
public:
explicit Loader();
std::shared_ptr load(QString path);
void loadAsyncPriority(QString path);
void loadAsync(QString path);
void clearTasks();
bool isBusy() const;
bool isLoading(QString path);
private:
QHash tasks;
QThreadPool *pool;
void clearPool();
void doLoadAsync(QString path, int priority);
signals:
void loadFinished(std::shared_ptr, const QString &path);
void loadFailed(const QString &path);
private slots:
void onLoadFinished(std::shared_ptr, const QString&);
};
qimgv-master/qimgv/components/loader/loaderrunnable.cpp 0000664 0000000 0000000 00000000471 14761273276 0023772 0 ustar 00root root 0000000 0000000 #include "loaderrunnable.h"
#include
LoaderRunnable::LoaderRunnable(QString _path) : path(_path) {
}
void LoaderRunnable::run() {
//QElapsedTimer t;
//t.start();
auto image = ImageFactory::createImage(path);
//qDebug() << "L: " << t.elapsed();
emit finished(image, path);
}
qimgv-master/qimgv/components/loader/loaderrunnable.h 0000664 0000000 0000000 00000000515 14761273276 0023436 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include "utils/imagefactory.h"
class LoaderRunnable: public QObject, public QRunnable
{
Q_OBJECT
public:
LoaderRunnable(QString _path);
void run();
private:
QString path;
signals:
void finished(std::shared_ptr, QString);
void failed(QString);
};
qimgv-master/qimgv/components/scaler/ 0000775 0000000 0000000 00000000000 14761273276 0020272 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/scaler/scaler.cpp 0000664 0000000 0000000 00000010734 14761273276 0022254 0 ustar 00root root 0000000 0000000 #include "scaler.h"
/* What this should do in theory:
* 1 request comes
* 2 we run it
* 3a if during scaling no new requests came, we return the result and forget about it. end.
* 3b if some requests did come, by the end of current task we dispose of its result,
* start the last task that came and ignore the middle ones.
*/
Scaler::Scaler(Cache *_cache, QObject *parent)
: QObject(parent),
buffered(false),
running(false),
currentRequestTimestamp(0),
cache(_cache)
{
sem = new QSemaphore(1);
pool = new QThreadPool(this);
pool->setMaxThreadCount(1);
runnable = new ScalerRunnable();
runnable->setAutoDelete(false);
connect(this, &Scaler::startBufferedRequest, this, &Scaler::slotStartBufferedRequest, Qt::DirectConnection);
connect(runnable, &ScalerRunnable::started, this, &Scaler::onTaskStart, Qt::DirectConnection);
connect(runnable, &ScalerRunnable::finished, this, &Scaler::onTaskFinish, Qt::DirectConnection);
connect(this, &Scaler::acceptScalingResult, this, &Scaler::slotForwardScaledResult, Qt::QueuedConnection);
}
void Scaler::requestScaled(ScalerRequest req) {
sem->acquire(1);
if(!running) {
//////////////////////////////////
if(!buffered) {
bufferedRequest = req;
buffered = true;
//qDebug() << "1 requestScaled() - locking.. " << req.image->name();
cache->reserve(req.image->fileName());
//qDebug() << "1 requestScaled() - LOCKED! " << req.image->name();
startRequest(req);
} else if(bufferedRequest.image != req.image) {
//qDebug() << "2 requestScaled() - locking... " << req.image->name();
cache->reserve(req.image->fileName());
//qDebug() << "2 requestScaled() - LOCKED! " << req.image->name();
auto tmp = bufferedRequest;
bufferedRequest = req;
buffered = true;
if(startedRequest.image != tmp.image) {
cache->release(tmp.image->fileName());
//qDebug() << "2 requestScaled() - RELEASED! " << tmp.image->name();
}
} else {
bufferedRequest = req;
buffered = true;
}
//////////////////////////////
} else {
if(!buffered) {
if(req.image != startedRequest.image)
cache->reserve(req.image->fileName());
bufferedRequest = req;
buffered = true;
} else {
if(req.image == bufferedRequest.image) {
bufferedRequest = req;
buffered = true;
} else {
if(bufferedRequest.image != startedRequest.image) {
//qDebug() << "4 RELEASING " << bufferedRequest.image->name();
cache->release(bufferedRequest.image->fileName());
}
if(req.image != startedRequest.image)
cache->reserve(req.image->fileName());
bufferedRequest = req;
buffered = true;
}
}
}
sem->release(1);
}
void Scaler::onTaskStart(ScalerRequest req) {
sem->acquire(1);
running = true;
// clear buffered flag if there were no requests after us
if(buffered && bufferedRequest == req) {
buffered = false;
}
startedRequest = req;
//qDebug() << "onTaskStart(): " << req.image->name();
sem->release(1);
}
void Scaler::onTaskFinish(QImage *scaled, ScalerRequest req) {
sem->acquire(1);
running = false;
if(buffered && bufferedRequest.image == req.image) {
} else {
//qDebug() << "onTaskFinish() - 2 releasing.. " << req.image->name();
QString name = req.image->fileName();
cache->release(req.image->fileName());
//qDebug() << "onTaskFinish() - 2 RELEASED! " << name;
}
if(buffered) {
//qDebug() << "onTaskFinish - startingBuffered: " << bufferedRequest.string;
delete scaled;
//startRequest(bufferedRequest);
emit startBufferedRequest();
sem->release(1);
} else {
sem->release(1);
emit acceptScalingResult(scaled, req);
}
}
void Scaler::slotStartBufferedRequest() {
startRequest(bufferedRequest);
}
void Scaler::slotForwardScaledResult(QImage *image, ScalerRequest req) {
QPixmap *pixmap = new QPixmap();
*pixmap = QPixmap::fromImage(*image);
delete image;
emit scalingFinished(pixmap, req);
}
void Scaler::startRequest(ScalerRequest req) {
runnable->setRequest(req);
pool->start(runnable);
}
qimgv-master/qimgv/components/scaler/scaler.h 0000664 0000000 0000000 00000001772 14761273276 0021723 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include "components/cache/cache.h"
#include "scalerrequest.h"
#include "scalerrunnable.h"
class Scaler : public QObject {
Q_OBJECT
public:
explicit Scaler(Cache *_cache, QObject *parent = nullptr);
signals:
void scalingFinished(QPixmap* result, ScalerRequest request);
void acceptScalingResult(QImage *image, ScalerRequest req);
void startBufferedRequest();
public slots:
void requestScaled(ScalerRequest req);
private slots:
void onTaskStart(ScalerRequest req);
void onTaskFinish(QImage* scaled, ScalerRequest req);
void slotStartBufferedRequest();
void slotForwardScaledResult(QImage *image, ScalerRequest req);
private:
QThreadPool *pool;
ScalerRunnable *runnable;
bool buffered, running;
clock_t currentRequestTimestamp;
ScalerRequest bufferedRequest, startedRequest;
Cache *cache;
void startRequest(ScalerRequest req);
QSemaphore *sem;
};
qimgv-master/qimgv/components/scaler/scalerrequest.h 0000664 0000000 0000000 00000001367 14761273276 0023334 0 ustar 00root root 0000000 0000000 #ifndef SCALERREQUEST_H
#define SCALERREQUEST_H
#include
#include "sourcecontainers/image.h"
#include "settings.h" // move enums somewhere else?
class ScalerRequest {
public:
ScalerRequest() : image(nullptr), size(QSize(0,0)), filter(QI_FILTER_BILINEAR) { }
ScalerRequest(std::shared_ptr _image, QSize _size, QString _path, ScalingFilter _filter) : image(_image), size(_size), path(_path), filter(_filter) {}
std::shared_ptr image;
QSize size;
QString path;
ScalingFilter filter;
bool operator==(const ScalerRequest &another) const {
if(another.image == image && another.size == size && another.filter == filter)
return true;
return false;
}
};
#endif // SCALERREQUEST_H
qimgv-master/qimgv/components/scaler/scalerrunnable.cpp 0000664 0000000 0000000 00000001227 14761273276 0024000 0 ustar 00root root 0000000 0000000 #include "scalerrunnable.h"
#include
ScalerRunnable::ScalerRunnable() {
}
void ScalerRunnable::setRequest(ScalerRequest r) {
req = r;
}
void ScalerRunnable::run() {
emit started(req);
//QElapsedTimer t;
//t.start();
QImage *scaled = nullptr;
if(req.filter == 0 || (req.size.width() > req.image->width() && !settings->smoothUpscaling())) {
scaled = ImageLib::scaled(req.image->getImage(), req.size, QI_FILTER_NEAREST);
} else {
scaled = ImageLib::scaled(req.image->getImage(), req.size, req.filter);
}
//qDebug() << ">> " << req.size << ": " << t.elapsed();
emit finished(scaled, req);
}
qimgv-master/qimgv/components/scaler/scalerrunnable.h 0000664 0000000 0000000 00000001077 14761273276 0023450 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include
#include
#include "components/cache/cache.h"
#include "scalerrequest.h"
#include "utils/imagelib.h"
#include "settings.h"
class ScalerRunnable : public QObject, public QRunnable
{
Q_OBJECT
public:
explicit ScalerRunnable();
void setRequest(ScalerRequest r);
void run();
signals:
void started(ScalerRequest);
void finished(QImage*, ScalerRequest);
private:
ScalerRequest req;
const float CMPL_FALLBACK_THRESHOLD = 70.0; // equivalent of ~ 5000x3500 @ 32bpp
};
qimgv-master/qimgv/components/scriptmanager/ 0000775 0000000 0000000 00000000000 14761273276 0021660 5 ustar 00root root 0000000 0000000 qimgv-master/qimgv/components/scriptmanager/scriptmanager.cpp 0000664 0000000 0000000 00000011101 14761273276 0025215 0 ustar 00root root 0000000 0000000 #include "scriptmanager.h"
ScriptManager *scriptManager = nullptr;
ScriptManager::ScriptManager(QObject *parent)
: QObject(parent)
{
}
ScriptManager::~ScriptManager() {
scriptManager->saveScripts();
delete scriptManager;
}
ScriptManager *ScriptManager::getInstance() {
if(!scriptManager) {
scriptManager = new ScriptManager();
scriptManager->readScripts();
}
return scriptManager;
}
void ScriptManager::runScript(const QString &scriptName, std::shared_ptr img) {
if(scripts.contains(scriptName)) {
Script script = scripts.value(scriptName);
if(script.command.isEmpty())
return;
QProcess exec(this);
auto arguments = splitCommandLine(script.command);
processArguments(arguments, img);
QString program = arguments.takeAt(0);
if(script.blocking) {
exec.start(program, arguments);
if(!exec.waitForStarted()) {
qDebug() << "Unable not run application/script." << program << " Make sure it is an executable.";
}
exec.waitForFinished(10000);
} else {
if(!exec.startDetached(program, arguments)) {
QFileInfo fi(program);
QString errorString;
if(fi.isFile() && !fi.isExecutable())
errorString = "Error: " + program + " is not an executable.";
else
errorString = "Error: unable run application/script. See README for working examples.";
emit error(errorString);
qWarning() << errorString;
}
}
} else {
qDebug() << "[ScriptManager] File " << scriptName << " does not exist.";
}
}
QString ScriptManager::runCommand(QString cmd) {
QProcess exec;
QStringList cmdSplit = ScriptManager::splitCommandLine(cmd);
exec.start(cmdSplit.takeAt(0), cmdSplit);
exec.waitForFinished(2000);
return exec.readAllStandardOutput();
}
void ScriptManager::runCommandDetached(QString cmd) {
QStringList cmdSplit = ScriptManager::splitCommandLine(cmd);
QProcess::startDetached(cmdSplit.takeAt(0), cmdSplit);
}
// TODO: what if filename contains one of the tags?
void ScriptManager::processArguments(QStringList &cmd, std::shared_ptr img) {
for (auto& i : cmd) {
if(i.contains("%file%"))
i.replace("%file%", img.get()->filePath());
#ifdef __WIN32
// force "\" as a directory separator
i.replace("/", "\\");
i.replace("\\\\", "\\");
#endif
}
}
// thanks stackoverflow
QStringList ScriptManager::splitCommandLine(const QString &cmdLine) {
QStringList list;
QString arg;
bool escape = false;
enum { Idle, Arg, QuotedArg } state = Idle;
foreach (QChar const c, cmdLine) {
//if(!escape && c == '\\') {
// escape = true;
// continue;
//}
switch (state) {
case Idle:
if(!escape && c == '"')
state = QuotedArg;
else if (escape || !c.isSpace()) {
arg += c;
state = Arg;
}
break;
case Arg:
if(!escape && c == '"')
state = QuotedArg;
else if(escape || !c.isSpace())
arg += c;
else {
list << arg;
arg.clear();
state = Idle;
}
break;
case QuotedArg:
if(!escape && c == '"')
state = arg.isEmpty() ? Idle : Arg;
else
arg += c;
break;
}
escape = false;
}
if(!arg.isEmpty())
list << arg;
return list;
}
bool ScriptManager::scriptExists(QString scriptName) {
return scripts.contains(scriptName);
}
void ScriptManager::readScripts() {
settings->readScripts(scripts);
}
void ScriptManager::saveScripts() {
settings->saveScripts(scripts);
}
// replaces if it already exists
void ScriptManager::addScript(QString scriptName, Script script) {
if(scripts.contains(scriptName)) {
qDebug() << "[ScriptManager] Replacing script" << scriptName;
scripts.remove(scriptName);
}
scripts.insert(scriptName, script);
}
void ScriptManager::removeScript(QString scriptName) {
scripts.remove(scriptName);
}
const QMap &ScriptManager::allScripts() {
return scriptManager->scripts;
}
QList ScriptManager::scriptNames() {
return scriptManager->scripts.keys();
}
Script ScriptManager::getScript(QString scriptName) {
return scripts.value(scriptName);
}
qimgv-master/qimgv/components/scriptmanager/scriptmanager.h 0000664 0000000 0000000 00000002256 14761273276 0024675 0 ustar 00root root 0000000 0000000 #pragma once
#include
#include
#include