Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
KDE:Unstable:Frameworks
libkexiv2
_service:obs_scm:libkexiv2-VERSIONgit.20240423T...
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:libkexiv2-VERSIONgit.20240423T130333~354ff39.obscpio of Package libkexiv2
07070100000000000081A40000000000000000000000016627958500000087000000000000000000000000000000000000003800000000libkexiv2-VERSIONgit.20240423T130333~354ff39/.gitignore*.kate-swp CMakeLists.txt.user* /.clang-format /compile_commands.json .clangd .idea /cmake-build* .cache build* tests/databases/*/*.db 07070100000001000081A40000000000000000000000016627958500000165000000000000000000000000000000000000003C00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/.gitlab-ci.yml# SPDX-FileCopyrightText: None # SPDX-License-Identifier: CC0-1.0 include: - project: sysadmin/ci-utilities file: - /gitlab-templates/linux.yml - /gitlab-templates/freebsd.yml - /gitlab-templates/windows.yml - /gitlab-templates/linux-qt6.yml - /gitlab-templates/freebsd-qt6.yml - /gitlab-templates/windows-qt6.yml 07070100000002000081A4000000000000000000000001662795850000017E000000000000000000000000000000000000003900000000libkexiv2-VERSIONgit.20240423T130333~354ff39/.kde-ci.yml# SPDX-FileCopyrightText: None # SPDX-License-Identifier: CC0-1.0 Dependencies: - 'on': ['Linux/Qt5', 'FreeBSD/Qt5', 'Windows/Qt5'] 'require': 'frameworks/extra-cmake-modules': '@stable' - 'on': ['Linux/Qt6', 'FreeBSD/Qt6', 'Windows/Qt6'] 'require': 'frameworks/extra-cmake-modules': '@latest-kf6' Options: require-passing-tests-on: ['Linux', 'FreeBSD', 'Windows'] 07070100000003000081A40000000000000000000000016627958500000001000000000000000000000000000000000000003400000000libkexiv2-VERSIONgit.20240423T130333~354ff39/.krazy 07070100000004000081A40000000000000000000000016627958500000139000000000000000000000000000000000000003500000000libkexiv2-VERSIONgit.20240423T130333~354ff39/AUTHORSAUTHORS AND MAINTAINERS: Caulier Gilles <caulier dot gilles at gmail dot com> Marcel Wiesweg <marcel dot wiesweg at gmx dot de> CONTRIBUTORS: Angelo Naselli <anaselli at linux dot it> Gerhard Kulzer <gerhard at kulzer dot net> Achim Bohnet <ach at mpe dot mpg dot de> Guillaume Castagnino <guilc at fr dot st> 07070100000005000081A40000000000000000000000016627958500001173000000000000000000000000000000000000003C00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/CMakeLists.txt# # SPDX-FileCopyrightText: 2010-2015 Gilles Caulier <caulier dot gilles at gmail dot com> # # SPDX-License-Identifier: BSD-3-Clause # cmake_minimum_required(VERSION 3.16) set(ECM_MIN_VERSION "5.91.0") set(QT_MIN_VERSION "5.15.0") set(EXIV2_MIN_VERSION "0.25") project(libkexiv2 VERSION "5.1.0") set(CMAKE_CXX_STANDARD 14) # exiv is not compatible with C++ > 14 yet set(CMAKE_CXX_STANDARD_REQUIRED ON) message(STATUS "----------------------------------------------------------------------------------") message(STATUS "Starting CMake configuration for: ${PROJECT_NAME}") # ======================================================= # Information to update before to release this library. # Library version history: # API ABI # 0.1.0 => 0.1.0 # 0.1.1 => 0.2.0 # 0.1.2 => 1.0.1 # 0.1.3 => 1.0.1 # 0.1.4 => 2.0.2 # 0.1.5 => 2.1.1 # 0.1.6 => 3.0.0 # 0.1.7 => 4.0.1 # 0.1.8 => 5.0.0 # 0.2.0 => 6.0.0 (released with KDE 4.1.0) # 0.3.0 => 7.0.0 (released with KDE 4.1.2) # 0.4.0 => 7.1.0 # 0.5.0 => 7.2.0 (Released with KDE 4.2.0) # 0.6.0 => 7.3.0 (Released with KDE 4.3.0) # 1.0.0 => 8.0.0 (Released with KDE 4.4.0) # 1.1.0 => 8.1.0 (Released with KDE 4.5.0) # 1.2.0 => 9.0.0 (Released with KDE 4.6.0) - Including XMP sidecar support # 2.0.0 => 10.0.0 (Released with KDE 4.7.0) # 2.1.0 => 10.0.1 (Released with KDE 4.7.1) - Add AltLangStrEdit visible lines API # 2.1.1 => 10.0.2 (Released with KDE 4.7.4) - Add AltLangStrEdit::setCurrentLanguageCode() # 2.2.0 => 11.0.0 (Released with KDE 4.8.1) - Remove deprecated methods # 2.3.0 => 11.1.0 (Released with KDE 4.8.2) - Add new static methods about XMP sidecar file management. # 2.3.1 => 11.2.0 - Add new method to set specific XMP tag string # 2.4.0 => 11.3.0 - Add new method to access on text edit widget from AltLangStrEdit # 5.0.0 => 15.0.0 (Released with KDE 5.x) # 5.1.0 => 15.0.0 (Released with KDE Gear) - Add QTransform-varianst methods RotationMatrix # Library ABI version used by linker. # For details : https://www.gnu.org/software/libtool/manual/libtool.html#Updating-version-info set(KEXIV2_LIB_SO_CUR_VERSION "15") set(KEXIV2_LIB_SO_REV_VERSION "0") set(KEXIV2_LIB_SO_AGE_VERSION "0") # TODO Qt6 or next ABI break: the very SO version is usually a single number, not a triple. # The library non-SO version as decribed in the link above is a separate thing # (cmp. VVERSION & SOVERSION args of set_target_properties(KF5KExiv2) # See below (where QT_MAJOR_VERSION is available) for resetting LIBKEXIV2_SO_VERSION to 0 with Qt6 builds set(LIBKEXIV2_SO_VERSION "${KEXIV2_LIB_SO_CUR_VERSION}.${KEXIV2_LIB_SO_REV_VERSION}.${KEXIV2_LIB_SO_AGE_VERSION}") ############## ECM setup ###################### find_package(ECM ${ECM_MIN_VERSION} CONFIG REQUIRED) set(CMAKE_MODULE_PATH ${libkexiv2_SOURCE_DIR}/cmake/modules ${ECM_MODULE_PATH}) include(KDEInstallDirs) include(KDECMakeSettings) include(KDECompilerSettings NO_POLICY_SCOPE) include(ECMGenerateHeaders) include(ECMSetupVersion) include(ECMMarkNonGuiExecutable) include(ECMQtDeclareLoggingCategory) include(ECMGenerateExportHeader) include(ECMDeprecationSettings) include(CMakePackageConfigHelpers) include(FeatureSummary) # reset to 0 once all deprecated API has been removed on full switch to Qt6 if (QT_MAJOR_VERSION STREQUAL "6") set(EXCLUDE_DEPRECATED_BEFORE_AND_AT 5.1.0 CACHE STRING "Control the range of deprecated API excluded from the build [default=5.1.0].") else() set(EXCLUDE_DEPRECATED_BEFORE_AND_AT 0 CACHE STRING "Control the range of deprecated API excluded from the build [default=0].") endif() if (QT_MAJOR_VERSION STREQUAL "6") # starting with 0 for the new Qt6 series set(LIBKEXIV2_SO_VERSION "0") endif() ############## Find Packages ################### if (QT_MAJOR_VERSION STREQUAL "6") set(QT_MIN_VERSION "6.5.0") endif() find_package(Qt${QT_MAJOR_VERSION} ${QT_MIN_VERSION} REQUIRED NO_MODULE COMPONENTS Core Gui ) find_package(LibExiv2 ${EXIV2_MIN_VERSION} REQUIRED) ############## Targets ######################### if (QT_MAJOR_VERSION STREQUAL "6") ecm_set_disabled_deprecation_versions( QT 6.5 ) else() ecm_set_disabled_deprecation_versions( QT 5.14 # QTransform::toAffine ) endif() add_subdirectory(src) if (BUILD_TESTING) add_subdirectory(tests) endif() feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) 07070100000006000041ED0000000000000000000000026627958500000000000000000000000000000000000000000000003600000000libkexiv2-VERSIONgit.20240423T130333~354ff39/LICENSES07070100000007000081A400000000000000000000000166279585000005C8000000000000000000000000000000000000004700000000libkexiv2-VERSIONgit.20240423T130333~354ff39/LICENSES/BSD-3-Clause.txtCopyright (c) <year> <owner>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 07070100000008000081A4000000000000000000000001662795850000437D000000000000000000000000000000000000004B00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/LICENSES/GPL-2.0-or-later.txtGNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice 07070100000009000081A40000000000000000000000016627958500000551000000000000000000000000000000000000003400000000libkexiv2-VERSIONgit.20240423T130333~354ff39/READMEEXIV2 Library interface for KDE -- AUTHORS ------------------------------------------------------------ See AUTHORS file for details. -- ABOUT -------------------------------------------------------------- Libkexiv2 is a wrapper around Exiv2 library to manipulate pictures metadata as EXIF/IPTC and XMP. Metadata interface follow this paper: http://www.metadataworkinggroup.com/pdf/mwg_guidance.pdf The library documentation is available on header files. -- DEPENDENCIES ------------------------------------------------------- CMake >= 3.0.0 https://www.cmake.org ECM >= 1.1.0 https://commits.kde.org/extra-cmake-modules libqt >= 5.9.0 https://qt.io libexiv2 >= 0.24.0 https://www.exiv2.org -- INSTALL ------------------------------------------------------------ Usual CMake options: -DCMAKE_INSTALL_PREFIX : decide where the program will be install on your computer. -DCMAKE_BUILD_TYPE : decide which type of build you want. You can chose between "debug", "profile", "relwithdebinfo" and "release". The default is "relwithdebinfo" (-O2 -g). Note: To know KDE install path on your computer, use 'kf5-config --prefix' command line like this (with debug object enabled): "cmake . -DCMAKE_BUILD_TYPE=debug -DCMAKE_INSTALL_PREFIX=`kf5-config --prefix`" 0707010000000A000081A40000000000000000000000016627958500000046000000000000000000000000000000000000003200000000libkexiv2-VERSIONgit.20240423T130333~354ff39/TODO- Extract GPS info from XMP tags. - Exif/Iptc => Xmp synchronization. 0707010000000B000041ED0000000000000000000000036627958500000000000000000000000000000000000000000000003300000000libkexiv2-VERSIONgit.20240423T130333~354ff39/cmake0707010000000C000041ED0000000000000000000000026627958500000000000000000000000000000000000000000000003D00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/cmake/templates0707010000000D000081A400000000000000000000000166279585000000F4000000000000000000000000000000000000005300000000libkexiv2-VERSIONgit.20240423T130333~354ff39/cmake/templates/KExiv2Config.cmake.in@PACKAGE_INIT@ include(CMakeFindDependencyMacro) find_dependency(Qt@QT_MAJOR_VERSION@Core @QT_MIN_VERSION@) find_dependency(Qt@QT_MAJOR_VERSION@Gui @QT_MIN_VERSION@) include("${CMAKE_CURRENT_LIST_DIR}/@KEXIV2_CMAKECONFIG_NAME@Targets.cmake") 0707010000000E000081A4000000000000000000000001662795850000011B000000000000000000000000000000000000003B00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/metainfo.yamlfancyname: KExiv2 description: Wrapper around Exiv2 library to manipulate picture metadata as EXIF and XMP type: functional public_lib: true platforms: - name: Linux - name: FreeBSD - name: Windows release: true libraries: - cmake: "KF5::KExiv2" cmakename: KF5KExiv2 0707010000000F000041ED0000000000000000000000026627958500000000000000000000000000000000000000000000003100000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src07070100000010000081A40000000000000000000000016627958500001196000000000000000000000000000000000000004000000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/CMakeLists.txt# # SPDX-FileCopyrightText: 2010-2015 Gilles Caulier <caulier dot gilles at gmail dot com> # # SPDX-License-Identifier: BSD-3-Clause # if (QT_MAJOR_VERSION STREQUAL "5") set(KEXIV2_INSTALL_INCLUDEDIR "${KDE_INSTALL_INCLUDEDIR_KF}/KExiv2") set(KEXIV2_CMAKECONFIG_NAME "KF${QT_MAJOR_VERSION}KExiv2") set(LIBRARYFILE_NAME "KF5KExiv2") set(TARGET_EXPORT_NAME "KExiv2") set(NAMESPACE_NAME "KF5::") else() set(KEXIV2_INSTALL_INCLUDEDIR "${KDE_INSTALL_INCLUDEDIR}/KExiv2Qt6") set(KEXIV2_CMAKECONFIG_NAME "KExiv2Qt6") set(LIBRARYFILE_NAME "KExiv2Qt6") set(TARGET_EXPORT_NAME "KExiv2Qt6") set(NAMESPACE_NAME "") endif() ecm_setup_version(${libkexiv2_VERSION} VARIABLE_PREFIX KEXIV2 VERSION_HEADER "libkexiv2_version.h" PACKAGE_VERSION_FILE "${KEXIV2_CMAKECONFIG_NAME}ConfigVersion.cmake" SOVERSION ${LIBKEXIV2_SO_VERSION} ) kde_enable_exceptions() add_library(KExiv2 SHARED) set_target_properties(KExiv2 PROPERTIES OUTPUT_NAME KF${QT_MAJOR_VERSION}KExiv2 VERSION ${KEXIV2_VERSION} SOVERSION ${KEXIV2_SOVERSION} OUTPUT_NAME ${LIBRARYFILE_NAME} EXPORT_NAME ${TARGET_EXPORT_NAME} ) if( WIN32 ) target_compile_definitions(KExiv2 PRIVATE -DEXV_HAVE_DLL) endif() target_sources(KExiv2 PRIVATE kexiv2.cpp kexiv2_p.cpp kexiv2data.cpp kexiv2image.cpp kexiv2comments.cpp kexiv2exif.cpp kexiv2iptc.cpp kexiv2gps.cpp kexiv2xmp.cpp kexiv2previews.cpp rotationmatrix.cpp ) ecm_qt_declare_logging_category(KExiv2 HEADER libkexiv2_debug.h IDENTIFIER LIBKEXIV2_LOG CATEGORY_NAME "libKExiv2" DESCRIPTION "libKExiv2" EXPORT kexiv2 ) ecm_generate_headers(kexiv2_CamelCase_HEADERS HEADER_NAMES KExiv2Data KExiv2 KExiv2Previews RotationMatrix PREFIX KExiv2 REQUIRED_HEADERS kexiv2_HEADERS ) if (QT_MAJOR_VERSION STREQUAL "5") set(_generate_export_header_version_args) else() # For Qt6/KF6 world transitively include the version header if(ECM_VERSION VERSION_LESS "5.106") set(include_version_header_code "#include <libkexiv2_version.h>\n") set(_generate_export_header_version_args CUSTOM_CONTENT_FROM_VARIABLE include_version_header_code) else() set(_generate_export_header_version_args USE_VERSION_HEADER libkexiv2_version.h) endif() endif() ecm_generate_export_header(KExiv2 BASE_NAME kexiv2 EXPORT_FILE_NAME libkexiv2_export.h EXPORT_MACRO_NAME LIBKEXIV2_EXPORT VERSION ${libkexiv2_VERSION} DEPRECATED_BASE_VERSION 0 DEPRECATION_VERSIONS 5.1 EXCLUDE_DEPRECATED_BEFORE_AND_AT ${EXCLUDE_DEPRECATED_BEFORE_AND_AT} ${_generate_export_header_version_args} ) target_include_directories(KExiv2 INTERFACE "$<INSTALL_INTERFACE:${KEXIV2_INSTALL_INCLUDEDIR};${KEXIV2_INSTALL_INCLUDEDIR}/kexiv2>" ) target_link_libraries(KExiv2 PUBLIC Qt::Gui Qt::Core PRIVATE LibExiv2::LibExiv2 ) if( WIN32 ) target_link_libraries(KExiv2 ${EXPAT_LIBRARIES}) endif() install(TARGETS KExiv2 EXPORT KExiv2Targets ${KF_INSTALL_TARGETS_DEFAULT_ARGS} ) install(FILES ${kexiv2_CamelCase_HEADERS} DESTINATION ${KEXIV2_INSTALL_INCLUDEDIR}/KExiv2 COMPONENT Devel ) install(FILES ${kexiv2_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/libkexiv2_export.h DESTINATION ${KEXIV2_INSTALL_INCLUDEDIR}/kexiv2 COMPONENT Devel ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libkexiv2_version.h DESTINATION ${KEXIV2_INSTALL_INCLUDEDIR} COMPONENT Devel ) ecm_qt_install_logging_categories( EXPORT kexiv2 FILE libkexiv2.categories DESTINATION "${KDE_INSTALL_LOGGINGCATEGORIESDIR}" ) ############## CMake Config Files ############## set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/${KEXIV2_CMAKECONFIG_NAME}") configure_package_config_file( "${CMAKE_SOURCE_DIR}/cmake/templates/KExiv2Config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/${KEXIV2_CMAKECONFIG_NAME}Config.cmake" INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR} ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${KEXIV2_CMAKECONFIG_NAME}Config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/${KEXIV2_CMAKECONFIG_NAME}ConfigVersion.cmake" DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) install(EXPORT KExiv2Targets FILE ${KEXIV2_CMAKECONFIG_NAME}Targets.cmake NAMESPACE ${NAMESPACE_NAME} DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) 07070100000011000081A4000000000000000000000001662795850000A94D000000000000000000000000000000000000003A00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/Doxyfile# Doxyfile 1.3.5 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = libKExiv2 # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, # Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en # (Japanese with English messages), Korean, Norwegian, Polish, Portuguese, # Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is used # as the annotated text. Otherwise, the brief description is used as-is. If left # blank, the following values are used ("$name" is automatically replaced with the # name of the entity): "The $name class" "The $name widget" "The $name file" # "is" "provides" "specifies" "contains" "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited # members of a class in the documentation of that class as if those members were # ordinary class members. Constructors, destructors and assignment operators of # the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. It is allowed to use relative paths in the argument list. STRIP_FROM_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like the Qt-style comments (thus requiring an # explicit @brief command for a brief description. JAVADOC_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources # only. Doxygen will then generate output that is more tailored for Java. # For instance, namespaces will be presented as packages, qualified scopes # will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = NO # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = NO # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = ./ INPUT += ./Mainpage.dox # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp # *.h++ *.idl *.odl *.cs *.php *.php3 *.inc FILE_PATTERNS = *.cpp \ *.h # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories # that are symbolic links (a Unix filesystem feature) are excluded from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. EXCLUDE_PATTERNS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command <filter> <input-file>, where <filter> # is the value of the INPUT_FILTER tag, and <input-file> is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. INPUT_FILTER = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES (the default) # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES (the default) # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # If the GENERATE_TREEVIEW tag is set to YES, a side panel will be # generated containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, # Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are # probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. This is useful # if you want to understand what is going on. On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_PREDEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. PREDEFINED = _XMP_SUPPORT_ # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse the # parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::addtions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base or # super classes. Setting the tag to NO turns the diagrams off. Note that this # option is superseded by the HAVE_DOT option below. This is only a fallback. It is # recommended to install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = YES # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = YES # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will # generate a call dependency graph for every global function or class method. # Note that enabling this option will significantly increase the time of a run. # So in most cases it will be better to enable call graphs for selected # functions only using the \callgraph command. CALL_GRAPH = YES # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found on the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes that # lay further from the root node will be omitted. Note that setting this option to # 1 or 2 may greatly reduce the computation time needed for large code bases. Also # note that a graph may be further truncated if the graph's image dimensions are # not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH and MAX_DOT_GRAPH_HEIGHT). # If 0 is used for the depth value (the default), the graph is not depth-constrained. MAX_DOT_GRAPH_DEPTH = 0 # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES #--------------------------------------------------------------------------- # Configuration::addtions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO 07070100000012000081A400000000000000000000000166279585000001C8000000000000000000000000000000000000003E00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/Mainpage.dox/** @mainpage libKExiv2 libKExiv2 is a wrapper around <a href="https://exiv2.org/">exiv2</a>, providing read/write access to EXIF, IPTC and XMP metadata. The main differences to <a href="https://exiv2.org/">exiv2</a> are: <ul> <li> Functions take standard Qt containers as parameters <li> Helper functions for GPS data <li> Transparent XMP sidecar support </ul> To get started, have a look at the KExiv2Iface::KExiv2 class. @see KExiv2Iface::KExiv2 */07070100000013000081A4000000000000000000000001662795850000331C000000000000000000000000000000000000003C00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2013 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #include "kexiv2.h" #include "kexiv2_p.h" // Local includes #include "libkexiv2_version.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { KExiv2::KExiv2() : d(new KExiv2Private) { } KExiv2::KExiv2(const KExiv2& metadata) : d(new KExiv2Private) { d->copyPrivateData(metadata.d.get()); } KExiv2::KExiv2(const KExiv2Data& data) : d(new KExiv2Private) { setData(data); } KExiv2::KExiv2(const QString& filePath) : d(new KExiv2Private) { load(filePath); } KExiv2::~KExiv2() = default; KExiv2& KExiv2::operator=(const KExiv2& metadata) { d->copyPrivateData(metadata.d.get()); return *this; } //-- Statics methods ---------------------------------------------- bool KExiv2::initializeExiv2() { #ifdef _XMP_SUPPORT_ if (!Exiv2::XmpParser::initialize()) return false; registerXmpNameSpace(QString::fromLatin1("http://ns.adobe.com/lightroom/1.0/"), QString::fromLatin1("lr")); registerXmpNameSpace(QString::fromLatin1("http://www.digikam.org/ns/kipi/1.0/"), QString::fromLatin1("kipi")); registerXmpNameSpace(QString::fromLatin1("http://ns.microsoft.com/photo/1.2/"), QString::fromLatin1("MP")); registerXmpNameSpace(QString::fromLatin1("http://ns.acdsee.com/iptc/1.0/"), QString::fromLatin1("acdsee")); registerXmpNameSpace(QString::fromLatin1("http://www.video"), QString::fromLatin1("video")); #endif // _XMP_SUPPORT_ #ifdef EXV_ENABLE_BMFF Exiv2::enableBMFF(true); #endif return true; } bool KExiv2::cleanupExiv2() { // Fix memory leak if Exiv2 support XMP. #ifdef _XMP_SUPPORT_ unregisterXmpNameSpace(QString::fromLatin1("http://ns.adobe.com/lightroom/1.0/")); unregisterXmpNameSpace(QString::fromLatin1("http://www.digikam.org/ns/kipi/1.0/")); unregisterXmpNameSpace(QString::fromLatin1("http://ns.microsoft.com/photo/1.2/")); unregisterXmpNameSpace(QString::fromLatin1("http://ns.acdsee.com/iptc/1.0/")); unregisterXmpNameSpace(QString::fromLatin1("http://www.video")); Exiv2::XmpParser::terminate(); #endif // _XMP_SUPPORT_ return true; } bool KExiv2::supportXmp() { #ifdef _XMP_SUPPORT_ return true; #else return false; #endif // _XMP_SUPPORT_ } bool KExiv2::supportMetadataWritting(const QString& typeMime) { if (typeMime == QString::fromLatin1("image/jpeg")) { return true; } else if (typeMime == QString::fromLatin1("image/tiff")) { return true; } else if (typeMime == QString::fromLatin1("image/png")) { return true; } else if (typeMime == QString::fromLatin1("image/jp2")) { return true; } else if (typeMime == QString::fromLatin1("image/x-raw")) { return true; } else if (typeMime == QString::fromLatin1("image/pgf")) { return true; } return false; } QString KExiv2::Exiv2Version() { // Since 0.14.0 release, we can extract run-time version of Exiv2. // else we return make version. return QString::fromStdString(Exiv2::versionString()); } QString KExiv2::version() { return QString::fromLatin1(KEXIV2_VERSION_STRING); } QString KExiv2::sidecarFilePathForFile(const QString& path) { QString ret; if (!path.isEmpty()) { ret = path + QString::fromLatin1(".xmp"); } return ret; } QUrl KExiv2::sidecarUrl(const QUrl& url) { QString sidecarPath = sidecarFilePathForFile(url.path()); QUrl sidecarUrl(url); sidecarUrl.setPath(sidecarPath); return sidecarUrl; } QUrl KExiv2::sidecarUrl(const QString& path) { return QUrl::fromLocalFile(sidecarFilePathForFile(path)); } QString KExiv2::sidecarPath(const QString& path) { return sidecarFilePathForFile(path); } bool KExiv2::hasSidecar(const QString& path) { return QFileInfo(sidecarFilePathForFile(path)).exists(); } //-- General methods ---------------------------------------------- KExiv2Data KExiv2::data() const { KExiv2Data data; data.d = d->data; return data; } void KExiv2::setData(const KExiv2Data& data) { if (data.d) { d->data = data.d; } else { // KExiv2Data can have a null pointer, // but we never want a null pointer in Private. d->data->clear(); } } bool KExiv2::loadFromData(const QByteArray& imgData) const { if (imgData.isEmpty()) return false; try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open((Exiv2::byte*)imgData.data(), imgData.size()); #else Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open((Exiv2::byte*)imgData.data(), imgData.size()); #endif d->filePath.clear(); image->readMetadata(); // Size and mimetype --------------------------------- d->pixelSize = QSize(image->pixelWidth(), image->pixelHeight()); d->mimeType = QString::fromLatin1(image->mimeType().c_str()); // Image comments --------------------------------- d->imageComments() = image->comment(); // Exif metadata ---------------------------------- d->exifMetadata() = image->exifData(); // Iptc metadata ---------------------------------- d->iptcMetadata() = image->iptcData(); #ifdef _XMP_SUPPORT_ // Xmp metadata ----------------------------------- d->xmpMetadata() = image->xmpData(); #endif // _XMP_SUPPORT_ return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot load metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::load(const QString& filePath) const { if (filePath.isEmpty()) { return false; } d->filePath = filePath; bool hasLoaded = false; try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image; #else Exiv2::Image::AutoPtr image; #endif image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(filePath)).constData()); image->readMetadata(); // Size and mimetype --------------------------------- d->pixelSize = QSize(image->pixelWidth(), image->pixelHeight()); d->mimeType = QString::fromLatin1(image->mimeType().c_str()); // Image comments --------------------------------- d->imageComments() = image->comment(); // Exif metadata ---------------------------------- d->exifMetadata() = image->exifData(); // Iptc metadata ---------------------------------- d->iptcMetadata() = image->iptcData(); #ifdef _XMP_SUPPORT_ // Xmp metadata ----------------------------------- d->xmpMetadata() = image->xmpData(); #endif // _XMP_SUPPORT_ hasLoaded = true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot load metadata from file "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #ifdef _XMP_SUPPORT_ try { if (d->useXMPSidecar4Reading) { QString xmpSidecarPath = sidecarFilePathForFile(filePath); QFileInfo xmpSidecarFileInfo(xmpSidecarPath); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr xmpsidecar; #else Exiv2::Image::AutoPtr xmpsidecar; #endif if (xmpSidecarFileInfo.exists() && xmpSidecarFileInfo.isReadable()) { // Read sidecar data xmpsidecar = Exiv2::ImageFactory::open(QFile::encodeName(xmpSidecarPath).constData()); xmpsidecar->readMetadata(); // Merge #if EXIV2_TEST_VERSION(0,28,0) d->loadSidecarData(std::move(xmpsidecar)); #else d->loadSidecarData(xmpsidecar); #endif hasLoaded = true; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot load XMP sidecar"), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #endif // _XMP_SUPPORT_ return hasLoaded; } bool KExiv2::save(const QString& imageFilePath) const { // If our image is really a symlink, we should follow the symlink so that // when we delete the file and rewrite it, we are honoring the symlink // (rather than just deleting it and putting a file there). // However, this may be surprising to the user when they are writing sidecar // files. They might expect them to show up where the symlink is. So, we // shouldn't follow the link when figuring out what the filename for the // sidecar should be. // Note, we are not yet handling the case where the sidecar itself is a // symlink. QString regularFilePath = imageFilePath; // imageFilePath might be a // symlink. Below we will change // regularFile to the pointed to // file if so. QFileInfo givenFileInfo(imageFilePath); if (givenFileInfo.isSymLink()) { qCDebug(LIBKEXIV2_LOG) << "filePath" << imageFilePath << "is a symlink." << "Using target" << givenFileInfo.canonicalPath(); regularFilePath = givenFileInfo.canonicalPath();// Walk all the symlinks } // NOTE: see B.K.O #137770 & #138540 : never touch the file if is read only. QFileInfo finfo(regularFilePath); QFileInfo dinfo(finfo.path()); if (!dinfo.isWritable()) { qCDebug(LIBKEXIV2_LOG) << "Dir '" << dinfo.filePath() << "' is read-only. Metadata not saved."; return false; } bool writeToFile = false; bool writeToSidecar = false; bool writeToSidecarIfFileNotPossible = false; bool writtenToFile = false; bool writtenToSidecar = false; qCDebug(LIBKEXIV2_LOG) << "KExiv2::metadataWritingMode" << d->metadataWritingMode; switch(d->metadataWritingMode) { case WRITETOSIDECARONLY: writeToSidecar = true; break; case WRITETOIMAGEONLY: writeToFile = true; break; case WRITETOSIDECARANDIMAGE: writeToFile = true; writeToSidecar = true; break; case WRITETOSIDECARONLY4READONLYFILES: writeToFile = true; writeToSidecarIfFileNotPossible = true; break; } if (writeToFile) { qCDebug(LIBKEXIV2_LOG) << "Will write Metadata to file" << finfo.absoluteFilePath(); writtenToFile = d->saveToFile(finfo); if (writtenToFile) { qCDebug(LIBKEXIV2_LOG) << "Metadata for file" << finfo.fileName() << "written to file."; } } if (writeToSidecar || (writeToSidecarIfFileNotPossible && !writtenToFile)) { qCDebug(LIBKEXIV2_LOG) << "Will write XMP sidecar for file" << givenFileInfo.fileName(); writtenToSidecar = d->saveToXMPSidecar(QFileInfo(imageFilePath)); if (writtenToSidecar) { qCDebug(LIBKEXIV2_LOG) << "Metadata for file '" << givenFileInfo.fileName() << "' written to XMP sidecar."; } } return writtenToFile || writtenToSidecar; } bool KExiv2::applyChanges() const { if (d->filePath.isEmpty()) { qCDebug(LIBKEXIV2_LOG) << "Failed to apply changes: file path is empty!"; return false; } return save(d->filePath); } bool KExiv2::isEmpty() const { if (!hasComments() && !hasExif() && !hasIptc() && !hasXmp()) return true; return false; } void KExiv2::setFilePath(const QString& path) { d->filePath = path; } QString KExiv2::getFilePath() const { return d->filePath; } QSize KExiv2::getPixelSize() const { return d->pixelSize; } QString KExiv2::getMimeType() const { return d->mimeType; } void KExiv2::setWriteRawFiles(const bool on) { d->writeRawFiles = on; } bool KExiv2::writeRawFiles() const { return d->writeRawFiles; } void KExiv2::setUseXMPSidecar4Reading(const bool on) { d->useXMPSidecar4Reading = on; } bool KExiv2::useXMPSidecar4Reading() const { return d->useXMPSidecar4Reading; } void KExiv2::setMetadataWritingMode(const int mode) { d->metadataWritingMode = mode; } int KExiv2::metadataWritingMode() const { return d->metadataWritingMode; } void KExiv2::setUpdateFileTimeStamp(bool on) { d->updateFileTimeStamp = on; } bool KExiv2::updateFileTimeStamp() const { return d->updateFileTimeStamp; } bool KExiv2::setProgramId(bool /*on*/) const { return true; } } // NameSpace KExiv2Iface 07070100000014000081A4000000000000000000000001662795850000B3FD000000000000000000000000000000000000003A00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2.h/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2013 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef KEXIV2_H #define KEXIV2_H // Std #include <memory> // QT includes #include <QByteArray> #include <QString> #include <QDateTime> #include <QMap> #include <QSharedDataPointer> #include <QStringList> #include <QVariant> #include <QUrl> #include <QImage> // Local includes #include "libkexiv2_export.h" #include "kexiv2data.h" /** * @brief KExiv2Iface - Exiv2 library interface * * @li Exiv2: https://www.exiv2.org * @li Exif : https://www.exif.org/Exif2-2.PDF * @li Iptc : https://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf * @li Xmp : https://www.adobe.com/devnet/xmp.html * https://www.iptc.org/std/Iptc4xmpCore/1.0/specification/Iptc4xmpCore_1.0-spec-XMPSchema_8.pdf * @li Paper: http://www.metadataworkinggroup.com/pdf/mwg_guidance.pdf */ namespace KExiv2Iface { /** * @class KExiv2 kexiv2.h <KExiv2/KExiv2> * * KExiv2 */ class LIBKEXIV2_EXPORT KExiv2 { public: /** The image metadata writing mode, between image file metadata and XMP sidecar file, depending on the context. * @sa MetadataWritingMode(), metadataWritingMode() */ enum MetadataWritingMode { /// Write metadata to image file only. WRITETOIMAGEONLY = 0, /// Write metadata to sidecar file only. WRITETOSIDECARONLY = 1, /// Write metadata to image and sidecar files. WRITETOSIDECARANDIMAGE = 2, /// Write metadata to sidecar file only for read only images such as RAW files for example. WRITETOSIDECARONLY4READONLYFILES = 3 }; /** The image color workspace values given by Exif metadata. */ enum ImageColorWorkSpace { WORKSPACE_UNSPECIFIED = 0, WORKSPACE_SRGB = 1, WORKSPACE_ADOBERGB = 2, WORKSPACE_UNCALIBRATED = 65535 }; /** The image orientation values given by Exif metadata. */ enum ImageOrientation { ORIENTATION_UNSPECIFIED = 0, ORIENTATION_NORMAL = 1, ORIENTATION_HFLIP = 2, ORIENTATION_ROT_180 = 3, ORIENTATION_VFLIP = 4, ORIENTATION_ROT_90_HFLIP = 5, ORIENTATION_ROT_90 = 6, ORIENTATION_ROT_90_VFLIP = 7, ORIENTATION_ROT_270 = 8 }; /** * Xmp tag types, used by setXmpTag, only first three types are used */ enum XmpTagType { NormalTag = 0, ArrayBagTag = 1, StructureTag = 2, ArrayLangTag = 3, ArraySeqTag = 4 }; /** A map used to store Tags Key and Tags Value. */ typedef QMap<QString, QString> MetaDataMap; /** A map used to store a list of Alternative Language values. The map key is the language code following RFC3066 notation (like "fr-FR" for French), and the map value the text. */ typedef QMap<QString, QString> AltLangMap; /** A map used to store Tags Key and a list of Tags properties : - name, - title, - description. */ typedef QMap<QString, QStringList> TagsMap; public: /** Standard constructor. */ KExiv2(); /** Copy constructor. */ KExiv2(const KExiv2& metadata); /** Constructor to load from parsed data. */ KExiv2(const KExiv2Data& data); /** Contructor to Load Metadata from image file. */ KExiv2(const QString& filePath); /** Standard destructor */ virtual ~KExiv2(); /** Create a copy of container */ KExiv2& operator=(const KExiv2& metadata); public: //----------------------------------------------------------------- /// @name Static methods //@{ /** Return true if Exiv2 library initialization is done properly. This method must be called before using libkexiv2 with multithreading. It initialize several non re-entrancy code from Adobe XMP SDK See B.K.O #166424 for details. Call cleanupExiv2() to clean things up later. */ static bool initializeExiv2(); /** Return true if Exiv2 library memory allocations are cleaned properly. This method must be called after using libkexiv2 with multithreading. It cleans up memory used by Adobe XMP SDK See B.K.O #166424 for details. */ static bool cleanupExiv2(); /** Return true if library can handle Xmp metadata */ static bool supportXmp(); /** Return true if library can write metadata to typeMime file format. */ static bool supportMetadataWritting(const QString& typeMime); /** Return a string version of Exiv2 release in format "major.minor.patch" */ static QString Exiv2Version(); /** Return a string version of libkexiv2 release */ static QString version(); /** Return the XMP Sidecar file path for a image file path. * If image file path do not include a file name or is empty, this function return a null string. */ static QString sidecarFilePathForFile(const QString& path); /** Like sidecarFilePathForFile(), but works for local file path. */ static QString sidecarPath(const QString& path); /** Like sidecarFilePathForFile(), but works for remote URLs. */ static QUrl sidecarUrl(const QUrl& url); /** Gives a file url for a local path. */ static QUrl sidecarUrl(const QString& path); /** Performs a QFileInfo based check if the given local file has a sidecar. */ static bool hasSidecar(const QString& path); //@} //----------------------------------------------------------------- /// @name General methods //@{ KExiv2Data data() const; void setData(const KExiv2Data& data); /** Load all metadata (Exif, Iptc, Xmp, and JFIF Comments) from a byte array. Return true if metadata have been loaded successfully from image data. */ bool loadFromData(const QByteArray& imgData) const; /** Load all metadata (Exif, Iptc, Xmp, and JFIF Comments) from a picture (JPEG, RAW, TIFF, PNG, DNG, etc...). Return true if metadata have been loaded successfully from file. */ virtual bool load(const QString& filePath) const; /** Save all metadata to a file. This one can be different than original picture to perform transfert operation Return true if metadata have been saved into file. */ bool save(const QString& filePath) const; /** The same than save() method, but it apply on current image. Return true if metadata have been saved into file. */ bool applyChanges() const; /** Return 'true' if metadata container in memory as no Comments, Exif, Iptc, and Xmp. */ bool isEmpty() const; /** Set the file path of current image. */ void setFilePath(const QString& path); /** Return the file path of current image. */ QString getFilePath() const; /** Returns the pixel size of the current image. This information is read from the file, * not from the metadata. The returned QSize is valid if the KExiv2 object was _constructed_ * by reading a file or image data; the information is not available when the object * was created from KExiv2Data. * Note that in the Exif or XMP metadata, there may be fields describing the image size. * These fields are not accessed by this method. * When replacing the metadata with setData(), the metadata may change; this information * always keeps referring to the file it was initially read from. */ QSize getPixelSize() const; /** Returns the mime type of this image. The information is read from the file; * see the docs for getPixelSize() to know when it is available. */ QString getMimeType() const; /** Enable or disable writing metadata operations to RAW tiff based files. It requires Exiv2 0.18. By default RAW files are untouched. */ void setWriteRawFiles(const bool on); /** Return true if writing metadata operations on RAW tiff based files is enabled. It's require Exiv2 0.18. */ bool writeRawFiles() const; /** Enable or disable using XMP sidecar for reading metadata */ void setUseXMPSidecar4Reading(const bool on); /** Return true if using XMP sidecar for reading metadata is enabled. */ bool useXMPSidecar4Reading() const; /** Set metadata writing mode. * @param mode Metadata writing mode as defined by the #MetadataWritingMode enum. * @sa MetadataWritingMode, metadataWritingMode() */ void setMetadataWritingMode(const int mode); /** Return the metadata writing mode. * @returns Metadata writing mode as defined by the #MetadataWritingMode enum. * @sa MetadataWritingMode, setMetadataWritingMode() */ int metadataWritingMode() const; /** Enable or disable file timestamp updating when metadata are saved. By default files timestamp are untouched. */ void setUpdateFileTimeStamp(bool on); /** Return true if file timestamp is updated when metadata are saved. */ bool updateFileTimeStamp() const; //@} //------------------------------------------------------------------- /// @name Metadata image information manipulation methods //@{ /** Set Program name and program version in Exif and Iptc Metadata. Return true if information have been changed in metadata. */ bool setImageProgramId(const QString& program, const QString& version) const; /** Return the size of image in pixels using Exif tags. Return a null dimmension if size cannot be found. */ QSize getImageDimensions() const; /** Set the size of image in pixels in Exif tags. Return true if size have been changed in metadata. */ bool setImageDimensions(const QSize& size, bool setProgramName=true) const; /** Return the image orientation set in Exif metadata. The makernotes of image are also parsed to get this information. See ImageOrientation values for details. */ KExiv2::ImageOrientation getImageOrientation() const; /** Set the Exif orientation tag of image. See ImageOrientation values for details Return true if orientation have been changed in metadata. */ bool setImageOrientation(ImageOrientation orientation, bool setProgramName=true) const; /** Return the image color-space set in Exif metadata. The makernotes of image are also parsed to get this information. See ImageColorWorkSpace values for details. */ KExiv2::ImageColorWorkSpace getImageColorWorkSpace() const; /** Set the Exif color-space tag of image. See ImageColorWorkSpace values for details Return true if work-space have been changed in metadata. */ bool setImageColorWorkSpace(ImageColorWorkSpace workspace, bool setProgramName=true) const; /** Return the time stamp of image. Exif information are check in first, IPTC in second if image don't have Exif information. If no time stamp is found, a null date is returned. */ QDateTime getImageDateTime() const; /** Set the Exif and Iptc time stamp. If 'setDateTimeDigitized' parameter is true, the 'Digitalized' time stamp is set, else only 'Created' time stamp is set. */ bool setImageDateTime(const QDateTime& dateTime, bool setDateTimeDigitized=false, bool setProgramName=true) const; /** Return the digitization time stamp of the image. First Exif information is checked, then IPTC. If no digitization time stamp is found, getImageDateTime() is called if fallbackToCreationTime is true, or a null QDateTime is returned if fallbackToCreationTime is false. */ QDateTime getDigitizationDateTime(bool fallbackToCreationTime=false) const; /** Return a QImage copy of Iptc preview image. Return a null image if preview cannot be found. */ bool getImagePreview(QImage& preview) const; /** Set the Iptc preview image. The thumbnail image must have the right size before (64Kb max with JPEG file, else 256Kb). Look Iptc specification for details. Return true if preview have been changed in metadata. Re-implemente this method if you want to use another image file format than JPEG to save preview. */ virtual bool setImagePreview(const QImage& preview, bool setProgramName=true) const; //@} //----------------------------------------------------------------- /// @name Comments manipulation methods //@{ /** Return 'true' if Comments can be written in file. */ static bool canWriteComment(const QString& filePath); /** Return 'true' if metadata container in memory as Comments. */ bool hasComments() const; /** Clear the Comments metadata container in memory. */ bool clearComments() const; /** Return a Qt byte array copy of Comments container get from current image. Comments are JFIF section of JPEG images. Look Exiv2 API for more information. Return a null Qt byte array if there is no Comments metadata in memory. */ QByteArray getComments() const; /** Return a Qt string object of Comments from current image decoded using the 'detectEncodingAndDecode()' method. Return a null string if there is no Comments metadata available. */ QString getCommentsDecoded() const; /** Set the Comments data using a Qt byte array. Return true if Comments metadata have been changed in memory. */ bool setComments(const QByteArray& data) const; /** Language Alternative autodetection. Return a QString without language alternative header. Header is saved into 'lang'. If no language alternative is founf, value is returned as well and 'lang' is set to a null string. */ static QString detectLanguageAlt(const QString& value, QString& lang); //@} //----------------------------------------------------------------- /// @name Exif manipulation methods //@{ /** Return a map of all standard Exif tags supported by Exiv2. */ TagsMap getStdExifTagsList() const; /** Return a map of all non-standard Exif tags (makernotes) supported by Exiv2. */ TagsMap getMakernoteTagsList() const; /** Return 'true' if Exif can be written in file. */ static bool canWriteExif(const QString& filePath); /** Return 'true' if metadata container in memory as Exif. */ bool hasExif() const; /** Clear the Exif metadata container in memory. */ bool clearExif() const; /** Returns the exif data encoded to a QByteArray in a form suitable for storage in a JPEG image. Note that this encoding is a lossy operation. Set true 'addExifHeader' parameter to add an Exif header to Exif metadata. Returns a null Qt byte array if there is no Exif metadata in memory. */ QByteArray getExifEncoded(bool addExifHeader=false) const; /** Set the Exif data using a Qt byte array. Return true if Exif metadata have been changed in memory. */ bool setExif(const QByteArray& data) const; /** Return a QImage copy of Exif thumbnail image. Return a null image if thumbnail cannot be found. The 'fixOrientation' parameter will rotate automatically the thumbnail if Exif orientation tags information are attached with thumbnail. */ QImage getExifThumbnail(bool fixOrientation) const; /** Fix orientation of a QImage image accordingly with Exif orientation tag. Return true if image is rotated, else false. */ bool rotateExifQImage(QImage& image, ImageOrientation orientation) const; /** Set the Exif Thumbnail image. The thumbnail image must have the right dimensions before. Look Exif specification for details. Return true if thumbnail have been changed in metadata. */ bool setExifThumbnail(const QImage& thumb, bool setProgramName=true) const; /** Remove the Exif Thumbnail from the image */ bool removeExifThumbnail() const; /** Adds a JPEG thumbnail to a TIFF images. Use this instead of setExifThumbnail for TIFF images. */ bool setTiffThumbnail(const QImage& thumb, bool setProgramName=true) const; /** Return a QString copy of Exif user comments. Return a null string if user comments cannot be found. */ QString getExifComment() const; /** Set the Exif user comments from image. Look Exif specification for more details about this tag. Return true if Exif user comments have been changed in metadata. */ bool setExifComment(const QString& comment, bool setProgramName=true) const; /** Get an Exif tags content like a string. If 'escapeCR' parameter is true, the CR characters will be removed. If Exif tag cannot be found a null string is returned. */ QString getExifTagString(const char* exifTagName, bool escapeCR=true) const; /** Set an Exif tag content using a string. Return true if tag is set successfully. */ bool setExifTagString(const char* exifTagName, const QString& value, bool setProgramName=true) const; /** Get an Exif tag content like a long value. Return true if Exif tag be found. */ bool getExifTagLong(const char* exifTagName, long &val) const; /** Get an Exif tag content like a long value. Return true if Exif tag be found. */ bool getExifTagLong(const char* exifTagName, long &val, int component) const; /** Set an Exif tag content using a long value. Return true if tag is set successfully. */ bool setExifTagLong(const char* exifTagName, long val, bool setProgramName=true) const; /** Get the 'component' index of an Exif tags content like a rational value. 'num' and 'den' are the numerator and the denominator of the rational value. Return true if Exif tag be found. */ bool getExifTagRational(const char* exifTagName, long int& num, long int& den, int component=0) const; /** Set an Exif tag content using a rational value. 'num' and 'den' are the numerator and the denominator of the rational value. Return true if tag is set successfully. */ bool setExifTagRational(const char* exifTagName, long int num, long int den, bool setProgramName=true) const; /** Get an Exif tag content like a bytes array. Return an empty bytes array if Exif tag cannot be found. */ QByteArray getExifTagData(const char* exifTagName) const; /** Set an Exif tag content using a bytes array. Return true if tag is set successfully. */ bool setExifTagData(const char* exifTagName, const QByteArray& data, bool setProgramName=true) const; /** Get an Exif tags content as a QVariant. Returns a null QVariant if the Exif tag cannot be found. For string and integer values the matching QVariant types will be used, for date and time values QVariant::DateTime. Rationals will be returned as QVariant::List with two integer QVariants (numerator, denominator) if rationalAsListOfInts is true, as double if rationalAsListOfInts is false. An exif tag of numerical type may contain more than one value; set component to the desired index. */ QVariant getExifTagVariant(const char* exifTagName, bool rationalAsListOfInts=true, bool escapeCR=true, int component=0) const; /** Set an Exif tag content using a QVariant. Returns true if tag is set successfully. All types described for the getExifTagVariant() method are supported. Calling with a QVariant of type ByteArray is equivalent to calling setExifTagData. For the meaning of rationalWantSmallDenominator, see the documentation of the convertToRational methods. Setting a value with multiple components is currently not supported. */ bool setExifTagVariant(const char* exifTagName, const QVariant& data, bool rationalWantSmallDenominator=true, bool setProgramName=true) const; /** Remove the Exif tag 'exifTagName' from Exif metadata. Return true if tag is removed successfully or if no tag was present. */ bool removeExifTag(const char* exifTagName, bool setProgramName=true) const; /** Return the Exif Tag title or a null string. */ QString getExifTagTitle(const char* exifTagName); /** Return the Exif Tag description or a null string. */ QString getExifTagDescription(const char* exifTagName); /** Takes a QVariant value as it could have been retrieved by getExifTagVariant with the given exifTagName, and returns its value properly converted to a string (including translations from Exiv2). This is equivalent to calling getExifTagString directly. If escapeCR is true CR characters will be removed from the result. */ QString createExifUserStringFromValue(const char* exifTagName, const QVariant& val, bool escapeCR=true); /** Return a map of Exif tags name/value found in metadata sorted by Exif keys given by 'exifKeysFilter'. 'exifKeysFilter' is a QStringList of Exif keys. For example, if you use the string list given below: "Iop" "Thumbnail" "Image" "Photo" List can be empty to not filter output. ... this method will return a map of all Exif tags witch : - include "Iop", or "Thumbnail", or "Image", or "Photo" in the Exif tag keys if 'inverSelection' is false. - not include "Iop", or "Thumbnail", or "Image", or "Photo" in the Exif tag keys if 'inverSelection' is true. */ KExiv2::MetaDataMap getExifTagsDataList(const QStringList& exifKeysFilter=QStringList(), bool invertSelection=false) const; //@} //------------------------------------------------------------- /// @name IPTC manipulation methods //@{ /** Return a map of all standard Iptc tags supported by Exiv2. */ KExiv2::TagsMap getIptcTagsList() const; /** Return 'true' if Iptc can be written in file. */ static bool canWriteIptc(const QString& filePath); /** Return 'true' if metadata container in memory as Iptc. */ bool hasIptc() const; /** Clear the Iptc metadata container in memory. */ bool clearIptc() const; /** Return a Qt byte array copy of Iptc container get from current image. Set true 'addIrbHeader' parameter to add an Irb header to Iptc metadata. Return a null Qt byte array if there is no Iptc metadata in memory. */ QByteArray getIptc(bool addIrbHeader=false) const; /** Set the Iptc data using a Qt byte array. Return true if Iptc metadata have been changed in memory. */ bool setIptc(const QByteArray& data) const; /** Get an Iptc tag content like a string. If 'escapeCR' parameter is true, the CR characters will be removed. If Iptc tag cannot be found a null string is returned. */ QString getIptcTagString(const char* iptcTagName, bool escapeCR=true) const; /** Set an Iptc tag content using a string. Return true if tag is set successfully. */ bool setIptcTagString(const char* iptcTagName, const QString& value, bool setProgramName=true) const; /** Returns a strings list with of multiple Iptc tags from the image. Return an empty list if no tag is found. */ /** Get the values of all IPTC tags with the given tag name in a string list. (In Iptc, there can be multiple tags with the same name) If the 'escapeCR' parameter is true, the CR characters will be removed. If no tag can be found an empty list is returned. */ QStringList getIptcTagsStringList(const char* iptcTagName, bool escapeCR=true) const; /** Set multiple Iptc tags contents using a strings list. 'maxSize' is the max characters size of one entry. Return true if all tags have been set successfully. */ bool setIptcTagsStringList(const char* iptcTagName, int maxSize, const QStringList& oldValues, const QStringList& newValues, bool setProgramName=true) const; /** Get an Iptc tag content as a bytes array. Return an empty bytes array if Iptc tag cannot be found. */ QByteArray getIptcTagData(const char* iptcTagName) const; /** Set an Iptc tag content using a bytes array. Return true if tag is set successfully. */ bool setIptcTagData(const char* iptcTagName, const QByteArray& data, bool setProgramName=true) const; /** Remove the all instance of Iptc tags 'iptcTagName' from Iptc metadata. Return true if all tags have been removed successfully (or none were present). */ bool removeIptcTag(const char* iptcTagName, bool setProgramName=true) const; /** Return the Iptc Tag title or a null string. */ QString getIptcTagTitle(const char* iptcTagName); /** Return the Iptc Tag description or a null string. */ QString getIptcTagDescription(const char* iptcTagName); /** Return a map of Iptc tags name/value found in metadata sorted by Iptc keys given by 'iptcKeysFilter'. 'iptcKeysFilter' is a QStringList of Iptc keys. For example, if you use the string list given below: "Envelope" "Application2" List can be empty to not filter output. ... this method will return a map of all Iptc tags witch : - include "Envelope", or "Application2" in the Iptc tag keys if 'inverSelection' is false. - not include "Envelope", or "Application2" in the Iptc tag keys if 'inverSelection' is true. */ KExiv2::MetaDataMap getIptcTagsDataList(const QStringList& iptcKeysFilter=QStringList(), bool invertSelection=false) const; /** Return a strings list of Iptc keywords from image. Return an empty list if no keyword are set. */ QStringList getIptcKeywords() const; /** Set Iptc keywords using a list of strings defined by 'newKeywords' parameter. Use 'getImageKeywords()' method to set 'oldKeywords' parameter with existing keywords from image. The method will compare all new keywords with all old keywords to prevent duplicate entries in image. Return true if keywords have been changed in metadata. */ bool setIptcKeywords(const QStringList& oldKeywords, const QStringList& newKeywords, bool setProgramName=true) const; /** Return a strings list of Iptc subjects from image. Return an empty list if no subject are set. */ QStringList getIptcSubjects() const; /** Set Iptc subjects using a list of strings defined by 'newSubjects' parameter. Use 'getImageSubjects()' method to set 'oldSubjects' parameter with existing subjects from image. The method will compare all new subjects with all old subjects to prevent duplicate entries in image. Return true if subjects have been changed in metadata. */ bool setIptcSubjects(const QStringList& oldSubjects, const QStringList& newSubjects, bool setProgramName=true) const; /** Return a strings list of Iptc sub-categories from image. Return an empty list if no sub-category are set. */ QStringList getIptcSubCategories() const; /** Set Iptc sub-categories using a list of strings defined by 'newSubCategories' parameter. Use 'getImageSubCategories()' method to set 'oldSubCategories' parameter with existing sub-categories from image. The method will compare all new sub-categories with all old sub-categories to prevent duplicate entries in image. Return true if sub-categories have been changed in metadata. */ bool setIptcSubCategories(const QStringList& oldSubCategories, const QStringList& newSubCategories, bool setProgramName=true) const; //@} //------------------------------------------------------------ /// @name XMP manipulation methods //@{ /** Return a map of all standard Xmp tags supported by Exiv2. */ KExiv2::TagsMap getXmpTagsList() const; /** Return 'true' if Xmp can be written in file. */ static bool canWriteXmp(const QString& filePath); /** Return 'true' if metadata container in memory as Xmp. */ bool hasXmp() const; /** Clear the Xmp metadata container in memory. */ bool clearXmp() const; /** Return a Qt byte array copy of XMp container get from current image. Return a null Qt byte array if there is no Xmp metadata in memory. */ QByteArray getXmp() const; /** Set the Xmp data using a Qt byte array. Return true if Xmp metadata have been changed in memory. */ bool setXmp(const QByteArray& data) const; /** Get a Xmp tag content like a string. If 'escapeCR' parameter is true, the CR characters will be removed. If Xmp tag cannot be found a null string is returned. */ QString getXmpTagString(const char* xmpTagName, bool escapeCR=true) const; /** Set a Xmp tag content using a string. Return true if tag is set successfully. */ bool setXmpTagString(const char* xmpTagName, const QString& value, bool setProgramName=true) const; /** Set a Xmp tag with a specific type. Return true if tag is set successfully. * This method only accept NormalTag, ArrayBagTag and StructureTag. * Other XmpTagTypes do nothing */ bool setXmpTagString(const char* xmpTagName, const QString& value, XmpTagType type,bool setProgramName=true) const; /** Return the Xmp Tag title or a null string. */ QString getXmpTagTitle(const char* xmpTagName); /** Return the Xmp Tag description or a null string. */ QString getXmpTagDescription(const char* xmpTagName); /** Return a map of Xmp tags name/value found in metadata sorted by Xmp keys given by 'xmpKeysFilter'. 'xmpKeysFilter' is a QStringList of Xmp keys. For example, if you use the string list given below: "dc" // Dubling Core schema. "xmp" // Standard Xmp schema. List can be empty to not filter output. ... this method will return a map of all Xmp tags witch : - include "dc", or "xmp" in the Xmp tag keys if 'inverSelection' is false. - not include "dc", or "xmp" in the Xmp tag keys if 'inverSelection' is true. */ KExiv2::MetaDataMap getXmpTagsDataList(const QStringList& xmpKeysFilter=QStringList(), bool invertSelection=false) const; /** Get all redondant Alternative Language Xmp tags content like a map. See AltLangMap class description for details. If 'escapeCR' parameter is true, the CR characters will be removed from strings. If Xmp tag cannot be found a null string list is returned. */ KExiv2::AltLangMap getXmpTagStringListLangAlt(const char* xmpTagName, bool escapeCR=true) const; /** Set an Alternative Language Xmp tag content using a map. See AltLangMap class description for details. If tag already exist, it wil be removed before. Return true if tag is set successfully. */ bool setXmpTagStringListLangAlt(const char* xmpTagName, const KExiv2::AltLangMap& values, bool setProgramName) const; /** Get a Xmp tag content like a string set with an alternative language header 'langAlt' (like "fr-FR" for French - RFC3066 notation) If 'escapeCR' parameter is true, the CR characters will be removed. If Xmp tag cannot be found a null string is returned. */ QString getXmpTagStringLangAlt(const char* xmpTagName, const QString& langAlt, bool escapeCR) const; /** Set a Xmp tag content using a string with an alternative language header. 'langAlt' contain the language alternative information (like "fr-FR" for French - RFC3066 notation) or is null to set alternative language to default settings ("x-default"). Return true if tag is set successfully. */ bool setXmpTagStringLangAlt(const char* xmpTagName, const QString& value, const QString& langAlt, bool setProgramName=true) const; /** Get a Xmp tag content like a sequence of strings. If 'escapeCR' parameter is true, the CR characters will be removed from strings. If Xmp tag cannot be found a null string list is returned. */ QStringList getXmpTagStringSeq(const char* xmpTagName, bool escapeCR=true) const; /** Set a Xmp tag content using the sequence of strings 'seq'. Return true if tag is set successfully. */ bool setXmpTagStringSeq(const char* xmpTagName, const QStringList& seq, bool setProgramName=true) const; /** Get a Xmp tag content like a bag of strings. If 'escapeCR' parameter is true, the CR characters will be removed from strings. If Xmp tag cannot be found a null string list is returned. */ QStringList getXmpTagStringBag(const char* xmpTagName, bool escapeCR) const; /** Set a Xmp tag content using the bag of strings 'bag'. Return true if tag is set successfully. */ bool setXmpTagStringBag(const char* xmpTagName, const QStringList& bag, bool setProgramName=true) const; /** Set an Xmp tag content using a list of strings defined by the 'entriesToAdd' parameter. The existing entries are preserved. The method will compare all new with all already existing entries to prevent duplicates in the image. Return true if the entries have been added to metadata. */ bool addToXmpTagStringBag(const char* xmpTagName, const QStringList& entriesToAdd, bool setProgramName) const; /** Remove those Xmp tag entries that are listed in entriesToRemove from the entries in metadata. Return true if tag entries are no longer contained in metadata. All other entries are preserved. */ bool removeFromXmpTagStringBag(const char* xmpTagName, const QStringList& entriesToRemove, bool setProgramName) const; /** Get an Xmp tag content as a QVariant. Returns a null QVariant if the Xmp tag cannot be found. For string and integer values the matching QVariant types will be used, for date and time values QVariant::DateTime. Rationals will be returned as QVariant::List with two integer QVariants (numerator, denominator) if rationalAsListOfInts is true, as double if rationalAsListOfInts is false. Arrays (ordered, unordered, alternative) are returned as type StringList. LangAlt values will have type Map (QMap<QString, QVariant>) with the language code as key and the contents as value, of type String. */ QVariant getXmpTagVariant(const char* xmpTagName, bool rationalAsListOfInts=true, bool stringEscapeCR=true) const; /** Return a strings list of Xmp keywords from image. Return an empty list if no keyword are set. */ QStringList getXmpKeywords() const; /** Set Xmp keywords using a list of strings defined by 'newKeywords' parameter. The existing keywords from image are preserved. The method will compare all new keywords with all already existing keywords to prevent duplicate entries in image. Return true if keywords have been changed in metadata. */ bool setXmpKeywords(const QStringList& newKeywords, bool setProgramName=true) const; /** Remove those Xmp keywords that are listed in keywordsToRemove from the keywords in metadata. Return true if keywords are no longer contained in metadata. */ bool removeXmpKeywords(const QStringList& keywordsToRemove, bool setProgramName=true); /** Return a strings list of Xmp subjects from image. Return an empty list if no subject are set. */ QStringList getXmpSubjects() const; /** Set Xmp subjects using a list of strings defined by 'newSubjects' parameter. The existing subjects from image are preserved. The method will compare all new subject with all already existing subject to prevent duplicate entries in image. Return true if subjects have been changed in metadata. */ bool setXmpSubjects(const QStringList& newSubjects, bool setProgramName=true) const; /** Remove those Xmp subjects that are listed in subjectsToRemove from the subjects in metadata. Return true if subjects are no longer contained in metadata. */ bool removeXmpSubjects(const QStringList& subjectsToRemove, bool setProgramName=true); /** Return a strings list of Xmp sub-categories from image. Return an empty list if no sub-category are set. */ QStringList getXmpSubCategories() const; /** Set Xmp sub-categories using a list of strings defined by 'newSubCategories' parameter. The existing sub-categories from image are preserved. The method will compare all new sub-categories with all already existing sub-categories to prevent duplicate entries in image. Return true if sub-categories have been changed in metadata. */ bool setXmpSubCategories(const QStringList& newSubCategories, bool setProgramName=true) const; /** Remove those Xmp sub-categories that are listed in categoriesToRemove from the sub-categories in metadata. Return true if subjects are no longer contained in metadata. */ bool removeXmpSubCategories(const QStringList& categoriesToRemove, bool setProgramName=true); /** Remove the Xmp tag 'xmpTagName' from Xmp metadata. Return true if tag is removed successfully or if no tag was present. */ bool removeXmpTag(const char* xmpTagName, bool setProgramName=true) const; /** Register a namespace which Exiv2 doesn't know yet. This is only needed when new Xmp properties are added manually. 'uri' is the namespace url and prefix the string used to construct new Xmp key. NOTE: If the Xmp metadata is read from an image, namespaces are decoded and registered by Exiv2 at the same time. */ static bool registerXmpNameSpace(const QString& uri, const QString& prefix); /** Unregister a previously registered custom namespace */ static bool unregisterXmpNameSpace(const QString& uri); //@} //------------------------------------------------------------ /// @name GPS manipulation methods //@{ /** Make sure all static required GPS EXIF and XMP tags exist */ bool initializeGPSInfo(const bool setProgramName); /** Get all GPS location information set in image. Return true if all information can be found. */ bool getGPSInfo(double& altitude, double& latitude, double& longitude) const; /** Get GPS location information set in the image, in the GPSCoordinate format as described in the XMP specification. Returns a null string in the information cannot be found. */ QString getGPSLatitudeString() const; QString getGPSLongitudeString() const; /** Get GPS location information set in the image, as a double floating point number as in degrees where the sign determines the direction ref (North + / South - ; East + / West -). Returns true if the information is available. */ bool getGPSLatitudeNumber(double* const latitude) const; bool getGPSLongitudeNumber(double* const longitude) const; /** Get GPS altitude information, in meters, relative to sea level (positive sign above sea level) */ bool getGPSAltitude(double* const altitude) const; /** Set all GPS location information into image. Return true if all information have been changed in metadata. */ bool setGPSInfo(const double altitude, const double latitude, const double longitude, const bool setProgramName=true); /** Set all GPS location information into image. Return true if all information have been changed in metadata. If you do not want altitude to be set, pass a null pointer. */ bool setGPSInfo(const double* const altitude, const double latitude, const double longitude, const bool setProgramName=true); /** Set all GPS location information into image. Return true if all information have been changed in metadata. */ bool setGPSInfo(const double altitude, const QString &latitude, const QString &longitude, const bool setProgramName=true); /** Remove all Exif tags relevant of GPS location information. Return true if all tags have been removed successfully in metadata. */ bool removeGPSInfo(const bool setProgramName=true); /** This method converts 'number' to a rational value, returned in the 'numerator' and 'denominator' parameters. Set the precision using 'rounding' parameter. Use this method if you want to retrieve a most exact rational for a number without further properties, without any requirements to the denominator. */ static void convertToRational(const double number, long int* const numerator, long int* const denominator, const int rounding); /** This method convert a 'number' to a rational value, returned in 'numerator' and 'denominator' parameters. This method will be able to retrieve a rational number from a double - if you constructed your double with 1.0 / 4786.0, this method will retrieve 1 / 4786. If your number is not expected to be rational, use the method above which is just as exact with rounding = 4 and more exact with rounding > 4. */ static void convertToRationalSmallDenominator(const double number, long int* const numerator, long int* const denominator); /** Converts a GPS position stored as rationals in Exif to the form described as GPSCoordinate in the XMP specification, either in the from "256,45,34N" or "256,45.566667N" */ static QString convertToGPSCoordinateString(const long int numeratorDegrees, const long int denominatorDegrees, const long int numeratorMinutes, const long int denominatorMinutes, const long int numeratorSeconds, long int denominatorSeconds, const char directionReference); /** Converts a GPS position stored as double floating point number in degrees to the form described as GPSCoordinate in the XMP specification. */ static QString convertToGPSCoordinateString(const bool isLatitude, double coordinate); /** Converts a GPSCoordinate string as defined by XMP to three rationals and the direction reference. Returns true if the conversion was successful. If minutes is given in the fractional form, a denominator of 1000000 for the minutes will be used. */ static bool convertFromGPSCoordinateString(const QString& coordinate, long int* const numeratorDegrees, long int* const denominatorDegrees, long int* const numeratorMinutes, long int* const denominatorMinutes, long int* const numeratorSeconds, long int* const denominatorSeconds, char* const directionReference); /** Convert a GPSCoordinate string as defined by XMP to a double floating point number in degrees where the sign determines the direction ref (North + / South - ; East + / West -). Returns true if the conversion was successful. */ static bool convertFromGPSCoordinateString(const QString& gpsString, double* const coordinate); /** Converts a GPSCoordinate string to user presentable numbers, integer degrees and minutes and double floating point seconds, and a direction reference ('N' or 'S', 'E' or 'W') */ static bool convertToUserPresentableNumbers(const QString& coordinate, int* const degrees, int* const minutes, double* const seconds, char* const directionReference); /** Converts a double floating point number to user presentable numbers, integer degrees and minutes and double floating point seconds, and a direction reference ('N' or 'S', 'E' or 'W'). The method needs to know for the direction reference if the latitude or the longitude is meant by the double parameter. */ static void convertToUserPresentableNumbers(const bool isLatitude, double coordinate, int* const degrees, int* const minutes, double* const seconds, char* const directionReference); //@} protected: /** Re-implement this method to set automatically the Program Name and Program Version information in Exif and Iptc metadata if 'on' argument is true. This method is called by all methods which change tags in metadata. By default this method does nothing and returns true. */ virtual bool setProgramId(bool on=true) const; private: /** Internal container to store private members. Used to improve binary compatibility */ std::unique_ptr<class KExiv2Private> const d; friend class KExiv2Previews; }; } // NameSpace KExiv2Iface #endif /* KEXIV2_H */ 07070100000015000081A4000000000000000000000001662795850000630F000000000000000000000000000000000000003E00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2_p.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #include "kexiv2_p.h" // C ANSI includes extern "C" { #include <sys/stat.h> #ifndef _MSC_VER #include <utime.h> #else #include <sys/utime.h> #endif } // Qt includes #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include <QStringDecoder> #else #include <QTextCodec> #endif // Local includes #include "libkexiv2_debug.h" // Pragma directives to reduce warnings from Exiv2. #if !defined(__APPLE__) && defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif namespace KExiv2Iface { KExiv2Private::KExiv2Private() : data(new KExiv2DataPrivate) { writeRawFiles = false; updateFileTimeStamp = false; useXMPSidecar4Reading = false; metadataWritingMode = KExiv2::WRITETOIMAGEONLY; loadedFromSidecar = false; Exiv2::LogMsg::setHandler(KExiv2Private::printExiv2MessageHandler); } KExiv2Private::~KExiv2Private() = default; void KExiv2Private::copyPrivateData(const KExiv2Private* const other) { data = other->data; filePath = other->filePath; writeRawFiles = other->writeRawFiles; updateFileTimeStamp = other->updateFileTimeStamp; useXMPSidecar4Reading = other->useXMPSidecar4Reading; metadataWritingMode = other->metadataWritingMode; } bool KExiv2Private::saveToXMPSidecar(const QFileInfo& finfo) const { QString filePath = KExiv2::sidecarFilePathForFile(finfo.filePath()); if (filePath.isEmpty()) { return false; } try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image; #else Exiv2::Image::AutoPtr image; #endif image = Exiv2::ImageFactory::create(Exiv2::ImageType::xmp, (const char*)(QFile::encodeName(filePath).constData())); #if EXIV2_TEST_VERSION(0,28,0) return saveOperations(finfo, std::move(image)); #else return saveOperations(finfo, image); #endif } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata to XMP sidecar using Exiv2 "), e); return false; } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; return false; } } bool KExiv2Private::saveToFile(const QFileInfo& finfo) const { if (!finfo.isWritable()) { qCDebug(LIBKEXIV2_LOG) << "File '" << finfo.fileName().toLatin1().constData() << "' is read only. Metadata not written."; return false; } QStringList rawTiffBasedSupported, rawTiffBasedNotSupported; // Raw files supported by Exiv2 0.23 rawTiffBasedSupported << QString::fromLatin1("dng") << QString::fromLatin1("nef") << QString::fromLatin1("pef") << QString::fromLatin1("orf") << QString::fromLatin1("srw") << QString::fromLatin1("cr2"); // Raw files not supported by Exiv2 0.23 rawTiffBasedNotSupported << QString::fromLatin1("3fr") << QString::fromLatin1("arw") << QString::fromLatin1("dcr") << QString::fromLatin1("erf") << QString::fromLatin1("k25") << QString::fromLatin1("kdc") << QString::fromLatin1("mos") << QString::fromLatin1("raw") << QString::fromLatin1("sr2") << QString::fromLatin1("srf") << QString::fromLatin1("rw2"); QString ext = finfo.suffix().toLower(); if (!writeRawFiles && (rawTiffBasedSupported.contains(ext) || rawTiffBasedNotSupported.contains(ext)) ) { qCDebug(LIBKEXIV2_LOG) << finfo.fileName() << "is a TIFF based RAW file, writing to such a file is disabled by current settings."; return false; } /* if (rawTiffBasedNotSupported.contains(ext)) { qCDebug(LIBKEXIV2_LOG) << finfo.fileName() << "is TIFF based RAW file not yet supported. Metadata not saved."; return false; } if (rawTiffBasedSupported.contains(ext) && !writeRawFiles) { qCDebug(LIBKEXIV2_LOG) << finfo.fileName() << "is TIFF based RAW file supported but writing mode is disabled. " << "Metadata not saved."; return false; } qCDebug(LIBKEXIV2_LOG) << "File Extension: " << ext << " is supported for writing mode"; bool ret = false; */ try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image; #else Exiv2::Image::AutoPtr image; #endif image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(finfo.filePath()).constData())); #if EXIV2_TEST_VERSION(0,28,0) return saveOperations(finfo, std::move(image)); #else return saveOperations(finfo, image); #endif } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata to image using Exiv2 "), e); return false; } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; return false; } } #if EXIV2_TEST_VERSION(0,28,0) bool KExiv2Private::saveOperations(const QFileInfo& finfo, Exiv2::Image::UniquePtr image) const #else bool KExiv2Private::saveOperations(const QFileInfo& finfo, Exiv2::Image::AutoPtr image) const #endif { try { Exiv2::AccessMode mode; bool wroteComment = false, wroteEXIF = false, wroteIPTC = false, wroteXMP = false; // We need to load target file metadata to merge with new one. It's mandatory with TIFF format: // like all tiff file structure is based on Exif. image->readMetadata(); // Image Comments --------------------------------- mode = image->checkMode(Exiv2::mdComment); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { image->setComment(imageComments()); wroteComment = true; } qCDebug(LIBKEXIV2_LOG) << "wroteComment: " << wroteComment; // Exif metadata ---------------------------------- mode = image->checkMode(Exiv2::mdExif); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { if (image->mimeType() == "image/tiff") { Exiv2::ExifData orgExif = image->exifData(); Exiv2::ExifData newExif; QStringList untouchedTags; // With tiff image we cannot overwrite whole Exif data as well, because // image data are stored in Exif container. We need to take a care about // to not lost image data. untouchedTags << QString::fromLatin1("Exif.Image.ImageWidth"); untouchedTags << QString::fromLatin1("Exif.Image.ImageLength"); untouchedTags << QString::fromLatin1("Exif.Image.BitsPerSample"); untouchedTags << QString::fromLatin1("Exif.Image.Compression"); untouchedTags << QString::fromLatin1("Exif.Image.PhotometricInterpretation"); untouchedTags << QString::fromLatin1("Exif.Image.FillOrder"); untouchedTags << QString::fromLatin1("Exif.Image.SamplesPerPixel"); untouchedTags << QString::fromLatin1("Exif.Image.StripOffsets"); untouchedTags << QString::fromLatin1("Exif.Image.RowsPerStrip"); untouchedTags << QString::fromLatin1("Exif.Image.StripByteCounts"); untouchedTags << QString::fromLatin1("Exif.Image.XResolution"); untouchedTags << QString::fromLatin1("Exif.Image.YResolution"); untouchedTags << QString::fromLatin1("Exif.Image.PlanarConfiguration"); untouchedTags << QString::fromLatin1("Exif.Image.ResolutionUnit"); for (Exiv2::ExifData::iterator it = orgExif.begin(); it != orgExif.end(); ++it) { if (untouchedTags.contains(QString::fromLatin1(it->key().c_str()))) { newExif[it->key().c_str()] = orgExif[it->key().c_str()]; } } Exiv2::ExifData readedExif = exifMetadata(); for (Exiv2::ExifData::iterator it = readedExif.begin(); it != readedExif.end(); ++it) { if (!untouchedTags.contains(QString::fromLatin1(it->key().c_str()))) { newExif[it->key().c_str()] = readedExif[it->key().c_str()]; } } image->setExifData(newExif); } else { image->setExifData(exifMetadata()); } wroteEXIF = true; } qCDebug(LIBKEXIV2_LOG) << "wroteEXIF: " << wroteEXIF; // Iptc metadata ---------------------------------- mode = image->checkMode(Exiv2::mdIptc); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { image->setIptcData(iptcMetadata()); wroteIPTC = true; } qCDebug(LIBKEXIV2_LOG) << "wroteIPTC: " << wroteIPTC; // Xmp metadata ----------------------------------- mode = image->checkMode(Exiv2::mdXmp); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { #ifdef _XMP_SUPPORT_ image->setXmpData(xmpMetadata()); wroteXMP = true; #endif } qCDebug(LIBKEXIV2_LOG) << "wroteXMP: " << wroteXMP; if (!wroteComment && !wroteEXIF && !wroteIPTC && !wroteXMP) { qCDebug(LIBKEXIV2_LOG) << "Writing metadata is not supported for file" << finfo.fileName(); return false; } else if (!wroteEXIF || !wroteIPTC || !wroteXMP) { qCDebug(LIBKEXIV2_LOG) << "Support for writing metadata is limited for file" << finfo.fileName(); } if (!updateFileTimeStamp) { // Don't touch access and modification timestamp of file. struct stat st; struct utimbuf ut; int ret = ::stat(QFile::encodeName(filePath).constData(), &st); if (ret == 0) { ut.modtime = st.st_mtime; ut.actime = st.st_atime; } image->writeMetadata(); if (ret == 0) { ::utime(QFile::encodeName(filePath).constData(), &ut); } qCDebug(LIBKEXIV2_LOG) << "File time stamp restored"; } else { image->writeMetadata(); } return true; } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } void KExiv2DataPrivate::clear() { imageComments.clear(); exifMetadata.clear(); iptcMetadata.clear(); #ifdef _XMP_SUPPORT_ xmpMetadata.clear(); #endif } void KExiv2Private::printExiv2ExceptionError(const QString& msg, Exiv2::Error& e) { std::string s(e.what()); qCCritical(LIBKEXIV2_LOG) << msg.toLatin1().constData() << " (Error #" #if EXIV2_TEST_VERSION(0,28,0) << Exiv2::Error(e.code()).what() #else << e.code() << ": " << s.c_str() #endif << ")"; } void KExiv2Private::printExiv2MessageHandler(int lvl, const char* msg) { qCDebug(LIBKEXIV2_LOG) << "Exiv2 (" << lvl << ") : " << msg; } QString KExiv2Private::convertCommentValue(const Exiv2::Exifdatum& exifDatum) const { try { std::string comment; std::string charset; comment = exifDatum.toString(); // libexiv2 will prepend "charset=\"SomeCharset\" " if charset is specified // Before conversion to QString, we must know the charset, so we stay with std::string for a while if (comment.length() > 8 && comment.substr(0, 8) == "charset=") { // the prepended charset specification is followed by a blank std::string::size_type pos = comment.find_first_of(' '); if (pos != std::string::npos) { // extract string between the = and the blank charset = comment.substr(8, pos-8); // get the rest of the string after the charset specification comment = comment.substr(pos+1); } } if (charset == "\"Unicode\"") { return QString::fromUtf8(comment.data()); } else if (charset == "\"Jis\"") { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) QStringDecoder codec("JIS7"); return codec.decode(comment.c_str()); #else QTextCodec* const codec = QTextCodec::codecForName("JIS7"); return codec->toUnicode(comment.c_str()); #endif } else if (charset == "\"Ascii\"") { return QString::fromLatin1(comment.c_str()); } else { return detectEncodingAndDecode(comment); } } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot convert Comment using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } QString KExiv2Private::detectEncodingAndDecode(const std::string& value) const { // For charset autodetection, we could use sophisticated code // (Mozilla chardet, KHTML's autodetection, QTextCodec::codecForContent), // but that is probably too much. // We check for UTF8, Local encoding and ASCII. // Look like KEncodingDetector class can provide a full implementation for encoding detection. if (value.empty()) { return QString(); } if (isUtf8(value.c_str())) { return QString::fromUtf8(value.c_str()); } // Utf8 has a pretty unique byte pattern. // Thats not true for ASCII, it is not possible // to reliably autodetect different ISO-8859 charsets. // So we can use either local encoding, or latin1. return QString::fromLocal8Bit(value.c_str()); } bool KExiv2Private::isUtf8(const char* const buffer) const { int i, n; unsigned char c; bool gotone = false; if (!buffer) return true; // character never appears in text #define F 0 // character appears in plain ASCII text #define T 1 // character appears in ISO-8859 text #define I 2 // character appears in non-ISO extended ASCII (Mac, IBM PC) #define X 3 static const unsigned char text_chars[256] = { // BEL BS HT LF FF CR F, F, F, F, F, F, F, T, T, T, T, F, T, T, F, F, // 0x0X // ESC F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, F, // 0x1X T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, // 0x2X T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, // 0x3X T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, // 0x4X T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, // 0x5X T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, // 0x6X T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, // 0x7X // NEL X, X, X, X, X, T, X, X, X, X, X, X, X, X, X, X, // 0x8X X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, // 0x9X I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, // 0xaX I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, // 0xbX I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, // 0xcX I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, // 0xdX I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, // 0xeX I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I // 0xfX }; for (i = 0; (c = buffer[i]); ++i) { if ((c & 0x80) == 0) { // 0xxxxxxx is plain ASCII // Even if the whole file is valid UTF-8 sequences, // still reject it if it uses weird control characters. if (text_chars[c] != T) return false; } else if ((c & 0x40) == 0) { // 10xxxxxx never 1st byte return false; } else { // 11xxxxxx begins UTF-8 int following = 0; if ((c & 0x20) == 0) { // 110xxxxx following = 1; } else if ((c & 0x10) == 0) { // 1110xxxx following = 2; } else if ((c & 0x08) == 0) { // 11110xxx following = 3; } else if ((c & 0x04) == 0) { // 111110xx following = 4; } else if ((c & 0x02) == 0) { // 1111110x following = 5; } else { return false; } for (n = 0; n < following; ++n) { i++; if (!(c = buffer[i])) goto done; if ((c & 0x80) == 0 || (c & 0x40)) return false; } gotone = true; } } done: return gotone; // don't claim it's UTF-8 if it's all 7-bit. } #undef F #undef T #undef I #undef X int KExiv2Private::getXMPTagsListFromPrefix(const QString& pf, KExiv2::TagsMap& tagsMap) const { int i = 0; #ifdef _XMP_SUPPORT_ try { QList<const Exiv2::XmpPropertyInfo*> tags; tags << Exiv2::XmpProperties::propertyList(pf.toLatin1().data()); for (QList<const Exiv2::XmpPropertyInfo*>::iterator it = tags.begin(); it != tags.end(); ++it) { while ( (*it) && !QString::fromLatin1((*it)->name_).isNull() ) { QString key = QLatin1String( Exiv2::XmpKey( pf.toLatin1().data(), (*it)->name_ ).key().c_str() ); QStringList values; values << QString::fromLatin1((*it)->name_) << QString::fromLatin1((*it)->title_) << QString::fromLatin1((*it)->desc_); tagsMap.insert(key, values); ++(*it); i++; } } } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot get Xmp tags list using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(pf); Q_UNUSED(tagsMap); #endif // _XMP_SUPPORT_ return i; } #ifdef _XMP_SUPPORT_ #if EXIV2_TEST_VERSION(0,28,0) void KExiv2Private::loadSidecarData(Exiv2::Image::UniquePtr xmpsidecar) #else void KExiv2Private::loadSidecarData(Exiv2::Image::AutoPtr xmpsidecar) #endif { // Having a sidecar is a special situation. // The sidecar data often "dominates", see in particular bug 309058 for important aspects: // If a field is removed from the sidecar, we must ignore (older) data for this field in the file. // First: Ignore file XMP, only use sidecar XMP xmpMetadata() = xmpsidecar->xmpData(); loadedFromSidecar = true; // EXIF // Four groups of properties are mapped between EXIF and XMP: // Date/Time, Description, Copyright, Creator // A few more tags are defined "writeback" tags in the XMP specification, the sidecar value therefore overrides the Exif value. // The rest is kept side-by-side. // (to understand, remember that the xmpsidecar's Exif data is actually XMP data mapped back to Exif) // Description, Copyright and Creator is dominated by the sidecar: Remove file Exif fields, if field not in XMP. ExifMergeHelper exifDominatedHelper; exifDominatedHelper << QLatin1String("Exif.Image.ImageDescription") << QLatin1String("Exif.Photo.UserComment") << QLatin1String("Exif.Image.Copyright") << QLatin1String("Exif.Image.Artist"); exifDominatedHelper.exclusiveMerge(xmpsidecar->exifData(), exifMetadata()); // Date/Time and "the few more" from the XMP spec are handled as writeback // Note that Date/Time mapping is slightly contradictory in latest specs. ExifMergeHelper exifWritebackHelper; exifWritebackHelper << QLatin1String("Exif.Image.DateTime") << QLatin1String("Exif.Image.DateTime") << QLatin1String("Exif.Photo.DateTimeOriginal") << QLatin1String("Exif.Photo.DateTimeDigitized") << QLatin1String("Exif.Image.Orientation") << QLatin1String("Exif.Image.XResolution") << QLatin1String("Exif.Image.YResolution") << QLatin1String("Exif.Image.ResolutionUnit") << QLatin1String("Exif.Image.Software") << QLatin1String("Exif.Photo.RelatedSoundFile"); exifWritebackHelper.mergeFields(xmpsidecar->exifData(), exifMetadata()); // IPTC // These fields cover almost all relevant IPTC data and are defined in the XMP specification for reconciliation. IptcMergeHelper iptcDominatedHelper; iptcDominatedHelper << QLatin1String("Iptc.Application2.ObjectName") << QLatin1String("Iptc.Application2.Urgency") << QLatin1String("Iptc.Application2.Category") << QLatin1String("Iptc.Application2.SuppCategory") << QLatin1String("Iptc.Application2.Keywords") << QLatin1String("Iptc.Application2.SubLocation") << QLatin1String("Iptc.Application2.SpecialInstructions") << QLatin1String("Iptc.Application2.Byline") << QLatin1String("Iptc.Application2.BylineTitle") << QLatin1String("Iptc.Application2.City") << QLatin1String("Iptc.Application2.ProvinceState") << QLatin1String("Iptc.Application2.CountryCode") << QLatin1String("Iptc.Application2.CountryName") << QLatin1String("Iptc.Application2.TransmissionReference") << QLatin1String("Iptc.Application2.Headline") << QLatin1String("Iptc.Application2.Credit") << QLatin1String("Iptc.Application2.Source") << QLatin1String("Iptc.Application2.Copyright") << QLatin1String("Iptc.Application2.Caption") << QLatin1String("Iptc.Application2.Writer"); iptcDominatedHelper.exclusiveMerge(xmpsidecar->iptcData(), iptcMetadata()); IptcMergeHelper iptcWritebackHelper; iptcWritebackHelper << QLatin1String("Iptc.Application2.DateCreated") << QLatin1String("Iptc.Application2.TimeCreated") << QLatin1String("Iptc.Application2.DigitizationDate") << QLatin1String("Iptc.Application2.DigitizationTime"); iptcWritebackHelper.mergeFields(xmpsidecar->iptcData(), iptcMetadata()); /* * TODO: Exiv2 (referring to 0.23) does not correctly synchronize all times values as given below. * Time values and their synchronization: * Original Date/Time – Creation date of the intellectual content (e.g. the photograph), rather than the creatio*n date of the content being shown Exif DateTimeOriginal (36867, 0x9003) and SubSecTimeOriginal (37521, 0x9291) IPTC DateCreated (IIM 2:55, 0x0237) and TimeCreated (IIM 2:60, 0x023C) XMP (photoshop:DateCreated) * Digitized Date/Time – Creation date of the digital representation Exif DateTimeDigitized (36868, 0x9004) and SubSecTimeDigitized (37522, 0x9292) IPTC DigitalCreationDate (IIM 2:62, 0x023E) and DigitalCreationTime (IIM 2:63, 0x023F) XMP (xmp:CreateDate) * Modification Date/Time – Modification date of the digital image file Exif DateTime (306, 0x132) and SubSecTime (37520, 0x9290) XMP (xmp:ModifyDate) */ } #endif // _XMP_SUPPORT_ } // NameSpace KExiv2Iface // Restore warnings #if !defined(__APPLE__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic pop #endif 07070100000016000081A40000000000000000000000016627958500002054000000000000000000000000000000000000003C00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2_p.h/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef KEXIV2PRIVATE_H #define KEXIV2PRIVATE_H #include "kexiv2.h" // C++ includes #include <cstdlib> #include <cstdio> #include <cassert> #include <cmath> #include <cfloat> #include <iostream> #include <iomanip> #include <string> // Qt includes #include <QFile> #include <QSize> #include <QLatin1String> #include <QFileInfo> #include <QSharedData> // Exiv2 includes ------------------------------------------------------- // NOTE: All Exiv2 header must be stay there to not expose external source code to Exiv2 API // and reduce Exiv2 dependency to client code. // The pragmas are required to be able to catch exceptions thrown by libexiv2: // See https://gcc.gnu.org/wiki/Visibility, the section about c++ exceptions. // They are needed for all libexiv2 versions that do not care about visibility. #ifdef __GNUC__ #pragma GCC visibility push(default) #endif #include <exiv2/exiv2.hpp> // Check if Exiv2 support XMP #ifdef EXV_HAVE_XMP_TOOLKIT # define _XMP_SUPPORT_ 1 #endif // With exiv2 > 0.20.0, all makernote header files have been removed to increase binary compatibility. // See Exiv2 bugzilla entry https://dev.exiv2.org/issues/719 // and wiki topic https://dev.exiv2.org/boards/3/topics/583 #ifdef __GNUC__ #pragma GCC visibility pop #endif // End of Exiv2 headers ------------------------------------------------------ namespace KExiv2Iface { class KExiv2DataPrivate : public QSharedData { public: void clear(); public: std::string imageComments; Exiv2::ExifData exifMetadata; Exiv2::IptcData iptcMetadata; #ifdef _XMP_SUPPORT_ Exiv2::XmpData xmpMetadata; #endif }; // -------------------------------------------------------------------------- class KExiv2Private { public: KExiv2Private(); ~KExiv2Private(); void copyPrivateData(const KExiv2Private* const other); bool saveToXMPSidecar(const QFileInfo& finfo) const; bool saveToFile(const QFileInfo& finfo) const; #if EXIV2_TEST_VERSION(0,28,0) bool saveOperations(const QFileInfo& finfo, Exiv2::Image::UniquePtr image) const; #else bool saveOperations(const QFileInfo& finfo, Exiv2::Image::AutoPtr image) const; #endif /** Wrapper method to convert a Comments content to a QString. */ QString convertCommentValue(const Exiv2::Exifdatum& exifDatum) const; /** Charset autodetection to convert a string to a QString. */ QString detectEncodingAndDecode(const std::string& value) const; /** UTF8 autodetection from a string. */ bool isUtf8(const char* const buffer) const; int getXMPTagsListFromPrefix(const QString& pf, KExiv2::TagsMap& tagsMap) const; const Exiv2::ExifData& exifMetadata() const { return data.constData()->exifMetadata; } const Exiv2::IptcData& iptcMetadata() const { return data.constData()->iptcMetadata; } const std::string& imageComments() const { return data.constData()->imageComments; } #ifdef _XMP_SUPPORT_ const Exiv2::XmpData& xmpMetadata() const { return data.constData()->xmpMetadata; } #endif Exiv2::ExifData& exifMetadata() { return data.data()->exifMetadata; } Exiv2::IptcData& iptcMetadata() { return data.data()->iptcMetadata; } std::string& imageComments() { return data.data()->imageComments; } #ifdef _XMP_SUPPORT_ Exiv2::XmpData& xmpMetadata() { return data.data()->xmpMetadata; } #if EXIV2_TEST_VERSION(0,28,0) void loadSidecarData(Exiv2::Image::UniquePtr xmpsidecar); #else void loadSidecarData(Exiv2::Image::AutoPtr xmpsidecar); #endif #endif public: /** Generic method to print the Exiv2 C++ Exception error message from 'e'. * 'msg' string is printed using kDebug rules.. */ static void printExiv2ExceptionError(const QString& msg, Exiv2::Error& e); /** Generic method to print debug message from Exiv2. * 'msg' string is printed using kDebug rules. 'lvl' is the debug level of Exiv2 message. */ static void printExiv2MessageHandler(int lvl, const char* msg); public: bool writeRawFiles; bool updateFileTimeStamp; bool useXMPSidecar4Reading; /// A mode from #MetadataWritingMode enum. int metadataWritingMode; /// XMP, and parts of EXIF/IPTC, were loaded from an XMP sidecar file bool loadedFromSidecar; QString filePath; QSize pixelSize; QString mimeType; QSharedDataPointer<KExiv2DataPrivate> data; }; // -------------------------------------------------------------------------------------------- template <class Data, class Key, class KeyString, class KeyStringList = QList<KeyString> > class MergeHelper { public: KeyStringList keys; MergeHelper& operator<<(const KeyString& key) { keys << key; return *this; } /** * Merge two (Exif,IPTC,Xmp)Data packages, where the result is stored in dest * and fields from src take precedence over existing data from dest. */ void mergeAll(const Data& src, Data& dest) { for (typename Data::const_iterator it = src.begin(); it != src.end(); ++it) { typename Data::iterator destIt = dest.findKey(Key(it->key())); if (destIt == dest.end()) { dest.add(*it); } else { *destIt = *it; } } } /** * Merge two (Exif,IPTC,Xmp)Data packages, the result is stored in dest. * Only keys in keys are considered for merging. * Fields from src take precedence over existing data from dest. */ void mergeFields(const Data& src, Data& dest) const { for (const KeyString& keyString : keys) { Key key(keyString.latin1()); typename Data::const_iterator it = src.findKey(key); if (it == src.end()) { continue; } typename Data::iterator destIt = dest.findKey(key); if (destIt == dest.end()) { dest.add(*it); } else { *destIt = *it; } } } /** * Merge two (Exif,IPTC,Xmp)Data packages, the result is stored in dest. * The following steps apply only to keys in "keys": * The result is determined by src. * Keys must exist in src to kept in dest. * Fields from src take precedence over existing data from dest. */ void exclusiveMerge(const Data& src, Data& dest) const { for (const KeyString& keyString : keys) { Key key(keyString.latin1()); typename Data::const_iterator it = src.findKey(key); typename Data::iterator destIt = dest.findKey(key); if (destIt == dest.end()) { if (it != src.end()) { dest.add(*it); } } else { if (it == src.end()) { dest.erase(destIt); } else { *destIt = *it; } } } } }; class ExifMergeHelper : public MergeHelper<Exiv2::ExifData, Exiv2::ExifKey, QLatin1String> { }; class IptcMergeHelper : public MergeHelper<Exiv2::IptcData, Exiv2::IptcKey, QLatin1String> { }; #ifdef _XMP_SUPPORT_ class XmpMergeHelper : public MergeHelper<Exiv2::XmpData, Exiv2::XmpKey, QLatin1String> { }; #endif } // NameSpace KExiv2Iface #endif // KEXIV2PRIVATE_H 07070100000017000081A4000000000000000000000001662795850000094E000000000000000000000000000000000000004400000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2comments.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ // Local includes #include "kexiv2_p.h" #include "kexiv2.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { bool KExiv2::canWriteComment(const QString& filePath) { try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image #else Exiv2::Image::AutoPtr image #endif = Exiv2::ImageFactory::open((const char*) (QFile::encodeName(filePath).constData())); Exiv2::AccessMode mode = image->checkMode(Exiv2::mdComment); return (mode == Exiv2::amWrite || mode == Exiv2::amReadWrite); } catch( Exiv2::Error& e ) { std::string s(e.what()); qCCritical(LIBKEXIV2_LOG) << "Cannot check Comment access mode using Exiv2 (Error #" #if EXIV2_TEST_VERSION(0,28,0) << Exiv2::Error(e.code()).what() #else << e.code() << ": " << s.c_str() #endif << ")"; } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::hasComments() const { return !d->imageComments().empty(); } bool KExiv2::clearComments() const { return setComments(QByteArray()); } QByteArray KExiv2::getComments() const { return QByteArray(d->imageComments().data(), d->imageComments().size()); } QString KExiv2::getCommentsDecoded() const { return d->detectEncodingAndDecode(d->imageComments()); } bool KExiv2::setComments(const QByteArray& data) const { d->imageComments() = std::string(data.data(), data.size()); return true; } QString KExiv2::detectLanguageAlt(const QString& value, QString& lang) { // Ex. from an Xmp tag Xmp.tiff.copyright: "lang="x-default" (c) Gilles Caulier 2007" if (value.size() > 6 && value.startsWith(QString::fromLatin1("lang=\""))) { int pos = value.indexOf(QString::fromLatin1("\""), 6); if (pos != -1) { lang = value.mid(6, pos-6); return (value.mid(pos+2)); } } lang.clear(); return value; } } // NameSpace KExiv2Iface 07070100000018000081A4000000000000000000000001662795850000026B000000000000000000000000000000000000004000000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2data.cpp/* SPDX-FileCopyrightText: 2009-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2009-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ // Local includes #include "kexiv2data.h" #include "kexiv2.h" #include "kexiv2_p.h" namespace KExiv2Iface { KExiv2Data::KExiv2Data() : d(nullptr) { } KExiv2Data::KExiv2Data(const KExiv2Data& other) { d = other.d; } KExiv2Data::~KExiv2Data() { } KExiv2Data& KExiv2Data::operator=(const KExiv2Data& other) { d = other.d; return *this; } } // NameSpace KExiv2Iface 07070100000019000081A400000000000000000000000166279585000002C5000000000000000000000000000000000000003E00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2data.h/* SPDX-FileCopyrightText: 2009-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2009-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef KEXIV2DATA_H #define KEXIV2DATA_H // Qt includes #include <QSharedDataPointer> // Local includes #include "libkexiv2_export.h" namespace KExiv2Iface { class LIBKEXIV2_EXPORT KExiv2Data { public: KExiv2Data(); KExiv2Data(const KExiv2Data&); ~KExiv2Data(); KExiv2Data& operator=(const KExiv2Data&); private: QSharedDataPointer<class KExiv2DataPrivate> d; friend class KExiv2; }; } // NameSpace KExiv2Iface #endif /* KEXIV2DATA_H */ 0707010000001A000081A4000000000000000000000001662795850000875F000000000000000000000000000000000000004000000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2exif.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #include "kexiv2.h" #include "kexiv2_p.h" // C++ includes #include <cctype> // Qt includes #include <QBuffer> // Local includes #include "rotationmatrix.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { bool KExiv2::canWriteExif(const QString& filePath) { try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image = #else Exiv2::Image::AutoPtr image = #endif Exiv2::ImageFactory::open((const char*) (QFile::encodeName(filePath).constData())); Exiv2::AccessMode mode = image->checkMode(Exiv2::mdExif); return (mode == Exiv2::amWrite || mode == Exiv2::amReadWrite); } catch( Exiv2::Error& e ) { std::string s(e.what()); qCCritical(LIBKEXIV2_LOG) << "Cannot check Exif access mode using Exiv2 (Error #" #if EXIV2_TEST_VERSION(0,28,0) << Exiv2::Error(e.code()).what() #else << e.code() << ": " << s.c_str() #endif << ")"; } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::hasExif() const { return !d->exifMetadata().empty(); } bool KExiv2::clearExif() const { try { d->exifMetadata().clear(); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot clear Exif data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QByteArray KExiv2::getExifEncoded(bool addExifHeader) const { try { if (!d->exifMetadata().empty()) { QByteArray data; Exiv2::ExifData& exif = d->exifMetadata(); Exiv2::Blob blob; Exiv2::ExifParser::encode(blob, Exiv2::bigEndian, exif); QByteArray ba((const char*)&blob[0], blob.size()); if (addExifHeader) { const uchar ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; data.resize(ba.size() + sizeof(ExifHeader)); memcpy(data.data(), ExifHeader, sizeof(ExifHeader)); memcpy(data.data() + sizeof(ExifHeader), ba.data(), ba.size()); } else { data = ba; } return data; } } catch( Exiv2::Error& e ) { if (!d->filePath.isEmpty()) qCDebug(LIBKEXIV2_LOG) << "From file " << d->filePath.toLatin1().constData(); d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Exif data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QByteArray(); } bool KExiv2::setExif(const QByteArray& data) const { try { if (!data.isEmpty()) { Exiv2::ExifParser::decode(d->exifMetadata(), (const Exiv2::byte*)data.data(), data.size()); return (!d->exifMetadata().empty()); } } catch( Exiv2::Error& e ) { if (!d->filePath.isEmpty()) qCCritical(LIBKEXIV2_LOG) << "From file " << d->filePath.toLatin1().constData(); d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } KExiv2::MetaDataMap KExiv2::getExifTagsDataList(const QStringList& exifKeysFilter, bool invertSelection) const { if (d->exifMetadata().empty()) return MetaDataMap(); try { Exiv2::ExifData exifData = d->exifMetadata(); exifData.sortByKey(); QString ifDItemName; MetaDataMap metaDataMap; for (Exiv2::ExifData::iterator md = exifData.begin(); md != exifData.end(); ++md) { QString key = QString::fromLatin1(md->key().c_str()); // Decode the tag value with a user friendly output. QString tagValue; if (key == QString::fromLatin1("Exif.Photo.UserComment")) { tagValue = d->convertCommentValue(*md); } else if (key == QString::fromLatin1("Exif.Image.0x935c")) { tagValue = QString::number(md->value().size()); } else { std::ostringstream os; os << *md; // Exif tag contents can be an translated strings, no only simple ascii. tagValue = QString::fromLocal8Bit(os.str().c_str()); } tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); // We apply a filter to get only the Exif tags that we need. if (!exifKeysFilter.isEmpty()) { if (!invertSelection) { if (exifKeysFilter.contains(key.section(QString::fromLatin1("."), 1, 1))) metaDataMap.insert(key, tagValue); } else { if (!exifKeysFilter.contains(key.section(QString::fromLatin1("."), 1, 1))) metaDataMap.insert(key, tagValue); } } else // else no filter at all. { metaDataMap.insert(key, tagValue); } } return metaDataMap; } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse EXIF metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return MetaDataMap(); } QString KExiv2::getExifComment() const { try { if (!d->exifMetadata().empty()) { Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifKey key("Exif.Photo.UserComment"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QString exifComment = d->convertCommentValue(*it); // some cameras fill the UserComment with whitespace if (!exifComment.isEmpty() && !exifComment.trimmed().isEmpty()) return exifComment; } Exiv2::ExifKey key2("Exif.Image.ImageDescription"); Exiv2::ExifData::iterator it2 = exifData.findKey(key2); if (it2 != exifData.end()) { QString exifComment = d->convertCommentValue(*it2); // Some cameras fill in nonsense default values QStringList blackList; blackList << QString::fromLatin1("SONY DSC"); // + whitespace blackList << QString::fromLatin1("OLYMPUS DIGITAL CAMERA"); blackList << QString::fromLatin1("MINOLTA DIGITAL CAMERA"); QString trimmedComment = exifComment.trimmed(); // some cameras fill the UserComment with whitespace if (!exifComment.isEmpty() && !trimmedComment.isEmpty() && !blackList.contains(trimmedComment)) return exifComment; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Exif User Comment using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } static bool is7BitAscii(const QString& s) { return std::all_of(s.begin(), s.end(), [](QChar c) { return c.unicode() <= 0x7f; }); } bool KExiv2::setExifComment(const QString& comment, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { removeExifTag("Exif.Image.ImageDescription"); removeExifTag("Exif.Photo.UserComment"); if (!comment.isNull()) { setExifTagString("Exif.Image.ImageDescription", comment, setProgramName); // Write as Unicode only when necessary. if (is7BitAscii(comment)) { // write as ASCII std::string exifComment("charset=\"Ascii\" "); exifComment += comment.toLatin1().constData(); d->exifMetadata()["Exif.Photo.UserComment"] = exifComment; return true; } // write as Unicode (UCS-2) std::string exifComment("charset=\"Unicode\" "); exifComment += comment.toUtf8().constData(); d->exifMetadata()["Exif.Photo.UserComment"] = exifComment; } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif Comment using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QString KExiv2::getExifTagTitle(const char* exifTagName) { try { std::string exifkey(exifTagName); Exiv2::ExifKey ek(exifkey); return QString::fromLocal8Bit( ek.tagLabel().c_str() ); } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get metadata tag title using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } QString KExiv2::getExifTagDescription(const char* exifTagName) { try { std::string exifkey(exifTagName); Exiv2::ExifKey ek(exifkey); return QString::fromLocal8Bit( ek.tagDesc().c_str() ); } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get metadata tag description using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } bool KExiv2::removeExifTag(const char* exifTagName, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { Exiv2::ExifKey exifKey(exifTagName); Exiv2::ExifData::iterator it = d->exifMetadata().findKey(exifKey); if (it != d->exifMetadata().end()) { d->exifMetadata().erase(it); return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot remove Exif tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::getExifTagRational(const char* exifTagName, long int& num, long int& den, int component) const { try { Exiv2::ExifKey exifKey(exifTagName); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey); if (it != exifData.end()) { num = (*it).toRational(component).first; den = (*it).toRational(component).second; return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Exif Rational value from key '%1' into image using Exiv2 ").arg(QString::fromLatin1(exifTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setExifTagLong(const char* exifTagName, long val, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { d->exifMetadata()[exifTagName] = static_cast<int32_t>(val); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif tag long value into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setExifTagRational(const char* exifTagName, long int num, long int den, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { d->exifMetadata()[exifTagName] = Exiv2::Rational(num, den); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif tag rational value into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setExifTagData(const char* exifTagName, const QByteArray& data, bool setProgramName) const { if (data.isEmpty()) return false; if (!setProgramId(setProgramName)) return false; try { Exiv2::DataValue val((Exiv2::byte*)data.data(), data.size()); d->exifMetadata()[exifTagName] = val; return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif tag data into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setExifTagVariant(const char* exifTagName, const QVariant& val, bool rationalWantSmallDenominator, bool setProgramName) const { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) switch (val.metaType().id()) #else switch (val.type()) #endif { case QMetaType::Int: case QMetaType::UInt: case QMetaType::Bool: case QMetaType::LongLong: case QMetaType::ULongLong: return setExifTagLong(exifTagName, val.toInt(), setProgramName); case QMetaType::Double: { long num, den; if (rationalWantSmallDenominator) convertToRationalSmallDenominator(val.toDouble(), &num, &den); else convertToRational(val.toDouble(), &num, &den, 4); return setExifTagRational(exifTagName, num, den, setProgramName); } case QMetaType::QVariantList: { long num = 0, den = 1; QList<QVariant> list = val.toList(); if (list.size() >= 1) num = list[0].toInt(); if (list.size() >= 2) den = list[1].toInt(); return setExifTagRational(exifTagName, num, den, setProgramName); } case QMetaType::QDate: case QMetaType::QDateTime: { QDateTime dateTime = val.toDateTime(); if(!dateTime.isValid()) return false; if (!setProgramId(setProgramName)) return false; try { const std::string &exifdatetime(dateTime.toString(QString::fromLatin1("yyyy:MM:dd hh:mm:ss")).toLatin1().constData()); d->exifMetadata()[exifTagName] = exifdatetime; } catch( Exiv2::Error &e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Date & Time in image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } case QMetaType::QString: case QMetaType::QChar: return setExifTagString(exifTagName, val.toString(), setProgramName); case QMetaType::QByteArray: return setExifTagData(exifTagName, val.toByteArray(), setProgramName); default: break; } return false; } QString KExiv2::createExifUserStringFromValue(const char* exifTagName, const QVariant& val, bool escapeCR) { try { Exiv2::ExifKey key(exifTagName); Exiv2::Exifdatum datum(key); #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) switch (val.metaType().id()) #else switch (val.type()) #endif { case QMetaType::Int: case QMetaType::Bool: case QMetaType::LongLong: case QMetaType::ULongLong: datum = (int32_t)val.toInt(); break; case QMetaType::UInt: datum = (uint32_t)val.toUInt(); break; case QMetaType::Double: { long num, den; convertToRationalSmallDenominator(val.toDouble(), &num, &den); Exiv2::Rational rational; rational.first = num; rational.second = den; datum = rational; break; } case QMetaType::QVariantList: { long num = 0, den = 1; QList<QVariant> list = val.toList(); if (list.size() >= 1) num = list[0].toInt(); if (list.size() >= 2) den = list[1].toInt(); Exiv2::Rational rational; rational.first = num; rational.second = den; datum = rational; break; } case QMetaType::QDate: case QMetaType::QDateTime: { QDateTime dateTime = val.toDateTime(); if(!dateTime.isValid()) break; const std::string &exifdatetime(dateTime.toString(QString::fromLatin1("yyyy:MM:dd hh:mm:ss")).toLatin1().constData()); datum = exifdatetime; break; } case QMetaType::QString: case QMetaType::QChar: datum = (std::string)val.toString().toLatin1().constData(); break; default: break; } std::ostringstream os; os << datum; QString tagValue = QString::fromLocal8Bit(os.str().c_str()); if (escapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return tagValue; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc tag string into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } bool KExiv2::getExifTagLong(const char* exifTagName, long& val) const { return getExifTagLong(exifTagName, val, 0); } bool KExiv2::getExifTagLong(const char* exifTagName, long& val, int component) const { try { Exiv2::ExifKey exifKey(exifTagName); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey); if (it != exifData.end() && it->count() > 0) { #if EXIV2_TEST_VERSION(0,28,0) val = it->toUint32(component); #else val = it->toLong(component); #endif return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Exif key '%1' into image using Exiv2 ").arg(QString::fromLatin1(exifTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QByteArray KExiv2::getExifTagData(const char* exifTagName) const { try { Exiv2::ExifKey exifKey(exifTagName); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey); if (it != exifData.end()) { char* const s = new char[(*it).size()]; (*it).copy((Exiv2::byte*)s, Exiv2::bigEndian); QByteArray data(s, (*it).size()); delete[] s; return data; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Exif key '%1' into image using Exiv2 ").arg(QString::fromLatin1(exifTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QByteArray(); } QVariant KExiv2::getExifTagVariant(const char* exifTagName, bool rationalAsListOfInts, bool stringEscapeCR, int component) const { try { Exiv2::ExifKey exifKey(exifTagName); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey); if (it != exifData.end()) { switch (it->typeId()) { case Exiv2::unsignedByte: case Exiv2::unsignedShort: case Exiv2::unsignedLong: case Exiv2::signedShort: case Exiv2::signedLong: if (it->count() > component) #if EXIV2_TEST_VERSION(0,28,0) return QVariant((int)it->toUint32(component)); #else return QVariant((int)it->toLong(component)); #endif else #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) return QVariant(QMetaType(QMetaType::Int)); #else return QVariant(QVariant::Int); #endif case Exiv2::unsignedRational: case Exiv2::signedRational: if (rationalAsListOfInts) { if (it->count() <= component) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) return QVariant(QMetaType(QMetaType::QVariantList)); #else return QVariant(QVariant::List); #endif QList<QVariant> list; list << (*it).toRational(component).first; list << (*it).toRational(component).second; return QVariant(list); } else { if (it->count() <= component) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) return QVariant(QMetaType(QMetaType::Double)); #else return QVariant(QVariant::Double); #endif // prefer double precision double num = (*it).toRational(component).first; double den = (*it).toRational(component).second; if (den == 0.0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) return QVariant(QMetaType(QMetaType::Double)); #else return QVariant(QVariant::Double); #endif return QVariant(num / den); } case Exiv2::date: case Exiv2::time: { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); return QVariant(dateTime); } case Exiv2::asciiString: case Exiv2::comment: case Exiv2::string: { std::ostringstream os; os << *it; QString tagValue = QString::fromLocal8Bit(os.str().c_str()); if (stringEscapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return QVariant(tagValue); } default: break; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Exif key '%1' in the image using Exiv2 ").arg(QString::fromLatin1(exifTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QVariant(); } QString KExiv2::getExifTagString(const char* exifTagName, bool escapeCR) const { try { Exiv2::ExifKey exifKey(exifTagName); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey); if (it != exifData.end()) { // See B.K.O #184156 comment #13 std::string val = it->print(&exifData); QString tagValue = QString::fromLocal8Bit(val.c_str()); if (escapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return tagValue; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Exif key '%1' into image using Exiv2 ").arg(QString::fromLatin1(exifTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } bool KExiv2::setExifTagString(const char* exifTagName, const QString& value, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { d->exifMetadata()[exifTagName] = std::string(value.toLatin1().constData()); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif tag string into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QImage KExiv2::getExifThumbnail(bool fixOrientation) const { QImage thumbnail; if (d->exifMetadata().empty()) return thumbnail; try { Exiv2::ExifThumbC thumb(d->exifMetadata()); Exiv2::DataBuf const c1 = thumb.copy(); #if EXIV2_TEST_VERSION(0,28,0) thumbnail.loadFromData(c1.c_data(), c1.size()); #else thumbnail.loadFromData(c1.pData_, c1.size_); #endif if (!thumbnail.isNull()) { if (fixOrientation) { Exiv2::ExifKey key1("Exif.Thumbnail.Orientation"); Exiv2::ExifKey key2("Exif.Image.Orientation"); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(key1); if (it == exifData.end()) it = exifData.findKey(key2); if (it != exifData.end() && it->count()) { #if EXIV2_TEST_VERSION(0,28,0) long orientation = it->toUint32(); #else long orientation = it->toLong(); #endif qCDebug(LIBKEXIV2_LOG) << "Exif Thumbnail Orientation: " << (int)orientation; rotateExifQImage(thumbnail, (ImageOrientation)orientation); } return thumbnail; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Exif Thumbnail using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return thumbnail; } bool KExiv2::rotateExifQImage(QImage& image, ImageOrientation orientation) const { QTransform matrix = RotationMatrix::toTransform(orientation); if ((orientation != ORIENTATION_NORMAL) && (orientation != ORIENTATION_UNSPECIFIED)) { image = image.transformed(matrix); return true; } return false; } bool KExiv2::setExifThumbnail(const QImage& thumbImage, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; if (thumbImage.isNull()) { return removeExifThumbnail(); } try { QByteArray data; QBuffer buffer(&data); buffer.open(QIODevice::WriteOnly); thumbImage.save(&buffer, "JPEG"); Exiv2::ExifThumb thumb(d->exifMetadata()); thumb.setJpegThumbnail((Exiv2::byte *)data.data(), data.size()); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif Thumbnail using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setTiffThumbnail(const QImage& thumbImage, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; removeExifThumbnail(); try { // Make sure IFD0 is explicitly marked as a main image Exiv2::ExifData::const_iterator pos = d->exifMetadata().findKey(Exiv2::ExifKey("Exif.Image.NewSubfileType")); #if EXIV2_TEST_VERSION(0,28,0) if (pos == d->exifMetadata().end() || pos->count() != 1 || pos->toUint32() != 0) #else if (pos == d->exifMetadata().end() || pos->count() != 1 || pos->toLong() != 0) #endif { #if EXIV2_TEST_VERSION(0,28,0) throw Exiv2::Error(Exiv2::ErrorCode::kerErrorMessage, "Exif.Image.NewSubfileType missing or not set as main image"); #elif EXIV2_TEST_VERSION(0,27,0) throw Exiv2::Error(Exiv2::kerErrorMessage, "Exif.Image.NewSubfileType missing or not set as main image"); #else throw Exiv2::Error(1, "Exif.Image.NewSubfileType missing or not set as main image"); #endif } // Remove sub-IFD tags std::string subImage1("SubImage1"); for (Exiv2::ExifData::iterator md = d->exifMetadata().begin(); md != d->exifMetadata().end();) { if (md->groupName() == subImage1) md = d->exifMetadata().erase(md); else ++md; } if (!thumbImage.isNull()) { // Set thumbnail tags QByteArray data; QBuffer buffer(&data); buffer.open(QIODevice::WriteOnly); thumbImage.save(&buffer, "JPEG"); Exiv2::DataBuf buf((Exiv2::byte *)data.data(), data.size()); Exiv2::ULongValue val; val.read("0"); #if EXIV2_TEST_VERSION(0,28,0) val.setDataArea(buf.c_data(), buf.size()); #else val.setDataArea(buf.pData_, buf.size_); #endif d->exifMetadata()["Exif.SubImage1.JPEGInterchangeFormat"] = val; #if EXIV2_TEST_VERSION(0,28,0) d->exifMetadata()["Exif.SubImage1.JPEGInterchangeFormatLength"] = uint32_t(buf.size()); #else d->exifMetadata()["Exif.SubImage1.JPEGInterchangeFormatLength"] = uint32_t(buf.size_); #endif d->exifMetadata()["Exif.SubImage1.Compression"] = uint16_t(6); // JPEG (old-style) d->exifMetadata()["Exif.SubImage1.NewSubfileType"] = uint32_t(1); // Thumbnail image return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set TIFF Thumbnail using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::removeExifThumbnail() const { try { // Remove all IFD0 subimages. Exiv2::ExifThumb thumb(d->exifMetadata()); thumb.erase(); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot remove Exif Thumbnail using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } KExiv2::TagsMap KExiv2::getStdExifTagsList() const { try { QList<const Exiv2::TagInfo*> tags; TagsMap tagsMap; const Exiv2::GroupInfo* gi = Exiv2::ExifTags::groupList(); while (gi->tagList_ != nullptr) { if (QString::fromLatin1(gi->ifdName_) != QString::fromLatin1("Makernote")) { Exiv2::TagListFct tl = gi->tagList_; const Exiv2::TagInfo* ti = tl(); while (ti->tag_ != 0xFFFF) { tags << ti; ++ti; } } ++gi; } for (QList<const Exiv2::TagInfo*>::iterator it = tags.begin(); it != tags.end(); ++it) { do { const Exiv2::TagInfo* const ti = *it; QString key = QLatin1String(Exiv2::ExifKey(*ti).key().c_str()); QStringList values; values << QString::fromLatin1(ti->name_) << QString::fromLatin1(ti->title_) << QString::fromLatin1(ti->desc_); tagsMap.insert(key, values); ++(*it); } while((*it)->tag_ != 0xffff); } return tagsMap; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Exif Tags list using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return TagsMap(); } KExiv2::TagsMap KExiv2::getMakernoteTagsList() const { try { QList<const Exiv2::TagInfo*> tags; TagsMap tagsMap; const Exiv2::GroupInfo* gi = Exiv2::ExifTags::groupList(); while (gi->tagList_ != nullptr) { if (QString::fromLatin1(gi->ifdName_) == QString::fromLatin1("Makernote")) { Exiv2::TagListFct tl = gi->tagList_; const Exiv2::TagInfo* ti = tl(); while (ti->tag_ != 0xFFFF) { tags << ti; ++ti; } } ++gi; } for (QList<const Exiv2::TagInfo*>::iterator it = tags.begin(); it != tags.end(); ++it) { do { const Exiv2::TagInfo* const ti = *it; QString key = QLatin1String(Exiv2::ExifKey(*ti).key().c_str()); QStringList values; values << QString::fromLatin1(ti->name_) << QString::fromLatin1(ti->title_) << QString::fromLatin1(ti->desc_); tagsMap.insert(key, values); ++(*it); } while((*it)->tag_ != 0xffff); } return tagsMap; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Makernote Tags list using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return TagsMap(); } } // NameSpace KExiv2Iface 0707010000001B000081A40000000000000000000000016627958500007B7F000000000000000000000000000000000000003F00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2gps.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-FileCopyrightText: 2010-2012 Michael G. Hansen <mike at mghansen dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #include "kexiv2.h" #include "kexiv2_p.h" // C ANSI includes #include <math.h> // C++ includes #include <climits> #include <cmath> // Local includes #include "libkexiv2_debug.h" namespace KExiv2Iface { bool KExiv2::getGPSInfo(double& altitude, double& latitude, double& longitude) const { // Some GPS device do not set Altitude. So a valid GPS position can be with a zero value. // No need to check return value. getGPSAltitude(&altitude); if (!getGPSLatitudeNumber(&latitude)) return false; if (!getGPSLongitudeNumber(&longitude)) return false; return true; } bool KExiv2::getGPSLatitudeNumber(double* const latitude) const { try { *latitude=0.0; // Try XMP first. Reason: XMP in sidecar may be more up-to-date than EXIF in original image. if ( convertFromGPSCoordinateString(getXmpTagString("Xmp.exif.GPSLatitude"), latitude) ) return true; // Now try to get the reference from Exif. const QByteArray latRef = getExifTagData("Exif.GPSInfo.GPSLatitudeRef"); if (!latRef.isEmpty()) { Exiv2::ExifKey exifKey("Exif.GPSInfo.GPSLatitude"); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey); if (it != exifData.end() && (*it).count() == 3) { // Latitude decoding from Exif. double num, den, min, sec; num = (double)((*it).toRational(0).first); den = (double)((*it).toRational(0).second); if (den == 0) return false; *latitude = num/den; num = (double)((*it).toRational(1).first); den = (double)((*it).toRational(1).second); if (den == 0) return false; min = num/den; if (min != -1.0) *latitude = *latitude + min/60.0; num = (double)((*it).toRational(2).first); den = (double)((*it).toRational(2).second); if (den == 0) { // be relaxed and accept 0/0 seconds. See #246077. if (num == 0) den = 1; else return false; } sec = num/den; if (sec != -1.0) *latitude = *latitude + sec/3600.0; } else { return false; } if (latRef[0] == 'S') *latitude *= -1.0; return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get GPS tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::getGPSLongitudeNumber(double* const longitude) const { try { *longitude=0.0; // Try XMP first. Reason: XMP in sidecar may be more up-to-date than EXIF in original image. if ( convertFromGPSCoordinateString(getXmpTagString("Xmp.exif.GPSLongitude"), longitude) ) return true; // Now try to get the reference from Exif. const QByteArray lngRef = getExifTagData("Exif.GPSInfo.GPSLongitudeRef"); if (!lngRef.isEmpty()) { // Longitude decoding from Exif. Exiv2::ExifKey exifKey2("Exif.GPSInfo.GPSLongitude"); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey2); if (it != exifData.end() && (*it).count() == 3) { /// @todo Decoding of latitude and longitude works in the same way, /// code here can be put in a separate function double num, den; num = (double)((*it).toRational(0).first); den = (double)((*it).toRational(0).second); if (den == 0) { return false; } *longitude = num/den; num = (double)((*it).toRational(1).first); den = (double)((*it).toRational(1).second); if (den == 0) { return false; } const double min = num/den; if (min != -1.0) { *longitude = *longitude + min/60.0; } num = (double)((*it).toRational(2).first); den = (double)((*it).toRational(2).second); if (den == 0) { // be relaxed and accept 0/0 seconds. See #246077. if (num == 0) den = 1; else return false; } const double sec = num/den; if (sec != -1.0) { *longitude = *longitude + sec/3600.0; } } else { return false; } if (lngRef[0] == 'W') { *longitude *= -1.0; } return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get GPS tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::getGPSAltitude(double* const altitude) const { try { double num, den; *altitude=0.0; // Try XMP first. Reason: XMP in sidecar may be more up-to-date than EXIF in original image. const QString altRefXmp = getXmpTagString("Xmp.exif.GPSAltitudeRef"); if (!altRefXmp.isEmpty()) { const QString altXmp = getXmpTagString("Xmp.exif.GPSAltitude"); if (!altXmp.isEmpty()) { num = altXmp.section(QString::fromLatin1("/"), 0, 0).toDouble(); den = altXmp.section(QString::fromLatin1("/"), 1, 1).toDouble(); if (den == 0) return false; *altitude = num/den; if (altRefXmp == QString::fromLatin1("1")) *altitude *= -1.0; return true; } } // Get the reference from Exif (above/below sea level) const QByteArray altRef = getExifTagData("Exif.GPSInfo.GPSAltitudeRef"); if (!altRef.isEmpty()) { // Altitude decoding from Exif. Exiv2::ExifKey exifKey3("Exif.GPSInfo.GPSAltitude"); Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it = exifData.findKey(exifKey3); if (it != exifData.end() && (*it).count()) { num = (double)((*it).toRational(0).first); den = (double)((*it).toRational(0).second); if (den == 0) return false; *altitude = num/den; } else { return false; } if (altRef[0] == '1') *altitude *= -1.0; return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get GPS tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QString KExiv2::getGPSLatitudeString() const { double latitude; if (!getGPSLatitudeNumber(&latitude)) return QString(); return convertToGPSCoordinateString(true, latitude); } QString KExiv2::getGPSLongitudeString() const { double longitude; if (!getGPSLongitudeNumber(&longitude)) return QString(); return convertToGPSCoordinateString(false, longitude); } bool KExiv2::initializeGPSInfo(const bool setProgramName) { if (!setProgramId(setProgramName)) return false; try { // TODO: what happens if these already exist? // Do all the easy constant ones first. // GPSVersionID tag: standard says is should be four bytes: 02 00 00 00 // (and, must be present). #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr value = Exiv2::Value::create(Exiv2::unsignedByte); #else Exiv2::Value::AutoPtr value = Exiv2::Value::create(Exiv2::unsignedByte); #endif value->read("2 0 0 0"); d->exifMetadata().add(Exiv2::ExifKey("Exif.GPSInfo.GPSVersionID"), value.get()); // Datum: the datum of the measured data. If not given, we insert WGS-84. d->exifMetadata()["Exif.GPSInfo.GPSMapDatum"] = "WGS-84"; #ifdef _XMP_SUPPORT_ setXmpTagString("Xmp.exif.GPSVersionID", QString::fromLatin1("2.0.0.0"), false); setXmpTagString("Xmp.exif.GPSMapDatum", QString::fromLatin1("WGS-84"), false); #endif // _XMP_SUPPORT_ return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot initialize GPS data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setGPSInfo(const double altitude, const double latitude, const double longitude, const bool setProgramName) { return setGPSInfo(&altitude, latitude, longitude, setProgramName); } bool KExiv2::setGPSInfo(const double* const altitude, const double latitude, const double longitude, const bool setProgramName) { if (!setProgramId(setProgramName)) return false; try { // In first, we need to clean up all existing GPS info. removeGPSInfo(); // now re-initialize the GPS info: if (!initializeGPSInfo(setProgramName)) return false; char scratchBuf[100]; long int nom, denom; long int deg, min; // Now start adding data. // ALTITUDE. if (altitude) { // Altitude reference: byte "00" meaning "above sea level", "01" mening "behing sea level". #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr value = Exiv2::Value::create(Exiv2::unsignedByte); #else Exiv2::Value::AutoPtr value = Exiv2::Value::create(Exiv2::unsignedByte); #endif if ((*altitude) >= 0) value->read("0"); else value->read("1"); d->exifMetadata().add(Exiv2::ExifKey("Exif.GPSInfo.GPSAltitudeRef"), value.get()); // And the actual altitude, as absolute value.. convertToRational(fabs(*altitude), &nom, &denom, 4); snprintf(scratchBuf, 100, "%ld/%ld", nom, denom); d->exifMetadata()["Exif.GPSInfo.GPSAltitude"] = scratchBuf; #ifdef _XMP_SUPPORT_ setXmpTagString("Xmp.exif.GPSAltitudeRef", ((*altitude) >= 0) ? QString::fromLatin1("0") : QString::fromLatin1("1"), false); setXmpTagString("Xmp.exif.GPSAltitude", QString::fromLatin1(scratchBuf), false); #endif // _XMP_SUPPORT_ } // LATITUDE // Latitude reference: // latitude < 0 : "S" // latitude > 0 : "N" // d->exifMetadata()["Exif.GPSInfo.GPSLatitudeRef"] = (latitude < 0 ) ? "S" : "N"; // Now the actual latitude itself. // This is done as three rationals. // I choose to do it as: // dd/1 - degrees. // mmmm/100 - minutes // 0/1 - seconds // Exif standard says you can do it with minutes // as mm/1 and then seconds as ss/1, but its // (slightly) more accurate to do it as // mmmm/100 than to split it. // We also absolute the value (with fabs()) // as the sign is encoded in LatRef. // Further note: original code did not translate between // dd.dddddd to dd mm.mm - that's why we now multiply // by 6000 - x60 to get minutes, x1000000 to get to mmmm/1000000. deg = (int)floor(fabs(latitude)); // Slice off after decimal. min = (int)floor((fabs(latitude) - floor(fabs(latitude))) * 60000000); snprintf(scratchBuf, 100, "%ld/1 %ld/1000000 0/1", deg, min); d->exifMetadata()["Exif.GPSInfo.GPSLatitude"] = scratchBuf; #ifdef _XMP_SUPPORT_ /** @todo The XMP spec does not mention Xmp.exif.GPSLatitudeRef, * because the reference is included in Xmp.exif.GPSLatitude. * Is there a historic reason for writing it anyway? */ setXmpTagString("Xmp.exif.GPSLatitudeRef", (latitude < 0) ? QString::fromLatin1("S") : QString::fromLatin1("N"), false); setXmpTagString("Xmp.exif.GPSLatitude", convertToGPSCoordinateString(true, latitude), false); #endif // _XMP_SUPPORT_ // LONGITUDE // Longitude reference: // longitude < 0 : "W" // longitude > 0 : "E" d->exifMetadata()["Exif.GPSInfo.GPSLongitudeRef"] = (longitude < 0 ) ? "W" : "E"; // Now the actual longitude itself. // This is done as three rationals. // I choose to do it as: // dd/1 - degrees. // mmmm/100 - minutes // 0/1 - seconds // Exif standard says you can do it with minutes // as mm/1 and then seconds as ss/1, but its // (slightly) more accurate to do it as // mmmm/100 than to split it. // We also absolute the value (with fabs()) // as the sign is encoded in LongRef. // Further note: original code did not translate between // dd.dddddd to dd mm.mm - that's why we now multiply // by 6000 - x60 to get minutes, x1000000 to get to mmmm/1000000. deg = (int)floor(fabs(longitude)); // Slice off after decimal. min = (int)floor((fabs(longitude) - floor(fabs(longitude))) * 60000000); snprintf(scratchBuf, 100, "%ld/1 %ld/1000000 0/1", deg, min); d->exifMetadata()["Exif.GPSInfo.GPSLongitude"] = scratchBuf; #ifdef _XMP_SUPPORT_ /** @todo The XMP spec does not mention Xmp.exif.GPSLongitudeRef, * because the reference is included in Xmp.exif.GPSLongitude. * Is there a historic reason for writing it anyway? */ setXmpTagString("Xmp.exif.GPSLongitudeRef", (longitude < 0) ? QString::fromLatin1("W") : QString::fromLatin1("E"), false); setXmpTagString("Xmp.exif.GPSLongitude", convertToGPSCoordinateString(false, longitude), false); #endif // _XMP_SUPPORT_ return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif GPS tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setGPSInfo(const double altitude, const QString& latitude, const QString& longitude, const bool setProgramName) { double longitudeValue, latitudeValue; if (!convertFromGPSCoordinateString(latitude, &latitudeValue)) return false; if (!convertFromGPSCoordinateString(longitude, &longitudeValue)) return false; return setGPSInfo(&altitude, latitudeValue, longitudeValue, setProgramName); } bool KExiv2::removeGPSInfo(const bool setProgramName) { if (!setProgramId(setProgramName)) return false; try { QStringList gpsTagsKeys; for (Exiv2::ExifData::iterator it = d->exifMetadata().begin(); it != d->exifMetadata().end(); ++it) { QString key = QString::fromLocal8Bit(it->key().c_str()); if (key.section(QString::fromLatin1("."), 1, 1) == QString::fromLatin1("GPSInfo")) gpsTagsKeys.append(key); } for(QStringList::const_iterator it2 = gpsTagsKeys.constBegin(); it2 != gpsTagsKeys.constEnd(); ++it2) { Exiv2::ExifKey gpsKey((*it2).toLatin1().constData()); Exiv2::ExifData::iterator it3 = d->exifMetadata().findKey(gpsKey); if (it3 != d->exifMetadata().end()) d->exifMetadata().erase(it3); } #ifdef _XMP_SUPPORT_ /** @todo The XMP spec does not mention Xmp.exif.GPSLongitudeRef, * and Xmp.exif.GPSLatitudeRef. But because we write them in setGPSInfo(), * we should also remove them here. */ removeXmpTag("Xmp.exif.GPSLatitudeRef", false); removeXmpTag("Xmp.exif.GPSLongitudeRef", false); removeXmpTag("Xmp.exif.GPSVersionID", false); removeXmpTag("Xmp.exif.GPSLatitude", false); removeXmpTag("Xmp.exif.GPSLongitude", false); removeXmpTag("Xmp.exif.GPSAltitudeRef", false); removeXmpTag("Xmp.exif.GPSAltitude", false); removeXmpTag("Xmp.exif.GPSTimeStamp", false); removeXmpTag("Xmp.exif.GPSSatellites", false); removeXmpTag("Xmp.exif.GPSStatus", false); removeXmpTag("Xmp.exif.GPSMeasureMode", false); removeXmpTag("Xmp.exif.GPSDOP", false); removeXmpTag("Xmp.exif.GPSSpeedRef", false); removeXmpTag("Xmp.exif.GPSSpeed", false); removeXmpTag("Xmp.exif.GPSTrackRef", false); removeXmpTag("Xmp.exif.GPSTrack", false); removeXmpTag("Xmp.exif.GPSImgDirectionRef", false); removeXmpTag("Xmp.exif.GPSImgDirection", false); removeXmpTag("Xmp.exif.GPSMapDatum", false); removeXmpTag("Xmp.exif.GPSDestLatitude", false); removeXmpTag("Xmp.exif.GPSDestLongitude", false); removeXmpTag("Xmp.exif.GPSDestBearingRef", false); removeXmpTag("Xmp.exif.GPSDestBearing", false); removeXmpTag("Xmp.exif.GPSDestDistanceRef", false); removeXmpTag("Xmp.exif.GPSDestDistance", false); removeXmpTag("Xmp.exif.GPSProcessingMethod", false); removeXmpTag("Xmp.exif.GPSAreaInformation", false); removeXmpTag("Xmp.exif.GPSDifferential", false); #endif // _XMP_SUPPORT_ return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot remove Exif GPS tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } void KExiv2::convertToRational(const double number, long int* const numerator, long int* const denominator, const int rounding) { // This function converts the given decimal number // to a rational (fractional) number. // // Examples in comments use Number as 25.12345, Rounding as 4. // Split up the number. double whole = trunc(number); double fractional = number - whole; // Calculate the "number" used for rounding. // This is 10^Digits - ie, 4 places gives us 10000. double rounder = pow(10.0, rounding); // Round the fractional part, and leave the number // as greater than 1. // To do this we: (for example) // 0.12345 * 10000 = 1234.5 // floor(1234.5) = 1234 - now bigger than 1 - ready... fractional = round(fractional * rounder); // Convert the whole thing to a fraction. // Fraction is: // (25 * 10000) + 1234 251234 // ------------------- = ------ = 25.1234 // 10000 10000 double numTemp = (whole * rounder) + fractional; double denTemp = rounder; // Now we should reduce until we can reduce no more. // Try simple reduction... // if Num // ----- = integer out then.... // Den if (trunc(numTemp / denTemp) == (numTemp / denTemp)) { // Divide both by Denominator. numTemp /= denTemp; denTemp /= denTemp; } // And, if that fails, brute force it. while (1) { // Jump out if we can't integer divide one. if ((numTemp / 2) != trunc(numTemp / 2)) break; if ((denTemp / 2) != trunc(denTemp / 2)) break; // Otherwise, divide away. numTemp /= 2; denTemp /= 2; } // Copy out the numbers. *numerator = (int)numTemp; *denominator = (int)denTemp; } void KExiv2::convertToRationalSmallDenominator(const double number, long int* const numerator, long int* const denominator) { // This function converts the given decimal number // to a rational (fractional) number. // // This method, in contrast to the method above, will retrieve the smallest possible // denominator. It is tested to retrieve the correct value for 1/x, with 0 < x <= 1000000. // Note: This requires double precision, storing in float breaks some numbers (49, 59, 86,...) // Split up the number. double whole = trunc(number); double fractional = number - whole; /* * Find best rational approximation to a double * by C.B. Falconer, 2006-09-07. Released to public domain. * * Newsgroups: comp.lang.c, comp.programming * From: CBFalconer <cbfalconer@yahoo.com> * Date: Thu, 07 Sep 2006 17:35:30 -0400 * Subject: Rational approximations */ int lastnum = 500; // this is _not_ the largest possible denominator long int num, approx, bestnum=0, bestdenom=1; double value, error, leasterr, criterion; value = fractional; if (value == 0.0) { *numerator = (long int)whole; *denominator = 1; return; } criterion = 2 * value * DBL_EPSILON; for (leasterr = value, num = 1; num < lastnum; ++num) { approx = (int)(num / value + 0.5); error = fabs((double)num / approx - value); if (error < leasterr) { bestnum = num; bestdenom = approx; leasterr = error; if (leasterr <= criterion) break; } } // add whole number part if (bestdenom * whole > (double)INT_MAX) { // In some cases, we would generate an integer overflow. // Fall back to Gilles's code which is better suited for such numbers. convertToRational(number, numerator, denominator, 5); } else { bestnum += bestdenom * (long int)whole; *numerator = bestnum; *denominator = bestdenom; } } QString KExiv2::convertToGPSCoordinateString(const long int numeratorDegrees, const long int denominatorDegrees, const long int numeratorMinutes, const long int denominatorMinutes, const long int numeratorSeconds, long int denominatorSeconds, const char directionReference) { /** * Precision: * A second at sea level measures 30m for our purposes, a minute 1800m. * (for more details, see https://en.wikipedia.org/wiki/Geographic_coordinate_system) * This means with a decimal precision of 8 for minutes we get +/-0,018mm. * (if I calculated correctly) */ QString coordinate; // be relaxed with seconds of 0/0 if (denominatorSeconds == 0 && numeratorSeconds == 0) denominatorSeconds = 1; if (denominatorDegrees == 1 && denominatorMinutes == 1 && denominatorSeconds == 1) { // use form DDD,MM,SSk coordinate = QString::fromLatin1("%1,%2,%3%4"); coordinate = coordinate.arg(numeratorDegrees).arg(numeratorMinutes).arg(numeratorSeconds).arg(directionReference); } else if (denominatorDegrees == 1 && denominatorMinutes == 100 && denominatorSeconds == 1) { // use form DDD,MM.mmk coordinate = QString::fromLatin1("%1,%2%3"); double minutes = (double)numeratorMinutes / (double)denominatorMinutes; minutes += (double)numeratorSeconds / 60.0; QString minutesString = QString::number(minutes, 'f', 8); while (minutesString.endsWith(QString::fromLatin1("0")) && !minutesString.endsWith(QString::fromLatin1(".0"))) { minutesString.chop(1); } coordinate = coordinate.arg(numeratorDegrees).arg(minutesString).arg(directionReference); } else if (denominatorDegrees == 0 || denominatorMinutes == 0 || denominatorSeconds == 0) { // Invalid. 1/0 is everything but 0. As is 0/0. return QString(); } else { // use form DDD,MM.mmk coordinate = QString::fromLatin1("%1,%2%3"); double degrees = (double)numeratorDegrees / (double)denominatorDegrees; double wholeDegrees = trunc(degrees); double minutes = (double)numeratorMinutes / (double)denominatorMinutes; minutes += (degrees - wholeDegrees) * 60.0; minutes += ((double)numeratorSeconds / (double)denominatorSeconds) / 60.0; QString minutesString = QString::number(minutes, 'f', 8); while (minutesString.endsWith(QString::fromLatin1("0")) && !minutesString.endsWith(QString::fromLatin1(".0"))) { minutesString.chop(1); } coordinate = coordinate.arg((int)wholeDegrees).arg(minutesString).arg(directionReference); } return coordinate; } QString KExiv2::convertToGPSCoordinateString(const bool isLatitude, double coordinate) { if (coordinate < -360.0 || coordinate > 360.0) return QString(); QString coordinateString; char directionReference; if (isLatitude) { if (coordinate < 0) directionReference = 'S'; else directionReference = 'N'; } else { if (coordinate < 0) directionReference = 'W'; else directionReference = 'E'; } // remove sign coordinate = fabs(coordinate); int degrees = (int)floor(coordinate); // get fractional part coordinate = coordinate - (double)(degrees); // To minutes double minutes = coordinate * 60.0; // use form DDD,MM.mmk coordinateString = QString::fromLatin1("%1,%2%3"); coordinateString = coordinateString.arg(degrees); coordinateString = coordinateString.arg(minutes, 0, 'f', 8).arg(directionReference); return coordinateString; } bool KExiv2::convertFromGPSCoordinateString(const QString& gpsString, long int* const numeratorDegrees, long int* const denominatorDegrees, long int* const numeratorMinutes, long int* const denominatorMinutes, long int* const numeratorSeconds, long int* const denominatorSeconds, char* const directionReference) { if (gpsString.isEmpty()) return false; *directionReference = gpsString.at(gpsString.length() - 1).toUpper().toLatin1(); QString coordinate = gpsString.left(gpsString.length() - 1); QStringList parts = coordinate.split(QString::fromLatin1(",")); if (parts.size() == 2) { // form DDD,MM.mmk *denominatorDegrees = 1; *denominatorMinutes = 1000000; *denominatorSeconds = 1; *numeratorDegrees = parts[0].toLong(); double minutes = parts[1].toDouble(); minutes *= 1000000; *numeratorMinutes = (long)round(minutes); *numeratorSeconds = 0; return true; } else if (parts.size() == 3) { // use form DDD,MM,SSk *denominatorDegrees = 1; *denominatorMinutes = 1; *denominatorSeconds = 1; *numeratorDegrees = parts[0].toLong(); *numeratorMinutes = parts[1].toLong(); *numeratorSeconds = parts[2].toLong(); return true; } else { return false; } } bool KExiv2::convertFromGPSCoordinateString(const QString& gpsString, double* const degrees) { if (gpsString.isEmpty()) return false; char directionReference = gpsString.at(gpsString.length() - 1).toUpper().toLatin1(); QString coordinate = gpsString.left(gpsString.length() - 1); QStringList parts = coordinate.split(QString::fromLatin1(",")); if (parts.size() == 2) { // form DDD,MM.mmk *degrees = parts[0].toLong(); *degrees += parts[1].toDouble() / 60.0; if (directionReference == 'W' || directionReference == 'S') *degrees *= -1.0; return true; } else if (parts.size() == 3) { // use form DDD,MM,SSk *degrees = parts[0].toLong(); *degrees += parts[1].toLong() / 60.0; *degrees += parts[2].toLong() / 3600.0; if (directionReference == 'W' || directionReference == 'S') *degrees *= -1.0; return true; } else { return false; } } bool KExiv2::convertToUserPresentableNumbers(const QString& gpsString, int* const degrees, int* const minutes, double* const seconds, char* const directionReference) { if (gpsString.isEmpty()) return false; *directionReference = gpsString.at(gpsString.length() - 1).toUpper().toLatin1(); QString coordinate = gpsString.left(gpsString.length() - 1); QStringList parts = coordinate.split(QString::fromLatin1(",")); if (parts.size() == 2) { // form DDD,MM.mmk *degrees = parts[0].toInt(); double fractionalMinutes = parts[1].toDouble(); *minutes = (int)trunc(fractionalMinutes); *seconds = (fractionalMinutes - (double)(*minutes)) * 60.0; return true; } else if (parts.size() == 3) { // use form DDD,MM,SSk *degrees = parts[0].toInt(); *minutes = parts[1].toInt(); *seconds = (double)parts[2].toInt(); return true; } else { return false; } } void KExiv2::convertToUserPresentableNumbers(const bool isLatitude, double coordinate, int* const degrees, int* const minutes, double* const seconds, char* const directionReference) { if (isLatitude) { if (coordinate < 0) *directionReference = 'S'; else *directionReference = 'N'; } else { if (coordinate < 0) *directionReference = 'W'; else *directionReference = 'E'; } // remove sign coordinate = fabs(coordinate); *degrees = (int)floor(coordinate); // get fractional part coordinate = coordinate - (double)(*degrees); // To minutes coordinate *= 60.0; *minutes = (int)floor(coordinate); // get fractional part coordinate = coordinate - (double)(*minutes); // To seconds coordinate *= 60.0; *seconds = coordinate; } } // NameSpace KExiv2Iface 0707010000001C000081A400000000000000000000000166279585000091D2000000000000000000000000000000000000004100000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2image.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #include "kexiv2.h" #include "kexiv2_p.h" // Qt includes #include <QBuffer> // Local includes #include "rotationmatrix.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { bool KExiv2::setImageProgramId(const QString& program, const QString& version) const { try { QString software(program); software.append(QString::fromLatin1("-")); software.append(version); // Set program info into Exif.Image.ProcessingSoftware tag (only available with Exiv2 >= 0.14.0). d->exifMetadata()["Exif.Image.ProcessingSoftware"] = std::string(software.toLatin1().constData()); // See B.K.O #142564: Check if Exif.Image.Software already exist. If yes, do not touch this tag. if (!d->exifMetadata().empty()) { Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifKey key("Exif.Image.Software"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it == exifData.end()) d->exifMetadata()["Exif.Image.Software"] = std::string(software.toLatin1().constData()); } // set program info into XMP tags. #ifdef _XMP_SUPPORT_ if (!d->xmpMetadata().empty()) { // Only create Xmp.xmp.CreatorTool if it do not exist. Exiv2::XmpData xmpData(d->xmpMetadata()); Exiv2::XmpKey key("Xmp.xmp.CreatorTool"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it == xmpData.end()) setXmpTagString("Xmp.xmp.CreatorTool", software, false); } setXmpTagString("Xmp.tiff.Software", software, false); #endif // _XMP_SUPPORT_ // Set program info into IPTC tags. d->iptcMetadata()["Iptc.Application2.Program"] = std::string(program.toLatin1().constData()); d->iptcMetadata()["Iptc.Application2.ProgramVersion"] = std::string(version.toLatin1().constData()); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Program identity into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QSize KExiv2::getImageDimensions() const { try { long width=-1, height=-1; // Try to get Exif.Photo tags Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifKey key("Exif.Photo.PixelXDimension"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end() && it->count()) #if EXIV2_TEST_VERSION(0,28,0) width = it->toUint32(); #else width = it->toLong(); #endif Exiv2::ExifKey key2("Exif.Photo.PixelYDimension"); Exiv2::ExifData::iterator it2 = exifData.findKey(key2); if (it2 != exifData.end() && it2->count()) #if EXIV2_TEST_VERSION(0,28,0) height = it2->toUint32(); #else height = it2->toLong(); #endif if (width != -1 && height != -1) return QSize(width, height); // Try to get Exif.Image tags width = -1; height = -1; Exiv2::ExifKey key3("Exif.Image.ImageWidth"); Exiv2::ExifData::iterator it3 = exifData.findKey(key3); if (it3 != exifData.end() && it3->count()) #if EXIV2_TEST_VERSION(0,28,0) width = it3->toUint32(); #else width = it3->toLong(); #endif Exiv2::ExifKey key4("Exif.Image.ImageLength"); Exiv2::ExifData::iterator it4 = exifData.findKey(key4); if (it4 != exifData.end() && it4->count()) #if EXIV2_TEST_VERSION(0,28,0) height = it4->toUint32(); #else height = it4->toLong(); #endif if (width != -1 && height != -1) return QSize(width, height); #ifdef _XMP_SUPPORT_ // Try to get Xmp.tiff tags width = -1; height = -1; bool wOk = false; bool hOk = false; QString str = getXmpTagString("Xmp.tiff.ImageWidth"); if (!str.isEmpty()) width = str.toInt(&wOk); str = getXmpTagString("Xmp.tiff.ImageLength"); if (!str.isEmpty()) height = str.toInt(&hOk); if (wOk && hOk) return QSize(width, height); // Try to get Xmp.exif tags width = -1; height = -1; wOk = false; hOk = false; str = getXmpTagString("Xmp.exif.PixelXDimension"); if (!str.isEmpty()) width = str.toInt(&wOk); str = getXmpTagString("Xmp.exif.PixelYDimension"); if (!str.isEmpty()) height = str.toInt(&hOk); if (wOk && hOk) return QSize(width, height); #endif // _XMP_SUPPORT_ } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse image dimensions tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QSize(); } bool KExiv2::setImageDimensions(const QSize& size, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { // Set Exif values. // NOTE: see B.K.O #144604: need to cast to record an unsigned integer value. d->exifMetadata()["Exif.Image.ImageWidth"] = static_cast<uint32_t>(size.width()); d->exifMetadata()["Exif.Image.ImageLength"] = static_cast<uint32_t>(size.height()); d->exifMetadata()["Exif.Photo.PixelXDimension"] = static_cast<uint32_t>(size.width()); d->exifMetadata()["Exif.Photo.PixelYDimension"] = static_cast<uint32_t>(size.height()); // Set Xmp values. #ifdef _XMP_SUPPORT_ setXmpTagString("Xmp.tiff.ImageWidth", QString::number(size.width()), false); setXmpTagString("Xmp.tiff.ImageLength", QString::number(size.height()), false); setXmpTagString("Xmp.exif.PixelXDimension", QString::number(size.width()), false); setXmpTagString("Xmp.exif.PixelYDimension", QString::number(size.height()), false); #endif // _XMP_SUPPORT_ return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set image dimensions using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } KExiv2::ImageOrientation KExiv2::getImageOrientation() const { try { Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it; long orientation; ImageOrientation imageOrient = ORIENTATION_NORMAL; // -- Standard Xmp tag -------------------------------- #ifdef _XMP_SUPPORT_ bool ok = false; QString str = getXmpTagString("Xmp.tiff.Orientation"); if (!str.isEmpty()) { orientation = str.toLong(&ok); if (ok) { qCDebug(LIBKEXIV2_LOG) << "Orientation => Xmp.tiff.Orientation => " << (int)orientation; return (ImageOrientation)orientation; } } #endif // _XMP_SUPPORT_ // Because some camera set a wrong standard exif orientation tag, // We need to check makernote tags in first! // -- Minolta Cameras ---------------------------------- Exiv2::ExifKey minoltaKey1("Exif.MinoltaCs7D.Rotation"); it = exifData.findKey(minoltaKey1); if (it != exifData.end() && it->count()) { #if EXIV2_TEST_VERSION(0,28,0) orientation = it->toUint32(); #else orientation = it->toLong(); #endif qCDebug(LIBKEXIV2_LOG) << "Orientation => Exif.MinoltaCs7D.Rotation => " << (int)orientation; switch(orientation) { case 76: imageOrient = ORIENTATION_ROT_90; break; case 82: imageOrient = ORIENTATION_ROT_270; break; } return imageOrient; } Exiv2::ExifKey minoltaKey2("Exif.MinoltaCs5D.Rotation"); it = exifData.findKey(minoltaKey2); if (it != exifData.end() && it->count()) { #if EXIV2_TEST_VERSION(0,28,0) orientation = it->toUint32(); #else orientation = it->toLong(); #endif qCDebug(LIBKEXIV2_LOG) << "Orientation => Exif.MinoltaCs5D.Rotation => " << (int)orientation; switch(orientation) { case 76: imageOrient = ORIENTATION_ROT_90; break; case 82: imageOrient = ORIENTATION_ROT_270; break; } return imageOrient; } // -- Standard Exif tag -------------------------------- Exiv2::ExifKey keyStd("Exif.Image.Orientation"); it = exifData.findKey(keyStd); if (it != exifData.end() && it->count()) { #if EXIV2_TEST_VERSION(0,28,0) orientation = it->toUint32(); #else orientation = it->toLong(); #endif qCDebug(LIBKEXIV2_LOG) << "Orientation => Exif.Image.Orientation => " << (int)orientation; return (ImageOrientation)orientation; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Exif Orientation tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return ORIENTATION_UNSPECIFIED; } bool KExiv2::setImageOrientation(ImageOrientation orientation, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { if (orientation < ORIENTATION_UNSPECIFIED || orientation > ORIENTATION_ROT_270) { qCDebug(LIBKEXIV2_LOG) << "Image orientation value is not correct!"; return false; } // Set Exif values. d->exifMetadata()["Exif.Image.Orientation"] = static_cast<uint16_t>(orientation); qCDebug(LIBKEXIV2_LOG) << "Exif.Image.Orientation tag set to: " << (int)orientation; // Set Xmp values. #ifdef _XMP_SUPPORT_ setXmpTagString("Xmp.tiff.Orientation", QString::number((int)orientation), false); #endif // _XMP_SUPPORT_ // -- Minolta/Sony Cameras ---------------------------------- // Minolta and Sony camera store image rotation in Makernote. // We remove these information to prevent duplicate values. Exiv2::ExifData::iterator it; Exiv2::ExifKey minoltaKey1("Exif.MinoltaCs7D.Rotation"); it = d->exifMetadata().findKey(minoltaKey1); if (it != d->exifMetadata().end()) { d->exifMetadata().erase(it); qCDebug(LIBKEXIV2_LOG) << "Removing Exif.MinoltaCs7D.Rotation tag"; } Exiv2::ExifKey minoltaKey2("Exif.MinoltaCs5D.Rotation"); it = d->exifMetadata().findKey(minoltaKey2); if (it != d->exifMetadata().end()) { d->exifMetadata().erase(it); qCDebug(LIBKEXIV2_LOG) << "Removing Exif.MinoltaCs5D.Rotation tag"; } // -- Exif embedded thumbnail ---------------------------------- Exiv2::ExifKey thumbKey("Exif.Thumbnail.Orientation"); it = d->exifMetadata().findKey(thumbKey); if (it != d->exifMetadata().end() && it->count()) { #if EXIV2_TEST_VERSION(0,28,0) RotationMatrix operation((KExiv2Iface::KExiv2::ImageOrientation)it->toUint32()); #else RotationMatrix operation((KExiv2Iface::KExiv2::ImageOrientation)it->toLong()); #endif operation *= orientation; (*it) = static_cast<uint16_t>(operation.exifOrientation()); } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif Orientation tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } KExiv2::ImageColorWorkSpace KExiv2::getImageColorWorkSpace() const { // Check Exif values. long exifColorSpace = -1; if (!getExifTagLong("Exif.Photo.ColorSpace", exifColorSpace)) { #ifdef _XMP_SUPPORT_ QVariant var = getXmpTagVariant("Xmp.exif.ColorSpace"); if (!var.isNull()) exifColorSpace = var.toInt(); #endif // _XMP_SUPPORT_ } if (exifColorSpace == 1) { return WORKSPACE_SRGB; // as specified by standard } else if (exifColorSpace == 2) { return WORKSPACE_ADOBERGB; // not in the standard! } else { if (exifColorSpace == 65535) { // A lot of cameras set the Exif.Iop.InteroperabilityIndex, // as documented for ExifTool QString interopIndex = getExifTagString("Exif.Iop.InteroperabilityIndex"); if (!interopIndex.isNull()) { if (interopIndex == QString::fromLatin1("R03")) return WORKSPACE_ADOBERGB; else if (interopIndex == QString::fromLatin1("R98")) return WORKSPACE_SRGB; } } // Note: Text EXIF ColorSpace tag may just not be present (NEF files) // Nikon camera set Exif.Photo.ColorSpace to uncalibrated or just skip this field, // then add additional information into the makernotes. // Exif.Nikon3.ColorSpace: 1 => sRGB, 2 => AdobeRGB long nikonColorSpace; if (getExifTagLong("Exif.Nikon3.ColorSpace", nikonColorSpace)) { if (nikonColorSpace == 1) return WORKSPACE_SRGB; else if (nikonColorSpace == 2) return WORKSPACE_ADOBERGB; } // Exif.Nikon3.ColorMode is set to "MODE2" for AdobeRGB, but there are sometimes two ColorMode fields // in a NEF, with the first one "COLOR" and the second one "MODE2"; but in this case, ColorSpace (above) was set. if (getExifTagString("Exif.Nikon3.ColorMode").contains(QString::fromLatin1("MODE2"))) return WORKSPACE_ADOBERGB; //TODO: This makernote tag (0x00b4) must be added to libexiv2 /* long canonColorSpace; if (getExifTagLong("Exif.Canon.ColorSpace", canonColorSpace)) { if (canonColorSpace == 1) return WORKSPACE_SRGB; else if (canonColorSpace == 2) return WORKSPACE_ADOBERGB; } */ // TODO : add more Makernote parsing here ... if (exifColorSpace == 65535) return WORKSPACE_UNCALIBRATED; } return WORKSPACE_UNSPECIFIED; } bool KExiv2::setImageColorWorkSpace(ImageColorWorkSpace workspace, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { // Set Exif value. d->exifMetadata()["Exif.Photo.ColorSpace"] = static_cast<uint16_t>(workspace); // Set Xmp value. #ifdef _XMP_SUPPORT_ setXmpTagString("Xmp.exif.ColorSpace", QString::number((int)workspace), false); #endif // _XMP_SUPPORT_ return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif color workspace tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QDateTime KExiv2::getImageDateTime() const { try { // In first, trying to get Date & time from Exif tags. if (!d->exifMetadata().empty()) { Exiv2::ExifData exifData(d->exifMetadata()); { Exiv2::ExifKey key("Exif.Photo.DateTimeOriginal"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Exif.Photo.DateTimeOriginal => " << dateTime; return dateTime; } } } { Exiv2::ExifKey key("Exif.Photo.DateTimeDigitized"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Exif.Photo.DateTimeDigitized => " << dateTime; return dateTime; } } } { Exiv2::ExifKey key("Exif.Image.DateTime"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Exif.Image.DateTime => " << dateTime; return dateTime; } } } } // In second, trying to get Date & time from Xmp tags. #ifdef _XMP_SUPPORT_ if (!d->xmpMetadata().empty()) { Exiv2::XmpData xmpData(d->xmpMetadata()); { Exiv2::XmpKey key("Xmp.exif.DateTimeOriginal"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.exif.DateTimeOriginal => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.exif.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.exif.DateTimeDigitized => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.photoshop.DateCreated"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.photoshop.DateCreated => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.xmp.CreateDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.xmp.CreateDate => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.tiff.DateTime"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.tiff.DateTime => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.xmp.ModifyDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.xmp.ModifyDate => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.xmp.MetadataDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.xmp.MetadataDate => " << dateTime; return dateTime; } } } // Video files support { Exiv2::XmpKey key("Xmp.video.DateTimeOriginal"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.video.DateTimeOriginal => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.DateUTC"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.video.DateUTC => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.ModificationDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.video.ModificationDate => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Xmp.video.DateTimeDigitized => " << dateTime; return dateTime; } } } } #endif // _XMP_SUPPORT_ // In third, trying to get Date & time from Iptc tags. if (!d->iptcMetadata().empty()) { Exiv2::IptcData iptcData(d->iptcMetadata()); // Try creation Iptc date & time entries. Exiv2::IptcKey keyDateCreated("Iptc.Application2.DateCreated"); Exiv2::IptcData::iterator it = iptcData.findKey(keyDateCreated); if (it != iptcData.end()) { QString IptcDateCreated(QString::fromLatin1(it->toString().c_str())); Exiv2::IptcKey keyTimeCreated("Iptc.Application2.TimeCreated"); Exiv2::IptcData::iterator it2 = iptcData.findKey(keyTimeCreated); if (it2 != iptcData.end()) { QString IptcTimeCreated(QString::fromLatin1(it2->toString().c_str())); QDate date = QDate::fromString(IptcDateCreated, Qt::ISODate); QTime time = QTime::fromString(IptcTimeCreated, Qt::ISODate); QDateTime dateTime = QDateTime(date, time); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Iptc.Application2.DateCreated => " << dateTime; return dateTime; } } } // Try digitization Iptc date & time entries. Exiv2::IptcKey keyDigitizationDate("Iptc.Application2.DigitizationDate"); Exiv2::IptcData::iterator it3 = iptcData.findKey(keyDigitizationDate); if (it3 != iptcData.end()) { QString IptcDateDigitization(QString::fromLatin1(it3->toString().c_str())); Exiv2::IptcKey keyDigitizationTime("Iptc.Application2.DigitizationTime"); Exiv2::IptcData::iterator it4 = iptcData.findKey(keyDigitizationTime); if (it4 != iptcData.end()) { QString IptcTimeDigitization(QString::fromLatin1(it4->toString().c_str())); QDate date = QDate::fromString(IptcDateDigitization, Qt::ISODate); QTime time = QTime::fromString(IptcTimeDigitization, Qt::ISODate); QDateTime dateTime = QDateTime(date, time); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime => Iptc.Application2.DigitizationDate => " << dateTime; return dateTime; } } } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Exif date & time tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QDateTime(); } bool KExiv2::setImageDateTime(const QDateTime& dateTime, bool setDateTimeDigitized, bool setProgramName) const { if(!dateTime.isValid()) return false; if (!setProgramId(setProgramName)) return false; try { // In first we write date & time into Exif. // DateTimeDigitized is set by slide scanners etc. when a picture is digitized. // DateTimeOriginal specifies the date/time when the picture was taken. // For digital cameras, these dates should be both set, and identical. // Reference: https://www.exif.org/Exif2-2.PDF, chapter 4.6.5, table 4, section F. const std::string &exifdatetime(dateTime.toString(QString::fromLatin1("yyyy:MM:dd hh:mm:ss")).toLatin1().constData()); d->exifMetadata()["Exif.Image.DateTime"] = exifdatetime; d->exifMetadata()["Exif.Photo.DateTimeOriginal"] = exifdatetime; if(setDateTimeDigitized) d->exifMetadata()["Exif.Photo.DateTimeDigitized"] = exifdatetime; #ifdef _XMP_SUPPORT_ // In second we write date & time into Xmp. const std::string &xmpdatetime(dateTime.toString(Qt::ISODate).toLatin1().constData()); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr xmpTxtVal = Exiv2::Value::create(Exiv2::xmpText); #else Exiv2::Value::AutoPtr xmpTxtVal = Exiv2::Value::create(Exiv2::xmpText); #endif xmpTxtVal->read(xmpdatetime); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.exif.DateTimeOriginal"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.photoshop.DateCreated"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.tiff.DateTime"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.xmp.CreateDate"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.xmp.MetadataDate"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.xmp.ModifyDate"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.DateTimeOriginal"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.DateUTC"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.ModificationDate"), xmpTxtVal.get()); if(setDateTimeDigitized) { d->xmpMetadata().add(Exiv2::XmpKey("Xmp.exif.DateTimeDigitized"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.DateTimeDigitized"), xmpTxtVal.get()); } // Tag not updated: // "Xmp.dc.DateTime" is a sequence of date relevant of dublin core change. // This is not the picture date as well #endif // _XMP_SUPPORT_ // In third we write date & time into Iptc. const std::string &iptcdate(dateTime.date().toString(Qt::ISODate).toLatin1().constData()); const std::string &iptctime(dateTime.time().toString(Qt::ISODate).toLatin1().constData()); d->iptcMetadata()["Iptc.Application2.DateCreated"] = iptcdate; d->iptcMetadata()["Iptc.Application2.TimeCreated"] = iptctime; if(setDateTimeDigitized) { d->iptcMetadata()["Iptc.Application2.DigitizationDate"] = iptcdate; d->iptcMetadata()["Iptc.Application2.DigitizationTime"] = iptctime; } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Date & Time into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QDateTime KExiv2::getDigitizationDateTime(bool fallbackToCreationTime) const { try { // In first, trying to get Date & time from Exif tags. if (!d->exifMetadata().empty()) { // Try Exif date time digitized. Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifKey key("Exif.Photo.DateTimeDigitized"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime (Exif digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } // In second, we trying XMP #ifdef _XMP_SUPPORT_ if (!d->xmpMetadata().empty()) { Exiv2::XmpData xmpData(d->xmpMetadata()); { Exiv2::XmpKey key("Xmp.exif.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime (XMP-Exif digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "DateTime (XMP-Video digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } } #endif // _XMP_SUPPORT_ // In third, trying to get Date & time from Iptc tags. if (!d->iptcMetadata().empty()) { // Try digitization Iptc date time entries. Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcKey keyDigitizationDate("Iptc.Application2.DigitizationDate"); Exiv2::IptcData::iterator it = iptcData.findKey(keyDigitizationDate); if (it != iptcData.end()) { QString IptcDateDigitization(QString::fromLatin1(it->toString().c_str())); Exiv2::IptcKey keyDigitizationTime("Iptc.Application2.DigitizationTime"); Exiv2::IptcData::iterator it2 = iptcData.findKey(keyDigitizationTime); if (it2 != iptcData.end()) { QString IptcTimeDigitization(QString::fromLatin1(it2->toString().c_str())); QDate date = QDate::fromString(IptcDateDigitization, Qt::ISODate); QTime time = QTime::fromString(IptcTimeDigitization, Qt::ISODate); QDateTime dateTime = QDateTime(date, time); if (dateTime.isValid()) { qCDebug(LIBKEXIV2_LOG) << "Date (IPTC digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Exif digitization date & time tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } if (fallbackToCreationTime) return getImageDateTime(); else return QDateTime(); } bool KExiv2::getImagePreview(QImage& preview) const { try { // In first we trying to get from Iptc preview tag. if (preview.loadFromData(getIptcTagData("Iptc.Application2.Preview")) ) return true; // TODO : Added here Makernotes preview extraction when Exiv2 will be fixed for that. } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get image preview using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setImagePreview(const QImage& preview, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; if (preview.isNull()) { removeIptcTag("Iptc.Application2.Preview"); removeIptcTag("Iptc.Application2.PreviewFormat"); removeIptcTag("Iptc.Application2.PreviewVersion"); return true; } try { QByteArray data; QBuffer buffer(&data); buffer.open(QIODevice::WriteOnly); // A little bit compressed preview jpeg image to limit IPTC size. preview.save(&buffer, "JPEG"); qCDebug(LIBKEXIV2_LOG) << "JPEG image preview size: (" << preview.width() << " x " << preview.height() << ") pixels - " << data.size() << " bytes"; Exiv2::DataValue val; val.read((Exiv2::byte *)data.data(), data.size()); d->iptcMetadata()["Iptc.Application2.Preview"] = val; // See https://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf Appendix A for details. d->iptcMetadata()["Iptc.Application2.PreviewFormat"] = 11; // JPEG d->iptcMetadata()["Iptc.Application2.PreviewVersion"] = 1; return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get image preview using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } } // NameSpace KExiv2Iface 0707010000001D000081A4000000000000000000000001662795850000649C000000000000000000000000000000000000004000000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2iptc.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ // Local includes #include "kexiv2.h" #include "kexiv2_p.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { bool KExiv2::canWriteIptc(const QString& filePath) { try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image = #else Exiv2::Image::AutoPtr image = #endif Exiv2::ImageFactory::open((const char*) (QFile::encodeName(filePath).constData())); Exiv2::AccessMode mode = image->checkMode(Exiv2::mdIptc); return (mode == Exiv2::amWrite || mode == Exiv2::amReadWrite); } catch(Exiv2::Error& e) { std::string s(e.what()); qCCritical(LIBKEXIV2_LOG) << "Cannot check Iptc access mode using Exiv2 (Error #" #if EXIV2_TEST_VERSION(0,28,0) << Exiv2::Error(e.code()).what() #else << e.code() << ": " << s.c_str() #endif << ")"; } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::hasIptc() const { return !d->iptcMetadata().empty(); } bool KExiv2::clearIptc() const { try { d->iptcMetadata().clear(); return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot clear Iptc data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QByteArray KExiv2::getIptc(bool addIrbHeader) const { try { if (!d->iptcMetadata().empty()) { Exiv2::IptcData& iptc = d->iptcMetadata(); Exiv2::DataBuf c2; if (addIrbHeader) { c2 = Exiv2::Photoshop::setIptcIrb(nullptr, 0, iptc); } else { c2 = Exiv2::IptcParser::encode(d->iptcMetadata()); } #if EXIV2_TEST_VERSION(0,28,0) QByteArray data((const char*)c2.c_data(), c2.size()); #else QByteArray data((const char*)c2.pData_, c2.size_); #endif return data; } } catch(Exiv2::Error& e) { if (!d->filePath.isEmpty()) { qCCritical(LIBKEXIV2_LOG) << "From file " << d->filePath.toLatin1().constData(); } d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Iptc data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QByteArray(); } bool KExiv2::setIptc(const QByteArray& data) const { try { if (!data.isEmpty()) { Exiv2::IptcParser::decode(d->iptcMetadata(), (const Exiv2::byte*)data.data(), data.size()); return (!d->iptcMetadata().empty()); } } catch(Exiv2::Error& e) { if (!d->filePath.isEmpty()) { qCCritical(LIBKEXIV2_LOG) << "From file " << d->filePath.toLatin1().constData(); } d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } KExiv2::MetaDataMap KExiv2::getIptcTagsDataList(const QStringList& iptcKeysFilter, bool invertSelection) const { if (d->iptcMetadata().empty()) return MetaDataMap(); try { Exiv2::IptcData iptcData = d->iptcMetadata(); iptcData.sortByKey(); QString ifDItemName; MetaDataMap metaDataMap; for (Exiv2::IptcData::iterator md = iptcData.begin(); md != iptcData.end(); ++md) { QString key = QString::fromLocal8Bit(md->key().c_str()); // Decode the tag value with a user friendly output. std::ostringstream os; os << *md; QString value; if (key == QString::fromLatin1("Iptc.Envelope.CharacterSet")) { value = QString::fromLatin1(iptcData.detectCharset()); } else { value = QString::fromUtf8(os.str().c_str()); } // To make a string just on one line. value.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); // Some Iptc key are redondancy. check if already one exist... MetaDataMap::iterator it = metaDataMap.find(key); // We apply a filter to get only the Iptc tags that we need. if (!iptcKeysFilter.isEmpty()) { if (!invertSelection) { if (iptcKeysFilter.contains(key.section(QString::fromLatin1("."), 1, 1))) { if (it == metaDataMap.end()) { metaDataMap.insert(key, value); } else { QString v = *it; v.append(QString::fromLatin1(", ")); v.append(value); metaDataMap.insert(key, v); } } } else { if (!iptcKeysFilter.contains(key.section(QString::fromLatin1("."), 1, 1))) { if (it == metaDataMap.end()) { metaDataMap.insert(key, value); } else { QString v = *it; v.append(QString::fromLatin1(", ")); v.append(value); metaDataMap.insert(key, v); } } } } else // else no filter at all. { if (it == metaDataMap.end()) { metaDataMap.insert(key, value); } else { QString v = *it; v.append(QString::fromLatin1(", ")); v.append(value); metaDataMap.insert(key, v); } } } return metaDataMap; } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Iptc metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return MetaDataMap(); } QString KExiv2::getIptcTagTitle(const char* iptcTagName) { try { std::string iptckey(iptcTagName); Exiv2::IptcKey ik(iptckey); return QString::fromLocal8Bit( Exiv2::IptcDataSets::dataSetTitle(ik.tag(), ik.record()) ); } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get metadata tag title using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } QString KExiv2::getIptcTagDescription(const char* iptcTagName) { try { std::string iptckey(iptcTagName); Exiv2::IptcKey ik(iptckey); return QString::fromLocal8Bit( Exiv2::IptcDataSets::dataSetDesc(ik.tag(), ik.record()) ); } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get metadata tag description using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } bool KExiv2::removeIptcTag(const char* iptcTagName, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { Exiv2::IptcData::iterator it = d->iptcMetadata().begin(); int i = 0; while(it != d->iptcMetadata().end()) { QString key = QString::fromLocal8Bit(it->key().c_str()); if (key == QString::fromLatin1(iptcTagName)) { it = d->iptcMetadata().erase(it); ++i; } else { ++it; } }; if (i > 0) return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot remove Iptc tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } bool KExiv2::setIptcTagData(const char* iptcTagName, const QByteArray& data, bool setProgramName) const { if (data.isEmpty()) return false; if (!setProgramId(setProgramName)) return false; try { Exiv2::DataValue val((Exiv2::byte *)data.data(), data.size()); d->iptcMetadata()[iptcTagName] = val; return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc tag data into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QByteArray KExiv2::getIptcTagData(const char* iptcTagName) const { try { Exiv2::IptcKey iptcKey(iptcTagName); Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcData::iterator it = iptcData.findKey(iptcKey); if (it != iptcData.end()) { char* const s = new char[(*it).size()]; (*it).copy((Exiv2::byte*)s, Exiv2::bigEndian); QByteArray data(s, (*it).size()); delete [] s; return data; } } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Iptc key '%1' into image using Exiv2 ").arg(QString::fromLatin1(iptcTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QByteArray(); } QString KExiv2::getIptcTagString(const char* iptcTagName, bool escapeCR) const { try { Exiv2::IptcKey iptcKey(iptcTagName); Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcData::iterator it = iptcData.findKey(iptcKey); if (it != iptcData.end()) { std::ostringstream os; os << *it; QString tagValue(QString::fromLatin1(os.str().c_str())); if (escapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return tagValue; } } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Iptc key '%1' into image using Exiv2 ").arg(QString::fromLatin1(iptcTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QString(); } bool KExiv2::setIptcTagString(const char* iptcTagName, const QString& value, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { d->iptcMetadata()[iptcTagName] = std::string(value.toUtf8().constData()); // Make sure we have set the charset to UTF-8 d->iptcMetadata()["Iptc.Envelope.CharacterSet"] = "\33%G"; return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc tag string into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QStringList KExiv2::getIptcTagsStringList(const char* iptcTagName, bool escapeCR) const { try { if (!d->iptcMetadata().empty()) { QStringList values; Exiv2::IptcData iptcData(d->iptcMetadata()); for (Exiv2::IptcData::iterator it = iptcData.begin(); it != iptcData.end(); ++it) { QString key = QString::fromLocal8Bit(it->key().c_str()); if (key == QString::fromLatin1(iptcTagName)) { QString tagValue = QString::fromUtf8(it->toString().c_str()); if (escapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); values.append(tagValue); } } return values; } } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Iptc key '%1' into image using Exiv2 ").arg(QString::fromLatin1(iptcTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QStringList(); } bool KExiv2::setIptcTagsStringList(const char* iptcTagName, int maxSize, const QStringList& oldValues, const QStringList& newValues, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { QStringList oldvals = oldValues; QStringList newvals = newValues; qCDebug(LIBKEXIV2_LOG) << d->filePath.toLatin1().constData() << " : " << iptcTagName << " => " << newvals.join(QString::fromLatin1(",")).toLatin1().constData(); // Remove all old values. Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcData::iterator it = iptcData.begin(); while(it != iptcData.end()) { QString key = QString::fromLocal8Bit(it->key().c_str()); QString val = QString::fromUtf8(it->toString().c_str()); // Also remove new values to avoid duplicates. They will be added again below. if ( key == QString::fromLatin1(iptcTagName) && (oldvals.contains(val) || newvals.contains(val)) ) it = iptcData.erase(it); else ++it; }; // Add new values. Exiv2::IptcKey iptcTag(iptcTagName); for (QStringList::iterator it = newvals.begin(); it != newvals.end(); ++it) { QString key = *it; key.truncate(maxSize); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr val = Exiv2::Value::create(Exiv2::string); #else Exiv2::Value::AutoPtr val = Exiv2::Value::create(Exiv2::string); #endif val->read(key.toUtf8().constData()); iptcData.add(iptcTag, val.get()); } d->iptcMetadata() = iptcData; // Make sure character set is UTF-8 setIptcTagString("Iptc.Envelope.CharacterSet", QString::fromLatin1("\33%G"), false); return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc key '%1' into image using Exiv2 ").arg(QString::fromLatin1(iptcTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QStringList KExiv2::getIptcKeywords() const { try { if (!d->iptcMetadata().empty()) { QStringList keywords; Exiv2::IptcData iptcData(d->iptcMetadata()); for (Exiv2::IptcData::iterator it = iptcData.begin(); it != iptcData.end(); ++it) { QString key = QString::fromLocal8Bit(it->key().c_str()); if (key == QString::fromLatin1("Iptc.Application2.Keywords")) { QString val = QString::fromUtf8(it->toString().c_str()); keywords.append(val); } } qCDebug(LIBKEXIV2_LOG) << d->filePath << " ==> Read Iptc Keywords: " << keywords; return keywords; } } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Iptc Keywords from image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QStringList(); } bool KExiv2::setIptcKeywords(const QStringList& oldKeywords, const QStringList& newKeywords, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { QStringList oldkeys = oldKeywords; QStringList newkeys = newKeywords; qCDebug(LIBKEXIV2_LOG) << d->filePath << " ==> New Iptc Keywords: " << newkeys; // Remove all old keywords. Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcData::iterator it = iptcData.begin(); while(it != iptcData.end()) { QString key = QString::fromLocal8Bit(it->key().c_str()); QString val = QString::fromUtf8(it->toString().c_str()); // Also remove new keywords to avoid duplicates. They will be added again below. if ( key == QString::fromLatin1("Iptc.Application2.Keywords") && (oldKeywords.contains(val) || newKeywords.contains(val)) ) it = iptcData.erase(it); else ++it; }; // Add new keywords. Note that Keywords Iptc tag is limited to 64 char but can be redondant. Exiv2::IptcKey iptcTag("Iptc.Application2.Keywords"); for (QStringList::iterator it = newkeys.begin(); it != newkeys.end(); ++it) { QString key = *it; key.truncate(64); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr val = Exiv2::Value::create(Exiv2::string); #else Exiv2::Value::AutoPtr val = Exiv2::Value::create(Exiv2::string); #endif val->read(key.toUtf8().constData()); iptcData.add(iptcTag, val.get()); } d->iptcMetadata() = iptcData; // Make sure character set is UTF-8 setIptcTagString("Iptc.Envelope.CharacterSet", QString::fromLatin1("\33%G"), false); return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc Keywords into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QStringList KExiv2::getIptcSubjects() const { try { if (!d->iptcMetadata().empty()) { QStringList subjects; Exiv2::IptcData iptcData(d->iptcMetadata()); for (Exiv2::IptcData::iterator it = iptcData.begin(); it != iptcData.end(); ++it) { QString key = QString::fromLocal8Bit(it->key().c_str()); if (key == QString::fromLatin1("Iptc.Application2.Subject")) { QString val(QString::fromLatin1(it->toString().c_str())); subjects.append(val); } } return subjects; } } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Iptc Subjects from image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QStringList(); } bool KExiv2::setIptcSubjects(const QStringList& oldSubjects, const QStringList& newSubjects, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { QStringList oldDef = oldSubjects; QStringList newDef = newSubjects; // Remove all old subjects. Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcData::iterator it = iptcData.begin(); while(it != iptcData.end()) { QString key = QString::fromLocal8Bit(it->key().c_str()); QString val = QString::fromUtf8(it->toString().c_str()); if (key == QString::fromLatin1("Iptc.Application2.Subject") && oldDef.contains(val)) it = iptcData.erase(it); else ++it; }; // Add new subjects. Note that Keywords Iptc tag is limited to 236 char but can be redondant. Exiv2::IptcKey iptcTag("Iptc.Application2.Subject"); for (QStringList::iterator it = newDef.begin(); it != newDef.end(); ++it) { QString key = *it; key.truncate(236); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr val = Exiv2::Value::create(Exiv2::string); #else Exiv2::Value::AutoPtr val = Exiv2::Value::create(Exiv2::string); #endif val->read(key.toUtf8().constData()); iptcData.add(iptcTag, val.get()); } d->iptcMetadata() = iptcData; // Make sure character set is UTF-8 setIptcTagString("Iptc.Envelope.CharacterSet", QString::fromLatin1("\33%G"), false); return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc Subjects into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } QStringList KExiv2::getIptcSubCategories() const { try { if (!d->iptcMetadata().empty()) { QStringList subCategories; Exiv2::IptcData iptcData(d->iptcMetadata()); for (Exiv2::IptcData::iterator it = iptcData.begin(); it != iptcData.end(); ++it) { QString key = QString::fromLocal8Bit(it->key().c_str()); if (key == QString::fromLatin1("Iptc.Application2.SuppCategory")) { QString val(QString::fromLatin1(it->toString().c_str())); subCategories.append(val); } } return subCategories; } } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Iptc Sub Categories from image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return QStringList(); } bool KExiv2::setIptcSubCategories(const QStringList& oldSubCategories, const QStringList& newSubCategories, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { QStringList oldkeys = oldSubCategories; QStringList newkeys = newSubCategories; // Remove all old Sub Categories. Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcData::iterator it = iptcData.begin(); while(it != iptcData.end()) { QString key = QString::fromLocal8Bit(it->key().c_str()); QString val = QString::fromUtf8(it->toString().c_str()); if (key == QString::fromLatin1("Iptc.Application2.SuppCategory") && oldSubCategories.contains(val)) it = iptcData.erase(it); else ++it; }; // Add new Sub Categories. Note that SubCategories Iptc tag is limited to 32 // characters but can be redondant. Exiv2::IptcKey iptcTag("Iptc.Application2.SuppCategory"); for (QStringList::iterator it = newkeys.begin(); it != newkeys.end(); ++it) { QString key = *it; key.truncate(32); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr val = Exiv2::Value::create(Exiv2::string); #else Exiv2::Value::AutoPtr val = Exiv2::Value::create(Exiv2::string); #endif val->read(key.toUtf8().constData()); iptcData.add(iptcTag, val.get()); } d->iptcMetadata() = iptcData; // Make sure character set is UTF-8 setIptcTagString("Iptc.Envelope.CharacterSet", QString::fromLatin1("\33%G"), false); return true; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Iptc Sub Categories into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return false; } KExiv2::TagsMap KExiv2::getIptcTagsList() const { try { QList<const Exiv2::DataSet*> tags; tags << Exiv2::IptcDataSets::envelopeRecordList() << Exiv2::IptcDataSets::application2RecordList(); TagsMap tagsMap; for (QList<const Exiv2::DataSet*>::iterator it = tags.begin(); it != tags.end(); ++it) { do { QString key = QLatin1String( Exiv2::IptcKey( (*it)->number_, (*it)->recordId_ ).key().c_str() ); QStringList values; values << QString::fromLatin1((*it)->name_) << QString::fromLatin1((*it)->title_) << QString::fromLatin1((*it)->desc_); tagsMap.insert(key, values); ++(*it); } while((*it)->number_ != 0xffff); } return tagsMap; } catch(Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Iptc Tags list using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } return TagsMap(); } } // NameSpace KExiv2Iface 0707010000001E000081A40000000000000000000000016627958500001404000000000000000000000000000000000000004400000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2previews.cpp/* SPDX-FileCopyrightText: 2009-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2009-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ // Local includes #include "kexiv2previews.h" #include "kexiv2_p.h" #include "kexiv2.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { class KExiv2PreviewsPrivate { public: KExiv2PreviewsPrivate() { manager = nullptr; } ~KExiv2PreviewsPrivate() { delete manager; } #if EXIV2_TEST_VERSION(0,28,0) void load(Exiv2::Image::UniquePtr image_) #else void load(Exiv2::Image::AutoPtr image_) #endif { #if EXIV2_TEST_VERSION(0,28,0) image = std::move(image_); #else image = image_; #endif image->readMetadata(); manager = new Exiv2::PreviewManager(*image); Exiv2::PreviewPropertiesList props = manager->getPreviewProperties(); // reverse order of list, which is smallest-first Exiv2::PreviewPropertiesList::reverse_iterator it; for (it = props.rbegin() ; it != props.rend() ; ++it) { properties << *it; } } public: #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image; #else Exiv2::Image::AutoPtr image; #endif Exiv2::PreviewManager* manager; QList<Exiv2::PreviewProperties> properties; }; KExiv2Previews::KExiv2Previews(const QString& filePath) : d(new KExiv2PreviewsPrivate) { try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(filePath).constData())); d->load(std::move(image)); #else Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(filePath).constData())); d->load(image); #endif } catch( Exiv2::Error& e ) { KExiv2Private::printExiv2ExceptionError(QString::fromLatin1("Cannot load metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } } KExiv2Previews::KExiv2Previews(const QByteArray& imgData) : d(new KExiv2PreviewsPrivate) { try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open((Exiv2::byte*)imgData.data(), imgData.size()); d->load(std::move(image)); #else Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open((Exiv2::byte*)imgData.data(), imgData.size()); d->load(image); #endif } catch( Exiv2::Error& e ) { KExiv2Private::printExiv2ExceptionError(QString::fromLatin1("Cannot load metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } } KExiv2Previews::~KExiv2Previews() = default; bool KExiv2Previews::isEmpty() { return d->properties.isEmpty(); } QSize KExiv2Previews::originalSize() const { if (d->image.get()) return QSize(d->image->pixelWidth(), d->image->pixelHeight()); return QSize(); } QString KExiv2Previews::originalMimeType() const { if (d->image.get()) return QString::fromLatin1(d->image->mimeType().c_str()); return QString(); } int KExiv2Previews::count() { return d->properties.size(); } int KExiv2Previews::dataSize(int index) { if (index < 0 || index >= size()) return 0; return d->properties[index].size_; } int KExiv2Previews::width(int index) { if (index < 0 || index >= size()) return 0; return d->properties[index].width_; } int KExiv2Previews::height(int index) { if (index < 0 || index >= size()) return 0; return d->properties[index].height_; } QString KExiv2Previews::mimeType(int index) { if (index < 0 || index >= size()) return QString(); return QString::fromLatin1(d->properties[index].mimeType_.c_str()); } QString KExiv2Previews::fileExtension(int index) { if (index < 0 || index >= size()) return QString(); return QString::fromLatin1(d->properties[index].extension_.c_str()); } QByteArray KExiv2Previews::data(int index) { if (index < 0 || index >= size()) return QByteArray(); qCDebug(LIBKEXIV2_LOG) << "index: " << index; qCDebug(LIBKEXIV2_LOG) << "d->properties: " << count(); try { Exiv2::PreviewImage image = d->manager->getPreviewImage(d->properties[index]); return QByteArray((const char*)image.pData(), image.size()); } catch( Exiv2::Error& e ) { KExiv2Private::printExiv2ExceptionError(QString::fromLatin1("Cannot load metadata using Exiv2 "), e); return QByteArray(); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; return QByteArray(); } } QImage KExiv2Previews::image(int index) { QByteArray previewData = data(index); QImage image; if (!image.loadFromData(previewData)) return QImage(); return image; } } // namespace KExiv2Iface 0707010000001F000081A400000000000000000000000166279585000008F1000000000000000000000000000000000000004200000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2previews.h/* SPDX-FileCopyrightText: 2009-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2009-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef KEXIV2PREVIEWS #define KEXIV2PREVIEWS // Std #include <memory> // Qt includes #include <QByteArray> #include <QSize> #include <QString> // Local includes #include "libkexiv2_export.h" class QImage; namespace KExiv2Iface { /** * @class KExiv2Previews kexiv2previews.h <KExiv2/KExiv2Previews> * * KExiv2Previews */ class LIBKEXIV2_EXPORT KExiv2Previews { public: /** * Open the given file and scan for embedded preview images */ KExiv2Previews(const QString& filePath); /** * Open the given image data and scan the image for embedded preview images. */ KExiv2Previews(const QByteArray& imgData); ~KExiv2Previews(); /// Returns the pixel size of the original image, as read from the file (not the metadata). QSize originalSize() const; /// Returns the mimeType of the original image, detected from the file's content. QString originalMimeType() const; /// Returns if there are any preview images available bool isEmpty(); /// Returns how many embedded previews are available int count(); int size() { return count(); } /** * For each contained preview image, return the size * of the image data in bytes, width and height of the preview, * the mimeType and the file extension. * Ensure that index < count(). * Previews are sorted by width*height, largest first. */ int dataSize(int index = 0); int width(int index = 0); int height(int index = 0); QString mimeType(int index = 0); QString fileExtension(int index = 0); /** * Retrieve the image data for the specified embedded preview image */ QByteArray data(int index = 0); /** * Loads the data of the specified preview and creates a QImage * from this data. Returns a null QImage if the loading failed. */ QImage image(int index = 0); private: std::unique_ptr<class KExiv2PreviewsPrivate> const d; }; } // namespace KExiv2Iface #endif // KEXIV2PREVIEWS 07070100000020000081A40000000000000000000000016627958500008753000000000000000000000000000000000000003F00000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/kexiv2xmp.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2006-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ // Local includes #include "kexiv2.h" #include "kexiv2_p.h" #include "libkexiv2_debug.h" namespace KExiv2Iface { bool KExiv2::canWriteXmp(const QString& filePath) { #ifdef _XMP_SUPPORT_ try { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Image::UniquePtr image = #else Exiv2::Image::AutoPtr image = #endif Exiv2::ImageFactory::open((const char*) (QFile::encodeName(filePath).constData())); Exiv2::AccessMode mode = image->checkMode(Exiv2::mdXmp); return (mode == Exiv2::amWrite || mode == Exiv2::amReadWrite); } catch( Exiv2::Error& e ) { std::string s(e.what()); qCCritical(LIBKEXIV2_LOG) << "Cannot check Xmp access mode using Exiv2 (Error #" #if EXIV2_TEST_VERSION(0,28,0) << Exiv2::Error(e.code()).what() #else << e.code() << ": " << s.c_str() #endif << ")"; } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(filePath); #endif // _XMP_SUPPORT_ return false; } bool KExiv2::hasXmp() const { #ifdef _XMP_SUPPORT_ return !d->xmpMetadata().empty(); #else return false; #endif // _XMP_SUPPORT_ } bool KExiv2::clearXmp() const { #ifdef _XMP_SUPPORT_ try { d->xmpMetadata().clear(); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot clear Xmp data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #endif // _XMP_SUPPORT_ return false; } QByteArray KExiv2::getXmp() const { #ifdef _XMP_SUPPORT_ try { if (!d->xmpMetadata().empty()) { std::string xmpPacket; Exiv2::XmpParser::encode(xmpPacket, d->xmpMetadata()); QByteArray data(xmpPacket.data(), xmpPacket.size()); return data; } } catch( Exiv2::Error& e ) { if (!d->filePath.isEmpty()) d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Xmp data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #endif // _XMP_SUPPORT_ return QByteArray(); } bool KExiv2::setXmp(const QByteArray& data) const { #ifdef _XMP_SUPPORT_ try { if (!data.isEmpty()) { std::string xmpPacket; xmpPacket.assign(data.data(), data.size()); if (Exiv2::XmpParser::decode(d->xmpMetadata(), xmpPacket) != 0) return false; else return true; } } catch( Exiv2::Error& e ) { if (!d->filePath.isEmpty()) qCCritical(LIBKEXIV2_LOG) << "From file " << d->filePath.toLatin1().constData(); d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp data using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(data); #endif // _XMP_SUPPORT_ return false; } KExiv2::MetaDataMap KExiv2::getXmpTagsDataList(const QStringList& xmpKeysFilter, bool invertSelection) const { #ifdef _XMP_SUPPORT_ if (d->xmpMetadata().empty()) return MetaDataMap(); try { Exiv2::XmpData xmpData = d->xmpMetadata(); xmpData.sortByKey(); QString ifDItemName; MetaDataMap metaDataMap; for (Exiv2::XmpData::iterator md = xmpData.begin(); md != xmpData.end(); ++md) { QString key = QString::fromLatin1(md->key().c_str()); // Decode the tag value with a user friendly output. std::ostringstream os; os << *md; QString value = QString::fromUtf8(os.str().c_str()); // If the tag is a language alternative type, parse content to detect language. if (md->typeId() == Exiv2::langAlt) { QString lang; value = detectLanguageAlt(value, lang); } else { value = QString::fromUtf8(os.str().c_str()); } // To make a string just on one line. value.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); // Some XMP key are redondancy. check if already one exist... MetaDataMap::iterator it = metaDataMap.find(key); // We apply a filter to get only the XMP tags that we need. if (!xmpKeysFilter.isEmpty()) { if (!invertSelection) { if (xmpKeysFilter.contains(key.section(QString::fromLatin1("."), 1, 1))) { if (it == metaDataMap.end()) { metaDataMap.insert(key, value); } else { QString v = *it; v.append(QString::fromLatin1(", ")); v.append(value); metaDataMap.insert(key, v); } } } else { if (!xmpKeysFilter.contains(key.section(QString::fromLatin1("."), 1, 1))) { if (it == metaDataMap.end()) { metaDataMap.insert(key, value); } else { QString v = *it; v.append(QString::fromLatin1(", ")); v.append(value); metaDataMap.insert(key, v); } } } } else // else no filter at all. { if (it == metaDataMap.end()) { metaDataMap.insert(key, value); } else { QString v = *it; v.append(QString::fromLatin1(", ")); v.append(value); metaDataMap.insert(key, v); } } } return metaDataMap; } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Xmp metadata using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpKeysFilter); Q_UNUSED(invertSelection); #endif // _XMP_SUPPORT_ return MetaDataMap(); } QString KExiv2::getXmpTagTitle(const char* xmpTagName) { #ifdef _XMP_SUPPORT_ try { std::string xmpkey(xmpTagName); Exiv2::XmpKey xk(xmpkey); return QString::fromLocal8Bit( Exiv2::XmpProperties::propertyTitle(xk) ); } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Xmp metadata tag title using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); #endif // _XMP_SUPPORT_ return QString(); } QString KExiv2::getXmpTagDescription(const char* xmpTagName) { #ifdef _XMP_SUPPORT_ try { std::string xmpkey(xmpTagName); Exiv2::XmpKey xk(xmpkey); return QString::fromLocal8Bit( Exiv2::XmpProperties::propertyDesc(xk) ); } catch (Exiv2::Error& e) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot get Xmp metadata tag description using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); #endif // _XMP_SUPPORT_ return QString(); } QString KExiv2::getXmpTagString(const char* xmpTagName, bool escapeCR) const { #ifdef _XMP_SUPPORT_ try { Exiv2::XmpData xmpData(d->xmpMetadata()); Exiv2::XmpKey key(xmpTagName); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { std::ostringstream os; os << *it; QString tagValue = QString::fromUtf8(os.str().c_str()); if (escapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return tagValue; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Xmp key '%1' into image using Exiv2 ").arg(QString::fromLatin1(xmpTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(escapeCR); #endif // _XMP_SUPPORT_ return QString(); } bool KExiv2::setXmpTagString(const char* xmpTagName, const QString& value, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { const std::string &txt(value.toUtf8().constData()); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr xmpTxtVal = Exiv2::Value::create(Exiv2::xmpText); #else Exiv2::Value::AutoPtr xmpTxtVal = Exiv2::Value::create(Exiv2::xmpText); #endif xmpTxtVal->read(txt); d->xmpMetadata()[xmpTagName].setValue(xmpTxtVal.get()); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp tag string into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(value); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } bool KExiv2::setXmpTagString(const char* xmpTagName, const QString& value, KExiv2::XmpTagType type, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { const std::string &txt(value.toUtf8().constData()); Exiv2::XmpTextValue xmpTxtVal(""); if (type == KExiv2::NormalTag) // normal type { xmpTxtVal.read(txt); d->xmpMetadata().add(Exiv2::XmpKey(xmpTagName),&xmpTxtVal); return true; } if (type == KExiv2::ArrayBagTag) // xmp type = bag { xmpTxtVal.setXmpArrayType(Exiv2::XmpValue::xaBag); xmpTxtVal.read(""); d->xmpMetadata().add(Exiv2::XmpKey(xmpTagName),&xmpTxtVal); } if (type == KExiv2::StructureTag) // xmp type = struct { xmpTxtVal.setXmpStruct(); d->xmpMetadata().add(Exiv2::XmpKey(xmpTagName),&xmpTxtVal); } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp tag string into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(value); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } KExiv2::AltLangMap KExiv2::getXmpTagStringListLangAlt(const char* xmpTagName, bool escapeCR) const { #ifdef _XMP_SUPPORT_ try { Exiv2::XmpData xmpData = d->xmpMetadata(); for (Exiv2::XmpData::iterator it = xmpData.begin(); it != xmpData.end(); ++it) { if (it->key() == xmpTagName && it->typeId() == Exiv2::langAlt) { AltLangMap map; const Exiv2::LangAltValue &value = static_cast<const Exiv2::LangAltValue &>(it->value()); for (Exiv2::LangAltValue::ValueType::const_iterator it2 = value.value_.begin(); it2 != value.value_.end(); ++it2) { QString lang = QString::fromUtf8(it2->first.c_str()); QString text = QString::fromUtf8(it2->second.c_str()); if (escapeCR) text.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); map.insert(lang, text); } return map; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Xmp key '%1' into image using Exiv2 ").arg(QString::fromLatin1(xmpTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(escapeCR); #endif // _XMP_SUPPORT_ return AltLangMap(); } bool KExiv2::setXmpTagStringListLangAlt(const char* xmpTagName, const KExiv2::AltLangMap& values, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { // Remove old XMP alternative Language tag. removeXmpTag(xmpTagName); if (!values.isEmpty()) { #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr xmpTxtVal = Exiv2::Value::create(Exiv2::langAlt); #else Exiv2::Value::AutoPtr xmpTxtVal = Exiv2::Value::create(Exiv2::langAlt); #endif for (AltLangMap::const_iterator it = values.constBegin(); it != values.constEnd(); ++it) { QString lang = it.key(); QString text = it.value(); QString txtLangAlt = QString::fromLatin1("lang=%1 %2").arg(lang).arg(text); const std::string &txt(txtLangAlt.toUtf8().constData()); xmpTxtVal->read(txt); } // ...and add the new one instead. d->xmpMetadata().add(Exiv2::XmpKey(xmpTagName), xmpTxtVal.get()); } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp tag string lang-alt into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(values); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } QString KExiv2::getXmpTagStringLangAlt(const char* xmpTagName, const QString& langAlt, bool escapeCR) const { #ifdef _XMP_SUPPORT_ try { Exiv2::XmpData xmpData(d->xmpMetadata()); Exiv2::XmpKey key(xmpTagName); for (Exiv2::XmpData::iterator it = xmpData.begin(); it != xmpData.end(); ++it) { if (it->key() == xmpTagName && it->typeId() == Exiv2::langAlt) { for (int i = 0; i < it->count(); i++) { std::ostringstream os; os << it->toString(i); QString lang; QString tagValue = QString::fromUtf8(os.str().c_str()); tagValue = detectLanguageAlt(tagValue, lang); if (langAlt == lang) { if (escapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return tagValue; } } } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Xmp key '%1' into image using Exiv2 ").arg(QString::fromLatin1(xmpTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(langAlt); Q_UNUSED(escapeCR); #endif // _XMP_SUPPORT_ return QString(); } bool KExiv2::setXmpTagStringLangAlt(const char* xmpTagName, const QString& value, const QString& langAlt, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { QString language(QString::fromLatin1("x-default")); // default alternative language. if (!langAlt.isEmpty()) language = langAlt; QString txtLangAlt = QString(QString::fromLatin1("lang=%1 %2")).arg(language).arg(value); const std::string &txt(txtLangAlt.toUtf8().constData()); #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr xmpTxtVal = Exiv2::Value::create(Exiv2::langAlt); #else Exiv2::Value::AutoPtr xmpTxtVal = Exiv2::Value::create(Exiv2::langAlt); #endif // Search if an Xmp tag already exist. AltLangMap map = getXmpTagStringListLangAlt(xmpTagName, false); if (!map.isEmpty()) { for (AltLangMap::iterator it = map.begin(); it != map.end(); ++it) { if (it.key() != langAlt) { const std::string &val((*it).toUtf8().constData()); xmpTxtVal->read(val); qCDebug(LIBKEXIV2_LOG) << *it; } } } xmpTxtVal->read(txt); removeXmpTag(xmpTagName); d->xmpMetadata().add(Exiv2::XmpKey(xmpTagName), xmpTxtVal.get()); return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp tag string lang-alt into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(value); Q_UNUSED(langAlt); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } QStringList KExiv2::getXmpTagStringSeq(const char* xmpTagName, bool escapeCR) const { #ifdef _XMP_SUPPORT_ try { Exiv2::XmpData xmpData(d->xmpMetadata()); Exiv2::XmpKey key(xmpTagName); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { if (it->typeId() == Exiv2::xmpSeq) { QStringList seq; for (int i = 0; i < it->count(); i++) { std::ostringstream os; os << it->toString(i); QString seqValue = QString::fromUtf8(os.str().c_str()); if (escapeCR) seqValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); seq.append(seqValue); } qCDebug(LIBKEXIV2_LOG) << "XMP String Seq (" << xmpTagName << "): " << seq; return seq; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Xmp key '%1' into image using Exiv2 ").arg(QString::fromLatin1(xmpTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(escapeCR); #endif // _XMP_SUPPORT_ return QStringList(); } bool KExiv2::setXmpTagStringSeq(const char* xmpTagName, const QStringList& seq, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { if (seq.isEmpty()) { removeXmpTag(xmpTagName); } else { const QStringList list = seq; #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr xmpTxtSeq = Exiv2::Value::create(Exiv2::xmpSeq); #else Exiv2::Value::AutoPtr xmpTxtSeq = Exiv2::Value::create(Exiv2::xmpSeq); #endif for (QStringList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it ) { const std::string &txt((*it).toUtf8().constData()); xmpTxtSeq->read(txt); } d->xmpMetadata()[xmpTagName].setValue(xmpTxtSeq.get()); } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp tag string Seq into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(seq); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } QStringList KExiv2::getXmpTagStringBag(const char* xmpTagName, bool escapeCR) const { #ifdef _XMP_SUPPORT_ try { Exiv2::XmpData xmpData(d->xmpMetadata()); Exiv2::XmpKey key(xmpTagName); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { if (it->typeId() == Exiv2::xmpBag) { QStringList bag; for (int i = 0; i < it->count(); i++) { std::ostringstream os; os << it->toString(i); QString bagValue = QString::fromUtf8(os.str().c_str()); if (escapeCR) bagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); bag.append(bagValue); } return bag; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Xmp key '%1' into image using Exiv2 ").arg(QString::fromLatin1(xmpTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(escapeCR); #endif // _XMP_SUPPORT_ return QStringList(); } bool KExiv2::setXmpTagStringBag(const char* xmpTagName, const QStringList& bag, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { if (bag.isEmpty()) { removeXmpTag(xmpTagName); } else { QStringList list = bag; #if EXIV2_TEST_VERSION(0,28,0) Exiv2::Value::UniquePtr xmpTxtBag = Exiv2::Value::create(Exiv2::xmpBag); #else Exiv2::Value::AutoPtr xmpTxtBag = Exiv2::Value::create(Exiv2::xmpBag); #endif for (QStringList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it ) { const std::string &txt((*it).toUtf8().constData()); xmpTxtBag->read(txt); } d->xmpMetadata()[xmpTagName].setValue(xmpTxtBag.get()); } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Xmp tag string Bag into image using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(bag); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } bool KExiv2::addToXmpTagStringBag(const char* xmpTagName, const QStringList& entriesToAdd, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; QStringList oldEntries = getXmpTagStringBag(xmpTagName, false); QStringList newEntries = entriesToAdd; // Create a list of keywords including old one which already exists. for (QStringList::const_iterator it = oldEntries.constBegin(); it != oldEntries.constEnd(); ++it ) { if (!newEntries.contains(*it)) newEntries.append(*it); } if (setXmpTagStringBag(xmpTagName, newEntries, false)) return true; return false; } bool KExiv2::removeFromXmpTagStringBag(const char* xmpTagName, const QStringList& entriesToRemove, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; QStringList currentEntries = getXmpTagStringBag(xmpTagName, false); QStringList newEntries; // Create a list of current keywords except those that shall be removed for (QStringList::const_iterator it = currentEntries.constBegin(); it != currentEntries.constEnd(); ++it ) { if (!entriesToRemove.contains(*it)) newEntries.append(*it); } if (setXmpTagStringBag(xmpTagName, newEntries, false)) return true; return false; } QVariant KExiv2::getXmpTagVariant(const char* xmpTagName, bool rationalAsListOfInts, bool stringEscapeCR) const { #ifdef _XMP_SUPPORT_ try { Exiv2::XmpData xmpData(d->xmpMetadata()); Exiv2::XmpKey key(xmpTagName); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { switch (it->typeId()) { case Exiv2::unsignedByte: case Exiv2::unsignedShort: case Exiv2::unsignedLong: case Exiv2::signedShort: case Exiv2::signedLong: #if EXIV2_TEST_VERSION(0,28,0) return QVariant((int)it->toUint32()); #else return QVariant((int)it->toLong()); #endif case Exiv2::unsignedRational: case Exiv2::signedRational: if (rationalAsListOfInts) { QList<QVariant> list; list << (*it).toRational().first; list << (*it).toRational().second; return QVariant(list); } else { // prefer double precision double num = (*it).toRational().first; double den = (*it).toRational().second; if (den == 0.0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) return QVariant(QMetaType(QMetaType::Double)); #else return QVariant(QVariant::Double); #endif return QVariant(num / den); } case Exiv2::date: case Exiv2::time: { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); return QVariant(dateTime); } case Exiv2::asciiString: case Exiv2::comment: case Exiv2::string: { std::ostringstream os; os << *it; QString tagValue = QString::fromLocal8Bit(os.str().c_str()); if (stringEscapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return QVariant(tagValue); } case Exiv2::xmpText: { std::ostringstream os; os << *it; QString tagValue = QString::fromUtf8(os.str().c_str()); if (stringEscapeCR) tagValue.replace(QString::fromLatin1("\n"), QString::fromLatin1(" ")); return tagValue; } case Exiv2::xmpBag: case Exiv2::xmpSeq: case Exiv2::xmpAlt: { QStringList list; for (int i=0; i < it->count(); i++) { list << QString::fromUtf8(it->toString(i).c_str()); } return list; } case Exiv2::langAlt: { // access the value directly const Exiv2::LangAltValue &value = static_cast<const Exiv2::LangAltValue &>(it->value()); QMap<QString, QVariant> map; // access the ValueType std::map< std::string, std::string> Exiv2::LangAltValue::ValueType::const_iterator i; for (i = value.value_.begin(); i != value.value_.end(); ++i) { map[QString::fromUtf8(i->first.c_str())] = QString::fromUtf8(i->second.c_str()); } return map; } default: break; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot find Xmp key '%1' into image using Exiv2 ").arg(QString::fromLatin1(xmpTagName)), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(rationalAsListOfInts); Q_UNUSED(stringEscapeCR); #endif // _XMP_SUPPORT_ return QVariant(); } bool KExiv2::registerXmpNameSpace(const QString& uri, const QString& prefix) { #ifdef _XMP_SUPPORT_ try { QString ns = uri; if (!uri.endsWith(QString::fromLatin1("/"))) ns.append(QString::fromLatin1("/")); Exiv2::XmpProperties::registerNs(ns.toLatin1().constData(), prefix.toLatin1().constData()); return true; } catch( Exiv2::Error& e ) { KExiv2Private::printExiv2ExceptionError(QString::fromLatin1("Cannot register a new Xmp namespace using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(uri); Q_UNUSED(prefix); #endif // _XMP_SUPPORT_ return false; } bool KExiv2::unregisterXmpNameSpace(const QString& uri) { #ifdef _XMP_SUPPORT_ try { QString ns = uri; if (!uri.endsWith(QString::fromLatin1("/"))) ns.append(QString::fromLatin1("/")); Exiv2::XmpProperties::unregisterNs(ns.toLatin1().constData()); return true; } catch( Exiv2::Error& e ) { KExiv2Private::printExiv2ExceptionError(QString::fromLatin1("Cannot unregister a new Xmp namespace using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(uri); #endif // _XMP_SUPPORT_ return false; } bool KExiv2::removeXmpTag(const char* xmpTagName, bool setProgramName) const { #ifdef _XMP_SUPPORT_ if (!setProgramId(setProgramName)) return false; try { Exiv2::XmpKey xmpKey(xmpTagName); Exiv2::XmpData::iterator it = d->xmpMetadata().findKey(xmpKey); if (it != d->xmpMetadata().end()) { d->xmpMetadata().erase(it); return true; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot remove Xmp tag using Exiv2 "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #else Q_UNUSED(xmpTagName); Q_UNUSED(setProgramName); #endif // _XMP_SUPPORT_ return false; } QStringList KExiv2::getXmpKeywords() const { return (getXmpTagStringBag("Xmp.dc.subject", false)); } bool KExiv2::setXmpKeywords(const QStringList& newKeywords, bool setProgramName) const { return addToXmpTagStringBag("Xmp.dc.subject", newKeywords, setProgramName); } bool KExiv2::removeXmpKeywords(const QStringList& keywordsToRemove, bool setProgramName) { return removeFromXmpTagStringBag("Xmp.dc.subject", keywordsToRemove, setProgramName); } QStringList KExiv2::getXmpSubCategories() const { return (getXmpTagStringBag("Xmp.photoshop.SupplementalCategories", false)); } bool KExiv2::setXmpSubCategories(const QStringList& newSubCategories, bool setProgramName) const { return addToXmpTagStringBag("Xmp.photoshop.SupplementalCategories", newSubCategories, setProgramName); } bool KExiv2::removeXmpSubCategories(const QStringList& subCategoriesToRemove, bool setProgramName) { return removeFromXmpTagStringBag("Xmp.photoshop.SupplementalCategories", subCategoriesToRemove, setProgramName); } QStringList KExiv2::getXmpSubjects() const { return (getXmpTagStringBag("Xmp.iptc.SubjectCode", false)); } bool KExiv2::setXmpSubjects(const QStringList& newSubjects, bool setProgramName) const { return addToXmpTagStringBag("Xmp.iptc.SubjectCode", newSubjects, setProgramName); } bool KExiv2::removeXmpSubjects(const QStringList& subjectsToRemove, bool setProgramName) { return removeFromXmpTagStringBag("Xmp.iptc.SubjectCode", subjectsToRemove, setProgramName); } KExiv2::TagsMap KExiv2::getXmpTagsList() const { TagsMap tagsMap; d->getXMPTagsListFromPrefix(QString::fromLatin1("dc"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("digiKam"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("xmp"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("xmpRights"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("xmpMM"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("xmpBJ"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("xmpTPg"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("xmpDM"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("MicrosoftPhoto"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("pdf"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("photoshop"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("crs"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("tiff"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("exif"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("aux"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("iptc"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("iptcExt"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("plus"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("mwg-rs"), tagsMap); d->getXMPTagsListFromPrefix(QString::fromLatin1("dwc"), tagsMap); return tagsMap; } } // NameSpace KExiv2Iface 07070100000021000081A400000000000000000000000166279585000024B6000000000000000000000000000000000000004400000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/rotationmatrix.cpp/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2004-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ // Local includes #include "rotationmatrix.h" namespace KExiv2Iface { /** If the picture is displayed according to the exif orientation tag, the user will request rotating operations relative to what he sees, and that is the picture rotated according to the EXIF tag. So the operation requested and the given EXIF angle must be combined. E.g. if orientation is "6" (rotate 90 clockwiseto show correctly) and the user selects 180 clockwise, the operation is 270. If the user selected 270, the operation would be None (and clearing the exif tag). This requires to describe the transformations in a model which cares for both composing (180+90=270) and eliminating (180+180=no action), as well as the non-commutative nature of the operations (vflip+90 is not 90+vflip) All 2D transformations can be described by a 2x3 matrix, see QWRotationMatrix. All transformations needed here - rotate 90, 180, 270, flipV, flipH - can be described in a 2x2 matrix with the values 0,1,-1 (because flipping is expressed by changing the sign only, and sine and cosine of 90, 180 and 270 are either 0,1 or -1). x' = m11 x + m12 y y' = m21 x + m22 y Moreover, all combinations of these rotate/flip operations result in one of the eight matrices defined below. (I did not proof that mathematically, but empirically) static const RotationMatrix identity; //( 1, 0, 0, 1) static const RotationMatrix rotate90; //( 0, 1, -1, 0) static const RotationMatrix rotate180; //(-1, 0, 0, -1) static const RotationMatrix rotate270; //( 0, -1, 1, 0) static const RotationMatrix flipHorizontal; //(-1, 0, 0, 1) static const RotationMatrix flipVertical; //( 1, 0, 0, -1) static const RotationMatrix rotate90flipHorizontal; //( 0, 1, 1, 0), first rotate, then flip static const RotationMatrix rotate90flipVertical; //( 0, -1, -1, 0), first rotate, then flip */ namespace Matrix { static const RotationMatrix identity ( 1, 0, 0, 1); static const RotationMatrix rotate90 ( 0, 1, -1, 0); static const RotationMatrix rotate180 (-1, 0, 0, -1); static const RotationMatrix rotate270 ( 0, -1, 1, 0); static const RotationMatrix flipHorizontal (-1, 0, 0, 1); static const RotationMatrix flipVertical ( 1, 0, 0, -1); static const RotationMatrix rotate90flipHorizontal ( 0, 1, 1, 0); static const RotationMatrix rotate90flipVertical ( 0, -1, -1, 0); RotationMatrix matrix(RotationMatrix::TransformationAction action) { switch (action) { case RotationMatrix::NoTransformation: return identity; case RotationMatrix::FlipHorizontal: return flipHorizontal; case RotationMatrix::FlipVertical: return flipVertical; case RotationMatrix::Rotate90: return rotate90; case RotationMatrix::Rotate180: return rotate180; case RotationMatrix::Rotate270: return rotate270; } return identity; } RotationMatrix matrix(KExiv2::ImageOrientation exifOrientation) { switch (exifOrientation) { case KExiv2::ORIENTATION_NORMAL: return identity; case KExiv2::ORIENTATION_HFLIP: return flipHorizontal; case KExiv2::ORIENTATION_ROT_180: return rotate180; case KExiv2::ORIENTATION_VFLIP: return flipVertical; case KExiv2::ORIENTATION_ROT_90_HFLIP: return rotate90flipHorizontal; case KExiv2::ORIENTATION_ROT_90: return rotate90; case KExiv2::ORIENTATION_ROT_90_VFLIP: return rotate90flipVertical; case KExiv2::ORIENTATION_ROT_270: return rotate270; case KExiv2::ORIENTATION_UNSPECIFIED: return identity; } return identity; } } // namespace Matrix RotationMatrix::RotationMatrix() { set( 1, 0, 0, 1 ); } RotationMatrix::RotationMatrix(TransformationAction action) { *this = Matrix::matrix(action); } RotationMatrix::RotationMatrix(KExiv2::ImageOrientation exifOrientation) { *this = Matrix::matrix(exifOrientation); } RotationMatrix::RotationMatrix(int m11, int m12, int m21, int m22) { set(m11, m12, m21, m22); } void RotationMatrix::set(int m11, int m12, int m21, int m22) { m[0][0]=m11; m[0][1]=m12; m[1][0]=m21; m[1][1]=m22; } bool RotationMatrix::isNoTransform() const { return (*this == Matrix::identity); } RotationMatrix& RotationMatrix::operator*=(const RotationMatrix& ma) { set( ma.m[0][0]*m[0][0] + ma.m[0][1]*m[1][0], ma.m[0][0]*m[0][1] + ma.m[0][1]*m[1][1], ma.m[1][0]*m[0][0] + ma.m[1][1]*m[1][0], ma.m[1][0]*m[0][1] + ma.m[1][1]*m[1][1] ); return *this; } bool RotationMatrix::operator==(const RotationMatrix& ma) const { return m[0][0]==ma.m[0][0] && m[0][1]==ma.m[0][1] && m[1][0]==ma.m[1][0] && m[1][1]==ma.m[1][1]; } bool RotationMatrix::operator!=(const RotationMatrix& ma) const { return !(*this==ma); } RotationMatrix& RotationMatrix::operator*=(TransformationAction action) { return (*this *= Matrix::matrix(action)); } RotationMatrix& RotationMatrix::operator*=(QList<TransformationAction> actions) { for (const TransformationAction& action : qAsConst(actions)) { *this *= Matrix::matrix(action); } return *this; } RotationMatrix& RotationMatrix::operator*=(KExiv2::ImageOrientation exifOrientation) { return (*this *= Matrix::matrix(exifOrientation)); } /** Converts the mathematically correct description into the primitive operations that can be carried out losslessly. */ QList<RotationMatrix::TransformationAction> RotationMatrix::transformations() const { QList<TransformationAction> transforms; if (*this == Matrix::rotate90) { transforms << Rotate90; } else if (*this == Matrix::rotate180) { transforms << Rotate180; } else if (*this == Matrix::rotate270) { transforms << Rotate270; } else if (*this == Matrix::flipHorizontal) { transforms << FlipHorizontal; } else if (*this == Matrix::flipVertical) { transforms << FlipVertical; } else if (*this == Matrix::rotate90flipHorizontal) { //first rotate, then flip! transforms << Rotate90; transforms << FlipHorizontal; } else if (*this == Matrix::rotate90flipVertical) { //first rotate, then flip! transforms << Rotate90; transforms << FlipVertical; } return transforms; } KExiv2::ImageOrientation RotationMatrix::exifOrientation() const { if (*this == Matrix::identity) { return KExiv2::ORIENTATION_NORMAL; } if (*this == Matrix::rotate90) { return KExiv2::ORIENTATION_ROT_90; } else if (*this == Matrix::rotate180) { return KExiv2::ORIENTATION_ROT_180; } else if (*this == Matrix::rotate270) { return KExiv2::ORIENTATION_ROT_270; } else if (*this == Matrix::flipHorizontal) { return KExiv2::ORIENTATION_HFLIP; } else if (*this == Matrix::flipVertical) { return KExiv2::ORIENTATION_VFLIP; } else if (*this == Matrix::rotate90flipHorizontal) { return KExiv2::ORIENTATION_ROT_90_HFLIP; } else if (*this == Matrix::rotate90flipVertical) { return KExiv2::ORIENTATION_ROT_90_VFLIP; } return KExiv2::ORIENTATION_UNSPECIFIED; } QTransform RotationMatrix::toTransform() const { return toTransform(exifOrientation()); } QTransform RotationMatrix::toTransform(KExiv2::ImageOrientation orientation) { QTransform matrix; switch (orientation) { case KExiv2::ORIENTATION_NORMAL: case KExiv2::ORIENTATION_UNSPECIFIED: break; case KExiv2::ORIENTATION_HFLIP: matrix.scale(-1, 1); break; case KExiv2::ORIENTATION_ROT_180: matrix.rotate(180); break; case KExiv2::ORIENTATION_VFLIP: matrix.scale(1, -1); break; case KExiv2::ORIENTATION_ROT_90_HFLIP: matrix.scale(-1, 1); matrix.rotate(90); break; case KExiv2::ORIENTATION_ROT_90: matrix.rotate(90); break; case KExiv2::ORIENTATION_ROT_90_VFLIP: matrix.scale(1, -1); matrix.rotate(90); break; case KExiv2::ORIENTATION_ROT_270: matrix.rotate(270); break; } return matrix; } #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #if KEXIV2_BUILD_DEPRECATED_SINCE(5, 1) QMatrix RotationMatrix::toMatrix() const { return toMatrix(exifOrientation()); } #endif #endif #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #if KEXIV2_BUILD_DEPRECATED_SINCE(5, 1) QMatrix RotationMatrix::toMatrix(KExiv2::ImageOrientation orientation) { return toTransform(orientation).toAffine(); } #endif #endif } // namespace KExiv2Iface 07070100000022000081A40000000000000000000000016627958500000FEB000000000000000000000000000000000000004200000000libkexiv2-VERSIONgit.20240423T130333~354ff39/src/rotationmatrix.h/* SPDX-FileCopyrightText: 2006-2015 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-FileCopyrightText: 2004-2012 Marcel Wiesweg <marcel dot wiesweg at gmx dot de> SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef LIBKEXIV2_ROTATIONMATRIX_H #define LIBKEXIV2_ROTATIONMATRIX_H // Local includes #include "kexiv2.h" #include "libkexiv2_export.h" // Qt includes #include <QtGlobal> #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #if KEXIV2_ENABLE_DEPRECATED_SINCE(5, 1) #include <QMatrix> #endif #endif #include <QTransform> namespace KExiv2Iface { /** * @class RotationMatrix rotationmatrix.h <KExiv2/RotationMatrix> * * RotationMatrix */ class LIBKEXIV2_EXPORT RotationMatrix { public: /** This describes single transform primitives. * Note some of the defined Exif rotation flags combine * two of these actions. * The enum values correspond to those defined * as JXFORM_CODE in the often used the JPEG tool transupp.h. */ enum TransformationAction { NoTransformation = 0, /// no transformation FlipHorizontal = 1, /// horizontal flip FlipVertical = 2, /// vertical flip Rotate90 = 5, /// 90-degree clockwise rotation Rotate180 = 6, /// 180-degree rotation Rotate270 = 7 /// 270-degree clockwise (or 90 ccw) }; public: /// Constructs the identity matrix (the matrix describing no transformation) RotationMatrix(); /// Returns the matrix corresponding to the given TransformationAction RotationMatrix(TransformationAction action); /// Returns the matrix corresponding to the given TransformationAction RotationMatrix(KExiv2::ImageOrientation exifOrientation); bool operator==(const RotationMatrix& ma) const; bool operator!=(const RotationMatrix& ma) const; /// Returns true of this matrix describes no transformation (is the identity matrix) bool isNoTransform() const; RotationMatrix& operator*=(const RotationMatrix& ma); /// Applies the given transform to this matrix RotationMatrix& operator*=(TransformationAction action); /// Applies the given transform actions to this matrix RotationMatrix& operator*=(QList<TransformationAction> actions); /// Applies the given Exif orientation flag to this matrix RotationMatrix& operator*=(KExiv2::ImageOrientation exifOrientation); /** Returns the actions described by this matrix. The order matters. * Not all possible matrices are supported, but all those that can be combined * by Exif rotation flags and the transform actions above. * If isNoTransform() or the matrix is not supported returns an empty list. */ QList<TransformationAction> transformations() const; /** Returns the Exif orienation flag describing this matrix. * Returns ORIENTATION_UNSPECIFIED if no flag matches this matrix. */ KExiv2::ImageOrientation exifOrientation() const; /** * Returns a QTransform representing this matrix * @since 5.1 */ QTransform toTransform() const; /** * Returns a QTransform for the given Exif orientation * @since 5.1 */ static QTransform toTransform(KExiv2::ImageOrientation orientation); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #if KEXIV2_ENABLE_DEPRECATED_SINCE(5, 1) /// Returns a QMatrix representing this matrix /// @deprecated Since 5.1, use toTransform(). KEXIV2_DEPRECATED_VERSION(5, 1, "Use toTransform()") QMatrix toMatrix() const; #endif #endif #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #if KEXIV2_ENABLE_DEPRECATED_SINCE(5, 1) /// Returns a QMatrix for the given Exif orientation KEXIV2_DEPRECATED_VERSION(5, 1, "Use toTransform(KExiv2::ImageOrientation)") static QMatrix toMatrix(KExiv2::ImageOrientation orientation); #endif #endif RotationMatrix(int m11, int m12, int m21, int m22); protected: void set(int m11, int m12, int m21, int m22); protected: int m[2][2]; }; } // namespace KExiv2Iface #endif // LIBKEXIV2_ROTATIONMATRIX_H 07070100000023000041ED0000000000000000000000026627958500000000000000000000000000000000000000000000003300000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests07070100000024000081A40000000000000000000000016627958500000420000000000000000000000000000000000000004200000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/CMakeLists.txt# # SPDX-FileCopyrightText: 2010-2014 Gilles Caulier <caulier dot gilles at gmail dot com> # # SPDX-License-Identifier: BSD-3-Clause # add_executable(setiptcpreview) target_sources(setiptcpreview PRIVATE setiptcpreview.cpp) target_link_libraries(setiptcpreview KExiv2) add_executable(loadfromba) target_sources(loadfromba PRIVATE loadfromba.cpp) target_link_libraries(loadfromba KExiv2) add_executable(erasetag) target_sources(erasetag PRIVATE erasetag.cpp) target_link_libraries(erasetag KExiv2) add_executable(printtagslist) target_sources(printtagslist PRIVATE printtagslist.cpp) target_link_libraries(printtagslist KExiv2) add_executable(usexmpsidecar) target_sources(usexmpsidecar PRIVATE usexmpsidecar.cpp) target_link_libraries(usexmpsidecar KExiv2) add_executable(readimagewritexmpsidecar) target_sources(readimagewritexmpsidecar PRIVATE readimagewritexmpsidecar.cpp) target_link_libraries(readimagewritexmpsidecar KExiv2) add_executable(setxmpface) target_sources(setxmpface PRIVATE setxmpface.cpp) target_link_libraries(setxmpface KExiv2) 07070100000025000081A400000000000000000000000166279585000003D9000000000000000000000000000000000000004000000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/erasetag.cpp/* A command line tool to tag from photo SPDX-FileCopyrightText: 2009-2012 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QString> #include <QFile> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; int main (int argc, char **argv) { if(argc != 2) { qDebug() << "erasetag - erase tag from from image"; qDebug() << "Usage: <image>"; return -1; } QString filePath = QString::fromLocal8Bit(argv[1]); KExiv2 meta; meta.load(filePath); meta.setWriteRawFiles(true); bool b = meta.removeExifTag("Exif.OlympusIp.BlackLevel", false); qDebug() << "Exif.OlympusIp.BlackLevel found = " << b; QByteArray ba = meta.getExifTagData("Exif.OlympusIp.BlackLevel"); qDebug() << "Exif.OlympusIp.BlackLevel removed = " << ba.isEmpty(); if (b) { meta.applyChanges(); } return 0; } 07070100000026000081A4000000000000000000000001662795850000043A000000000000000000000000000000000000004200000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/loadfromba.cpp/* A command line tool to load metadata from byte array SPDX-FileCopyrightText: 2009-2012 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QDataStream> #include <QImage> #include <QString> #include <QFile> #include <QByteArray> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; int main (int argc, char **argv) { if(argc != 2) { qDebug() << "loadfromba - test to load metadata from image as byte array"; qDebug() << "Usage: <image>"; return -1; } QString filePath = QString::fromLocal8Bit(argv[1]); QString baFile(QStringLiteral("ba.dat")); QImage image(filePath); image.save(baFile, "PNG"); QFile file(baFile); if ( !file.open(QIODevice::ReadOnly) ) return false; QByteArray data; data.resize(file.size()); QDataStream stream( &file ); stream.readRawData(data.data(), data.size()); file.close(); KExiv2 meta; meta.loadFromData(data); return 0; } 07070100000027000081A40000000000000000000000016627958500000A54000000000000000000000000000000000000004500000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/printtagslist.cpp/* A command line tool to print all tags list supported by Exiv2 SPDX-FileCopyrightText: 2009-2012 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QStringList> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; int main (int /*argc*/, char** /*argv*/) { KExiv2 meta; qDebug() << "-- Standard Exif Tags -------------------------------------------------------------"; KExiv2::TagsMap exiftags = meta.getStdExifTagsList(); for (KExiv2::TagsMap::const_iterator it = exiftags.constBegin(); it != exiftags.constEnd(); ++it ) { QString key = it.key(); QStringList values = it.value(); QString name = values[0]; QString title = values[1]; QString desc = values[2]; qDebug() << key << " :: " << name << " :: " << title << " :: " << desc; } qDebug() << "-- Makernote Tags -----------------------------------------------------------------"; KExiv2::TagsMap mntags = meta.getMakernoteTagsList(); for (KExiv2::TagsMap::const_iterator it = mntags.constBegin(); it != mntags.constEnd(); ++it ) { QString key = it.key(); QStringList values = it.value(); QString name = values[0]; QString title = values[1]; QString desc = values[2]; qDebug() << key << " :: " << name << " :: " << title << " :: " << desc; } qDebug() << "-- Standard Iptc Tags -----------------------------------------------------------------"; KExiv2::TagsMap iptctags = meta.getIptcTagsList(); for (KExiv2::TagsMap::const_iterator it = iptctags.constBegin(); it != iptctags.constEnd(); ++it ) { QString key = it.key(); QStringList values = it.value(); QString name = values[0]; QString title = values[1]; QString desc = values[2]; qDebug() << key << " :: " << name << " :: " << title << " :: " << desc; } qDebug() << "-- Standard Xmp Tags -----------------------------------------------------------------"; KExiv2::TagsMap xmptags = meta.getXmpTagsList(); for (KExiv2::TagsMap::const_iterator it = xmptags.constBegin(); it != xmptags.constEnd(); ++it ) { QString key = it.key(); QStringList values = it.value(); QString name = values[0]; QString title = values[1]; QString desc = values[2]; qDebug() << key << " :: " << name << " :: " << title << " :: " << desc; } return 0; } 07070100000028000081A40000000000000000000000016627958500000340000000000000000000000000000000000000005000000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/readimagewritexmpsidecar.cpp/* A command line tool to test XMP sidecar functionality SPDX-FileCopyrightText: 2010 Jakob Malm <jakob dot malm at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QString> #include <QFile> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; int main (int argc, char **argv) { if(argc != 2) { qDebug() << "readimagewritecmpsidecar - read metadata from image and write to XMP sidecar"; qDebug() << "Usage: <image>"; return -1; } QString filePath = QString::fromLocal8Bit(argv[1]); KExiv2 meta; // Read metadata from the image meta.load(filePath); // Write metadata to XMP sidecar meta.setMetadataWritingMode(KExiv2::WRITETOSIDECARONLY); meta.save(filePath); return 0; } 07070100000029000081A4000000000000000000000001662795850000054C000000000000000000000000000000000000004600000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/setiptcpreview.cpp/* A command line tool to set IPTC Preview SPDX-FileCopyrightText: 2009-2012 Gilles Caulier <caulier dot gilles at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QTransform> #include <QImage> #include <QString> #include <QFile> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; int main (int argc, char **argv) { if (argc != 2) { qDebug() << "setiptcpreview - update/add jpeg iptc preview to image"; qDebug() << "Usage: <image>"; return -1; } QImage preview; QString filePath = QString::fromLocal8Bit(argv[1]); KExiv2 meta(filePath); QImage image(filePath); QTransform matrix; matrix.rotate(90); image = image.transformed(matrix); QSize previewSize = image.size(); previewSize.scale(1280, 1024, Qt::KeepAspectRatio); // Ensure that preview is not upscaled if (previewSize.width() >= (int)image.width()) preview = image.copy(); else preview = image.scaled(previewSize.width(), previewSize.height(), Qt::IgnoreAspectRatio).copy(); meta.setImagePreview(preview); meta.applyChanges(); QImage preview2; KExiv2 meta2(filePath); meta2.getImagePreview(preview2); preview2.save(QString::fromLatin1("preview.png"), "PNG"); return 0; } 0707010000002A000081A40000000000000000000000016627958500001AA2000000000000000000000000000000000000004200000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/setxmpface.cpp/* A command line tool to set faces in Picassa format SPDX-FileCopyrightText: 2013 Munteanu Veaceslav <slavuttici at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QString> #include <QFile> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; bool setFaceTags(KExiv2& meta,const char* xmpTagName,const QMap<QString,QRectF>& faces, bool setProgramName) { Q_UNUSED(setProgramName); meta.setXmpTagString(xmpTagName,QString(),KExiv2::XmpTagType(1),false); QString qxmpTagName(QString::fromLatin1(xmpTagName)); QString nameTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Name"); QString typeTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Type"); QString areaTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area"); QString areaxTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:x"); QString areayTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:y"); QString areawTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:w"); QString areahTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:h"); QString areanormTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:unit"); QMap<QString,QRectF>::const_iterator it = faces.constBegin(); int i =1; while(it != faces.constEnd()) { qreal x,y,w,h; it.value().getRect(&x,&y,&w,&h); /** Set tag name **/ meta.setXmpTagString(nameTagKey.arg(i).toLatin1().constData(),it.key(), KExiv2::XmpTagType(0),false); /** Set tag type as Face **/ meta.setXmpTagString(typeTagKey.arg(i).toLatin1().constData(),QString::fromLatin1("Face"), KExiv2::XmpTagType(0),false); /** Set tag Area, with xmp type struct **/ meta.setXmpTagString(areaTagKey.arg(i).toLatin1().constData(),QString(), KExiv2::XmpTagType(2),false); /** Set stArea:x inside Area structure **/ meta.setXmpTagString(areaxTagKey.arg(i).toLatin1().constData(),QString::number(x), KExiv2::XmpTagType(0),false); /** Set stArea:y inside Area structure **/ meta.setXmpTagString(areayTagKey.arg(i).toLatin1().constData(),QString::number(y), KExiv2::XmpTagType(0),false); /** Set stArea:w inside Area structure **/ meta.setXmpTagString(areawTagKey.arg(i).toLatin1().constData(),QString::number(w), KExiv2::XmpTagType(0),false); /** Set stArea:h inside Area structure **/ meta.setXmpTagString(areahTagKey.arg(i).toLatin1().constData(),QString::number(h), KExiv2::XmpTagType(0),false); /** Set stArea:unit inside Area structure as normalized **/ meta.setXmpTagString(areanormTagKey.arg(i).toLatin1().constData(),QString::fromLatin1("normalized"), KExiv2::XmpTagType(0),false); ++it; ++i; } return true; } void removeFaceTags(KExiv2& meta,const char* xmpTagName) { QString qxmpTagName(QString::fromLatin1(xmpTagName)); QString regionTagKey = qxmpTagName + QString::fromLatin1("[%1]"); QString nameTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Name"); QString typeTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Type"); QString areaTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area"); QString areaxTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:x"); QString areayTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:y"); QString areawTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:w"); QString areahTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:h"); QString areanormTagKey = qxmpTagName + QString::fromLatin1("[%1]/mwg-rs:Area/stArea:unit"); meta.removeXmpTag(xmpTagName,false); bool dirty = true; int i =1; while(dirty) { dirty = false; dirty |=meta.removeXmpTag(regionTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(nameTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(typeTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(areaTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(areaxTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(areayTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(areawTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(areahTagKey.arg(i).toLatin1().constData(),false); dirty |=meta.removeXmpTag(areanormTagKey.arg(i).toLatin1().constData(),false); i++; } } int main (int argc, char **argv) { if (argc != 3) { qDebug() << "Adding a face rectangle to image"; qDebug() << "Usage: <add/remove> <image>"; return -1; } QString filePath(QString::fromLatin1(argv[2])); KExiv2Iface::KExiv2::initializeExiv2(); KExiv2 meta; meta.load(filePath); meta.setWriteRawFiles(true); /** Add a random rectangle with facetag Bob **/ QString name = QString::fromLatin1("Bob Marley"); float x =0.5; float y =0.5; float w = 60; float h = 60; QRectF rect(x,y,w,h); QMap<QString, QRectF> faces; faces[name] = rect; QString name2 = QString::fromLatin1("Hello Kitty!"); QRectF rect2(0.4,0.4,30,30); faces[name2] = rect2; bool g = meta.supportXmp(); qDebug() << "Image support XMP" << g; const QString bag = QString::fromLatin1("Xmp.mwg-rs.Regions/mwg-rs:RegionList"); QString op(QString::fromLatin1(argv[1])); if (op == QString::fromLatin1("add")) setFaceTags(meta,bag.toLatin1().constData(),faces,false); else removeFaceTags(meta,bag.toLatin1().constData()); meta.applyChanges(); QString recoverName = QString::fromLatin1("Xmp.mwg-rs.Regions/mwg-rs:RegionList[1]/mwg-rs:Name"); KExiv2 meta2; meta2.load(filePath); meta2.setWriteRawFiles(true); QString nameR = meta2.getXmpTagString(recoverName.toLatin1().constData(),false); qDebug() << "Saved name is:" << nameR; KExiv2Iface::KExiv2::cleanupExiv2(); return 0; } 0707010000002B000081A40000000000000000000000016627958500000346000000000000000000000000000000000000004500000000libkexiv2-VERSIONgit.20240423T130333~354ff39/tests/usexmpsidecar.cpp/* A command line tool to test XMP sidecar functionality SPDX-FileCopyrightText: 2010 Jakob Malm <jakob dot malm at gmail dot com> SPDX-License-Identifier: GPL-2.0-or-later */ // Qt includes #include <QString> #include <QFile> #include <QDebug> // Local includes #include "kexiv2.h" using namespace KExiv2Iface; int main (int argc, char **argv) { if(argc != 2) { qDebug() << "usexmpsidecar - read from and write to XMP sidecar"; qDebug() << "Usage: <image>"; return -1; } QString filePath(QString::fromLatin1(argv[1])); KExiv2 meta; meta.setUseXMPSidecar4Reading(true); meta.load(filePath); // print some metadata // add some metadata // write changed metadata // perhaps check to see if image file or XMP sidecar file was changed return 0; } 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!742 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor