diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..25963e5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,148 @@ +cmake_minimum_required(VERSION 3.5) + +set(PROJECT_NAME "Ghazal") +project(${PROJECT_NAME} VERSION 1.4 LANGUAGES C CXX) + +if(UNIX) + set(OUTPUT_FILE_NAME "ghazal") +else() + set(OUTPUT_FILE_NAME "Ghazal") +endif() + +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) + +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(QT NAMES Qt5 QUIET COMPONENTS Core) + +if(QT_FOUND) + set(QT_VERSION_MAJOR 5) +else() + find_package(QT NAMES Qt6 QUIET COMPONENTS Core) + if(QT_FOUND) + set(QT_VERSION_MAJOR 6) + else() + set(QT_VERSION_MAJOR 5) # If neither 5 nor 6 are found, we default to 5. The setup will fail further down. + endif() +endif() + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "" FORCE) +endif() + +if(QT_VERSION_MAJOR EQUAL 5) + find_package(Qt5 REQUIRED COMPONENTS Core Gui Widgets Sql Concurrent Xml Network) + if(UNIX) + set(QUAZIP_LIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/unix/quazip/libquazip1-qt5.so") + set(ZLIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/unix/quazip/libz.so") + elseif(WIN32) + set(QUAZIP_LIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/win/quazip/libquazip1-qt5.dll") + set(ZLIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/win/quazip/zlib1.dll") + endif() + set(GHAZAL_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Sql Qt5::Concurrent Qt5::Xml Qt5::Network ${QUAZIP_LIB}) +elseif(QT_VERSION_MAJOR EQUAL 6) + find_package(Qt6 REQUIRED COMPONENTS Core Core5Compat Gui Widgets Sql Concurrent Xml Network) + if(UNIX) + set(QUAZIP_LIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/unix/quazip/libquazip1-qt6.so") + set(ZLIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/unix/quazip/libz.so") + elseif(WIN32) + set(QUAZIP_LIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/win/quazip/libquazip1-qt6.dll") + set(ZLIB "${CMAKE_CURRENT_SOURCE_DIR}/libraries/win/quazip/zlib1.dll") + endif() + set(GHAZAL_LIBRARIES Qt6::Core Qt6::Core5Compat Qt6::Gui Qt6::Widgets Qt6::Sql Qt6::Concurrent Qt6::Xml Qt6::Network ${QUAZIP_LIB}) +endif() + +set(HEADERS + src/abjad_class.h + src/abjadform.h + src/abjadformmini.h + src/aboutauthorform.h + src/aboutform.h + src/appthemes.h + src/common_functions.h + src/databaseform.h + src/date_converter.h + src/downloadform.h + src/event_functions.h + src/filedownloader.h + src/mainwindow.h + src/searchexamplesform.h + src/searchform.h + src/settingsform.h + src/tabform.h + src/wordsearchform.h + src/worker.h +) + +set(SOURCES + src/abjad_class.cpp + src/abjadform.cpp + src/abjadformmini.cpp + src/aboutauthorform.cpp + src/aboutform.cpp + src/appthemes.cpp + src/common_functions.cpp + src/common_search.cpp + src/databaseform.cpp + src/date_converter.c + src/downloadform.cpp + src/event_functions.cpp + src/filedownloader.cpp + src/main.cpp + src/mainwindow.cpp + src/mainwindow_action_menu.cpp + src/mainwindow_app_setting.cpp + src/mainwindow_search_form.cpp + src/searchexamplesform.cpp + src/searchform.cpp + src/settingsform.cpp + src/tabform.cpp + src/tabform_context_menu.cpp + src/wordsearchform.cpp + src/worker.cpp +) + +set(FORMS + src/abjadform.ui + src/abjadformmini.ui + src/aboutauthorform.ui + src/aboutform.ui + src/databaseform.ui + src/downloadform.ui + src/mainwindow.ui + src/searchexamplesform.ui + src/searchform.ui + src/settingsform.ui + src/tabform.ui + src/wordsearchform.ui +) + +set(RESOURCES + resources/themes/darkstyle.qrc + resources/resource.qrc +) + +include_directories("${CMAKE_CURRENT_SOURCE_DIR}/libraries/include") + +if(WIN32 AND CMAKE_BUILD_TYPE STREQUAL "Release") + enable_language(RC) + set(APP_ICON_RESOURCE_WINDOWS "${CMAKE_CURRENT_SOURCE_DIR}/resources/resource_win.rc") + add_executable(${PROJECT_NAME} WIN32 ${HEADERS} ${SOURCES} ${FORMS} ${RESOURCES} ${APP_ICON_RESOURCE_WINDOWS}) +else() + add_executable(${PROJECT_NAME} ${HEADERS} ${SOURCES} ${FORMS} ${RESOURCES}) +endif() + +target_link_libraries(${PROJECT_NAME} ${GHAZAL_LIBRARIES}) + +set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME ${OUTPUT_FILE_NAME}) + +add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${QUAZIP_LIB} + ${ZLIB} + "${CMAKE_BINARY_DIR}") diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..492f7fd --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012-2022 Aboutaleb Roshan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..595d77b --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# Ghazal: The library of persian poetry +Ghazal is a library of persian poetry and a free and open-source software. Ghazal is written in C++ using the Qt framework. This software uses [Ganjoor](https://ganjoor.net) database. This branch here contains pre-built files for Windows and Linux ([AppImage](https://appimage.org)). Simply download the AppImage and run it on all linux distributions. + +## Building +Linux (cmake): +``` +cd ghazal-src-dir +cmake . -Bbuild +cd build +make +``` + +Linux (qmake): +``` +cd ghazal-src-dir +qmake ghazal.pro +make +``` + +Windows (cmake): +``` +cd ghazal-src-dir +cmake . -Bbuild -G"MinGW Makefiles" +cd build +mingw32-make +``` + +Windows (qmake): +``` +cd ghazal-src-dir +qmake ghazal.pro +mingw32-make +``` + +## PGP Public Key +Source and binary executables are signed with the following key: +- [abroshan39_PGP_public_key.asc](http://www.rosybit.com/abroshan39/abroshan39_PGP_public_key.asc) (Key ID: B0E5D23797D2D8CB) + +You can import the public key from the MIT PGP Public Key Server by running a command like: +``` +gpg --keyserver pgp.mit.edu --receive-keys B0E5D23797D2D8CB +``` + +## Authors +- Aboutaleb Roshan [@abroshan39](https://github.com/abroshan39) + +## License +Ghazal is licensed under MIT. See the `LICENSE` file. diff --git a/ghazal.pro b/ghazal.pro new file mode 100644 index 0000000..77151f5 --- /dev/null +++ b/ghazal.pro @@ -0,0 +1,100 @@ +QT += core gui widgets sql concurrent xml network + +greaterThan(QT_MAJOR_VERSION, 5): QT += core5compat + +CONFIG += c++11 + +# The following define makes your compiler emit warnings if you use +# any Qt feature that has been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +OUTPUT_FILE_NAME_UNIX = "ghazal" +OUTPUT_FILE_NAME_WIN = "Ghazal" +QUAZIP_LIB_NAME_UNIX = "quazip1-qt5" +QUAZIP_LIB_NAME_WIN = "quazip1-qt5" + +unix { + TARGET = $$OUTPUT_FILE_NAME_UNIX + LIBS += -L$$PWD/libraries/unix/quazip -l$$QUAZIP_LIB_NAME_UNIX +} + +win32 { + TARGET = $$OUTPUT_FILE_NAME_WIN + LIBS += -L$$PWD/libraries/win/quazip -l$$QUAZIP_LIB_NAME_WIN + RC_FILE = $$PWD/resources/resource_win.rc +} + +INCLUDEPATH += $$PWD/libraries/include + +HEADERS += \ + src/abjad_class.h \ + src/abjadform.h \ + src/abjadformmini.h \ + src/aboutauthorform.h \ + src/aboutform.h \ + src/appthemes.h \ + src/common_functions.h \ + src/databaseform.h \ + src/date_converter.h \ + src/downloadform.h \ + src/event_functions.h \ + src/filedownloader.h \ + src/mainwindow.h \ + src/searchexamplesform.h \ + src/searchform.h \ + src/settingsform.h \ + src/tabform.h \ + src/wordsearchform.h \ + src/worker.h + +SOURCES += \ + src/abjad_class.cpp \ + src/abjadform.cpp \ + src/abjadformmini.cpp \ + src/aboutauthorform.cpp \ + src/aboutform.cpp \ + src/appthemes.cpp \ + src/common_functions.cpp \ + src/common_search.cpp \ + src/databaseform.cpp \ + src/date_converter.c \ + src/downloadform.cpp \ + src/event_functions.cpp \ + src/filedownloader.cpp \ + src/main.cpp \ + src/mainwindow.cpp \ + src/mainwindow_action_menu.cpp \ + src/mainwindow_app_setting.cpp \ + src/mainwindow_search_form.cpp \ + src/searchexamplesform.cpp \ + src/searchform.cpp \ + src/settingsform.cpp \ + src/tabform.cpp \ + src/tabform_context_menu.cpp \ + src/wordsearchform.cpp \ + src/worker.cpp + +FORMS += \ + src/abjadform.ui \ + src/abjadformmini.ui \ + src/aboutauthorform.ui \ + src/aboutform.ui \ + src/databaseform.ui \ + src/downloadform.ui \ + src/mainwindow.ui \ + src/searchexamplesform.ui \ + src/searchform.ui \ + src/settingsform.ui \ + src/tabform.ui \ + src/wordsearchform.ui + +RESOURCES += \ + resources/themes/darkstyle.qrc \ + resources/resource.qrc diff --git a/libraries/include/JlCompress.h b/libraries/include/JlCompress.h new file mode 100644 index 0000000..fcb767b --- /dev/null +++ b/libraries/include/JlCompress.h @@ -0,0 +1,215 @@ +#ifndef JLCOMPRESSFOLDER_H_ +#define JLCOMPRESSFOLDER_H_ + +/* +Copyright (C) 2010 Roberto Pompermaier +Copyright (C) 2005-2016 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include "quazip.h" +#include "quazipfile.h" +#include "quazipfileinfo.h" +#include "quazip_qt_compat.h" +#include +#include +#include +#include + +/// Utility class for typical operations. +/** + This class contains a number of useful static functions to perform + simple operations, such as mass ZIP packing or extraction. + */ +class QUAZIP_EXPORT JlCompress { +public: + static bool copyData(QIODevice &inFile, QIODevice &outFile); + static QStringList extractDir(QuaZip &zip, const QString &dir); + static QStringList getFileList(QuaZip *zip); + static QString extractFile(QuaZip &zip, QString fileName, QString fileDest); + static QStringList extractFiles(QuaZip &zip, const QStringList &files, const QString &dir); + /// Compress a single file. + /** + \param zip Opened zip to compress the file to. + \param fileName The full path to the source file. + \param fileDest The full name of the file inside the archive. + \return true if success, false otherwise. + */ + static bool compressFile(QuaZip* zip, QString fileName, QString fileDest); + /// Compress a subdirectory. + /** + \param parentZip Opened zip containing the parent directory. + \param dir The full path to the directory to pack. + \param parentDir The full path to the directory corresponding to + the root of the ZIP. + \param recursive Whether to pack sub-directories as well or only + files. + \return true if success, false otherwise. + */ + static bool compressSubDir(QuaZip* parentZip, QString dir, QString parentDir, bool recursive, + QDir::Filters filters); + /// Extract a single file. + /** + \param zip The opened zip archive to extract from. + \param fileName The full name of the file to extract. + \param fileDest The full path to the destination file. + \return true if success, false otherwise. + */ + static bool extractFile(QuaZip* zip, QString fileName, QString fileDest); + /// Remove some files. + /** + \param listFile The list of files to remove. + \return true if success, false otherwise. + */ + static bool removeFile(QStringList listFile); + + /// Compress a single file. + /** + \param fileCompressed The name of the archive. + \param file The file to compress. + \return true if success, false otherwise. + */ + static bool compressFile(QString fileCompressed, QString file); + /// Compress a list of files. + /** + \param fileCompressed The name of the archive. + \param files The file list to compress. + \return true if success, false otherwise. + */ + static bool compressFiles(QString fileCompressed, QStringList files); + /// Compress a whole directory. + /** + Does not compress hidden files. See compressDir(QString, QString, bool, QDir::Filters). + + \param fileCompressed The name of the archive. + \param dir The directory to compress. + \param recursive Whether to pack the subdirectories as well, or + just regular files. + \return true if success, false otherwise. + */ + static bool compressDir(QString fileCompressed, QString dir = QString(), bool recursive = true); + /** + * @brief Compress a whole directory. + * + * Unless filters are specified explicitly, packs + * only regular non-hidden files (and subdirs, if @c recursive is true). + * If filters are specified, they are OR-combined with + * %QDir::AllDirs|%QDir::NoDotAndDotDot when searching for dirs + * and with QDir::Files when searching for files. + * + * @param fileCompressed path to the resulting archive + * @param dir path to the directory being compressed + * @param recursive if true, then the subdirectories are packed as well + * @param filters what to pack, filters are applied both when searching + * for subdirs (if packing recursively) and when looking for files to pack + * @return true on success, false otherwise + */ + static bool compressDir(QString fileCompressed, QString dir, + bool recursive, QDir::Filters filters); + + /// Extract a single file. + /** + \param fileCompressed The name of the archive. + \param fileName The file to extract. + \param fileDest The destination file, assumed to be identical to + \a file if left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QString extractFile(QString fileCompressed, QString fileName, QString fileDest = QString()); + /// Extract a list of files. + /** + \param fileCompressed The name of the archive. + \param files The file list to extract. + \param dir The directory to put the files to, the current + directory if left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QStringList extractFiles(QString fileCompressed, QStringList files, QString dir = QString()); + /// Extract a whole archive. + /** + \param fileCompressed The name of the archive. + \param dir The directory to extract to, the current directory if + left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QStringList extractDir(QString fileCompressed, QString dir = QString()); + /// Extract a whole archive. + /** + \param fileCompressed The name of the archive. + \param fileNameCodec The codec to use for file names. + \param dir The directory to extract to, the current directory if + left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QStringList extractDir(QString fileCompressed, QTextCodec* fileNameCodec, QString dir = QString()); + /// Get the file list. + /** + \return The list of the files in the archive, or, more precisely, the + list of the entries, including both files and directories if they + are present separately. + */ + static QStringList getFileList(QString fileCompressed); + /// Extract a single file. + /** + \param ioDevice pointer to device with compressed data. + \param fileName The file to extract. + \param fileDest The destination file, assumed to be identical to + \a file if left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QString extractFile(QIODevice *ioDevice, QString fileName, QString fileDest = QString()); + /// Extract a list of files. + /** + \param ioDevice pointer to device with compressed data. + \param files The file list to extract. + \param dir The directory to put the files to, the current + directory if left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QStringList extractFiles(QIODevice *ioDevice, QStringList files, QString dir = QString()); + /// Extract a whole archive. + /** + \param ioDevice pointer to device with compressed data. + \param dir The directory to extract to, the current directory if + left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QStringList extractDir(QIODevice *ioDevice, QString dir = QString()); + /// Extract a whole archive. + /** + \param ioDevice pointer to device with compressed data. + \param fileNameCodec The codec to use for file names. + \param dir The directory to extract to, the current directory if + left empty. + \return The list of the full paths of the files extracted, empty on failure. + */ + static QStringList extractDir(QIODevice* ioDevice, QTextCodec* fileNameCodec, QString dir = QString()); + /// Get the file list. + /** + \return The list of the files in the archive, or, more precisely, the + list of the entries, including both files and directories if they + are present separately. + */ + static QStringList getFileList(QIODevice *ioDevice); +}; + +#endif /* JLCOMPRESSFOLDER_H_ */ diff --git a/libraries/include/ioapi.h b/libraries/include/ioapi.h new file mode 100644 index 0000000..75d0aa6 --- /dev/null +++ b/libraries/include/ioapi.h @@ -0,0 +1,207 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + Modified by Sergey A. Tachenov to allow QIODevice API usage. + + For more info read MiniZip_info.txt + + Changes + + Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this) + Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux. + More if/def section may be needed to support other platforms + Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows. + (but you should use iowin32.c for windows instead) + +*/ + +#ifndef _ZLIBIOAPI64_H +#define _ZLIBIOAPI64_H + +#if (!defined(_WIN32)) && (!defined(WIN32)) + + // Linux needs this to support file operation on files larger then 4+GB + // But might need better if/def to select just the platforms that needs them. + + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif +#endif + +#include +#include +#include + +#if defined(USE_FILE32API) +#define fopen64 fopen +#define ftello64 ftell +#define fseeko64 fseek +#else +#ifdef _MSC_VER + #define fopen64 fopen + #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC))) + #define ftello64 _ftelli64 + #define fseeko64 _fseeki64 + #else // old MSC + #define ftello64 ftell + #define fseeko64 fseek + #endif +#endif +#endif + +/* +#ifndef ZPOS64_T + #ifdef _WIN32 + #define ZPOS64_T fpos_t + #else + #include + #define ZPOS64_T uint64_t + #endif +#endif +*/ + +#ifdef HAVE_MINIZIP64_CONF_H +#include "mz64conf.h" +#endif + +/* a type choosen by DEFINE */ +#ifdef HAVE_64BIT_INT_CUSTOM +typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T; +#else +#ifdef HAS_STDINT_H +#include "stdint.h" +typedef uint64_t ZPOS64_T; +#else + + +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef unsigned __int64 ZPOS64_T; +#else +typedef unsigned long long int ZPOS64_T; +#endif +#endif +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef OF +#define OF _Z_OF +#endif + +#define ZLIB_FILEFUNC_SEEK_CUR (1) +#define ZLIB_FILEFUNC_SEEK_END (2) +#define ZLIB_FILEFUNC_SEEK_SET (0) + +#define ZLIB_FILEFUNC_MODE_READ (1) +#define ZLIB_FILEFUNC_MODE_WRITE (2) +#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) + +#define ZLIB_FILEFUNC_MODE_EXISTING (4) +#define ZLIB_FILEFUNC_MODE_CREATE (8) + + +#ifndef ZCALLBACK + #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) + #define ZCALLBACK CALLBACK + #else + #define ZCALLBACK + #endif +#endif + + + + +typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, voidpf file, int mode)); +typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); +typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); +typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); + +typedef uLong (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); +typedef int (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); + + +/* here is the "old" 32 bits structure structure */ +typedef struct zlib_filefunc_def_s +{ + open_file_func zopen_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell_file_func ztell_file; + seek_file_func zseek_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc_def; + +typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream)); +typedef int (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, voidpf file, int mode)); + +typedef struct zlib_filefunc64_def_s +{ + open64_file_func zopen64_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell64_file_func ztell64_file; + seek64_file_func zseek64_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; + close_file_func zfakeclose_file; // for no-auto-close flag +} zlib_filefunc64_def; + +void fill_qiodevice64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_qiodevice_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); + +/* now internal definition, only for zip.c and unzip.h */ +typedef struct zlib_filefunc64_32_def_s +{ + zlib_filefunc64_def zfile_func64; + open_file_func zopen32_file; + tell_file_func ztell32_file; + seek_file_func zseek32_file; +} zlib_filefunc64_32_def; + + +#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream)) +//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode)) +#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream)) +#define ZFAKECLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zfakeclose_file)) ((filefunc).zfile_func64.opaque,filestream)) +#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream)) + +voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf file,int mode)); +int call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)); +ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)); + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32); + +#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode))) +#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream))) +#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode))) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/include/minizip_crypt.h b/libraries/include/minizip_crypt.h new file mode 100644 index 0000000..2e833f7 --- /dev/null +++ b/libraries/include/minizip_crypt.h @@ -0,0 +1,135 @@ +/* crypt.h -- base code for crypt/uncrypt ZIPfile + + + Version 1.01e, February 12th, 2005 + + Copyright (C) 1998-2005 Gilles Vollant + + This code is a modified version of crypting code in Infozip distribution + + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) + + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). + + If you don't need crypting in your application, just define symbols + NOCRYPT and NOUNCRYPT. + + This code support the "Traditional PKWARE Encryption". + + The new AES encryption added on Zip format by Winzip (see the page + http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong + Encryption is not supported. +*/ + +#include "quazip_global.h" + +#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) + +/*********************************************************************** + * Return the next byte in the pseudo-random sequence + */ +static int decrypt_byte(unsigned long* pkeys, const z_crc_t FAR * pcrc_32_tab QUAZIP_UNUSED) +{ + //(void) pcrc_32_tab; /* avoid "unused parameter" warning */ + unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an + * unpredictable manner on 16-bit systems; not a problem + * with any known compiler so far, though */ + + temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2; + return (int)(((temp * (temp ^ 1)) >> 8) & 0xff); +} + +/*********************************************************************** + * Update the encryption keys with the next byte of plain text + */ +static int update_keys(unsigned long* pkeys,const z_crc_t FAR * pcrc_32_tab,int c) +{ + (*(pkeys+0)) = CRC32((*(pkeys+0)), c); + (*(pkeys+1)) += (*(pkeys+0)) & 0xff; + (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; + { + register int keyshift = (int)((*(pkeys+1)) >> 24); + (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift); + } + return c; +} + + +/*********************************************************************** + * Initialize the encryption keys and the random header according to + * the given password. + */ +static void init_keys(const char* passwd,unsigned long* pkeys,const z_crc_t FAR * pcrc_32_tab) +{ + *(pkeys+0) = 305419896L; + *(pkeys+1) = 591751049L; + *(pkeys+2) = 878082192L; + while (*passwd != '\0') { + update_keys(pkeys,pcrc_32_tab,(int)*passwd); + passwd++; + } +} + +#define zdecode(pkeys,pcrc_32_tab,c) \ + (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab))) + +#define zencode(pkeys,pcrc_32_tab,c,t) \ + (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c)) + +#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED + +#define RAND_HEAD_LEN 12 + /* "last resort" source for second part of crypt seed pattern */ +# ifndef ZCR_SEED2 +# define ZCR_SEED2 3141592654UL /* use PI as default pattern */ +# endif + +static int crypthead(passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting) + const char *passwd; /* password string */ + unsigned char *buf; /* where to write header */ + int bufSize; + unsigned long* pkeys; + const z_crc_t FAR * pcrc_32_tab; + unsigned long crcForCrypting; +{ + int n; /* index in random header */ + int t; /* temporary */ + int c; /* random byte */ + unsigned char header[RAND_HEAD_LEN-2]; /* random header */ + static unsigned calls = 0; /* ensure different random header each time */ + + if (bufSize> 7) & 0xff; + header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); + } + /* Encrypt random header (last two bytes is high word of crc) */ + init_keys(passwd, pkeys, pcrc_32_tab); + for (n = 0; n < RAND_HEAD_LEN-2; n++) + { + buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); + } + buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); + buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); + return n; +} + +#endif diff --git a/libraries/include/quaadler32.h b/libraries/include/quaadler32.h new file mode 100644 index 0000000..633b175 --- /dev/null +++ b/libraries/include/quaadler32.h @@ -0,0 +1,54 @@ +#ifndef QUAADLER32_H +#define QUAADLER32_H + +/* +Copyright (C) 2010 Adam Walczak +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include + +#include "quachecksum32.h" + +/// Adler32 checksum +/** \class QuaAdler32 quaadler32.h + * This class wrappers the adler32 function with the QuaChecksum32 interface. + * See QuaChecksum32 for more info. + */ +class QUAZIP_EXPORT QuaAdler32 : public QuaChecksum32 +{ + +public: + QuaAdler32(); + + quint32 calculate(const QByteArray &data); + + void reset(); + void update(const QByteArray &buf); + quint32 value(); + +private: + quint32 checksum; +}; + +#endif //QUAADLER32_H diff --git a/libraries/include/quachecksum32.h b/libraries/include/quachecksum32.h new file mode 100644 index 0000000..09471e1 --- /dev/null +++ b/libraries/include/quachecksum32.h @@ -0,0 +1,79 @@ +#ifndef QUACHECKSUM32_H +#define QUACHECKSUM32_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include +#include "quazip_global.h" + +/// Checksum interface. +/** \class QuaChecksum32 quachecksum32.h + * This is an interface for 32 bit checksums. + * Classes implementing this interface can calcunate a certin + * checksum in a single step: + * \code + * QChecksum32 *crc32 = new QuaCrc32(); + * rasoult = crc32->calculate(data); + * \endcode + * or by streaming the data: + * \code + * QChecksum32 *crc32 = new QuaCrc32(); + * while(!fileA.atEnd()) + * crc32->update(fileA.read(bufSize)); + * resoultA = crc32->value(); + * crc32->reset(); + * while(!fileB.atEnd()) + * crc32->update(fileB.read(bufSize)); + * resoultB = crc32->value(); + * \endcode + */ +class QUAZIP_EXPORT QuaChecksum32 +{ + +public: + virtual ~QuaChecksum32(); + ///Calculates the checksum for data. + /** \a data source data + * \return data checksum + * + * This function has no efect on the value returned by value(). + */ + virtual quint32 calculate(const QByteArray &data) = 0; + + ///Resets the calculation on a checksun for a stream. + virtual void reset() = 0; + + ///Updates the calculated checksum for the stream + /** \a buf next portion of data from the stream + */ + virtual void update(const QByteArray &buf) = 0; + + ///Value of the checksum calculated for the stream passed throw update(). + /** \return checksum + */ + virtual quint32 value() = 0; +}; + +#endif //QUACHECKSUM32_H diff --git a/libraries/include/quacrc32.h b/libraries/include/quacrc32.h new file mode 100644 index 0000000..49808af --- /dev/null +++ b/libraries/include/quacrc32.h @@ -0,0 +1,50 @@ +#ifndef QUACRC32_H +#define QUACRC32_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include "quachecksum32.h" + +///CRC32 checksum +/** \class QuaCrc32 quacrc32.h +* This class wrappers the crc32 function with the QuaChecksum32 interface. +* See QuaChecksum32 for more info. +*/ +class QUAZIP_EXPORT QuaCrc32 : public QuaChecksum32 { + +public: + QuaCrc32(); + + quint32 calculate(const QByteArray &data); + + void reset(); + void update(const QByteArray &buf); + quint32 value(); + +private: + quint32 checksum; +}; + +#endif //QUACRC32_H diff --git a/libraries/include/quagzipfile.h b/libraries/include/quagzipfile.h new file mode 100644 index 0000000..77d2459 --- /dev/null +++ b/libraries/include/quagzipfile.h @@ -0,0 +1,108 @@ +#ifndef QUAZIP_QUAGZIPFILE_H +#define QUAZIP_QUAGZIPFILE_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include +#include "quazip_global.h" + +#include + +class QuaGzipFilePrivate; + +/// GZIP file +/** + This class is a wrapper around GZIP file access functions in zlib. Unlike QuaZip classes, it doesn't allow reading from a GZIP file opened as QIODevice, for example, if your GZIP file is in QBuffer. It only provides QIODevice access to a GZIP file contents, but the GZIP file itself must be identified by its name on disk or by descriptor id. + */ +class QUAZIP_EXPORT QuaGzipFile: public QIODevice { + Q_OBJECT +public: + /// Empty constructor. + /** + Must call setFileName() before trying to open. + */ + QuaGzipFile(); + /// Empty constructor with a parent. + /** + Must call setFileName() before trying to open. + \param parent The parent object, as per QObject logic. + */ + QuaGzipFile(QObject *parent); + /// Constructor. + /** + \param fileName The name of the GZIP file. + \param parent The parent object, as per QObject logic. + */ + QuaGzipFile(const QString &fileName, QObject *parent = nullptr); + /// Destructor. + virtual ~QuaGzipFile(); + /// Sets the name of the GZIP file to be opened. + void setFileName(const QString& fileName); + /// Returns the name of the GZIP file. + QString getFileName() const; + /// Returns true. + /** + Strictly speaking, zlib supports seeking for GZIP files, but it is + poorly implemented, because there is no way to implement it + properly. For reading, seeking backwards is very slow, and for + writing, it is downright impossible. Therefore, QuaGzipFile does not + support seeking at all. + */ + virtual bool isSequential() const; + /// Opens the file. + /** + \param mode Can be either QIODevice::Write or QIODevice::Read. + ReadWrite and Append aren't supported. + */ + virtual bool open(QIODevice::OpenMode mode); + /// Opens the file. + /** + \overload + \param fd The file descriptor to read/write the GZIP file from/to. + \param mode Can be either QIODevice::Write or QIODevice::Read. + ReadWrite and Append aren't supported. + */ + virtual bool open(int fd, QIODevice::OpenMode mode); + /// Flushes data to file. + /** + The data is written using Z_SYNC_FLUSH mode. Doesn't make any sense + when reading. + */ + virtual bool flush(); + /// Closes the file. + virtual void close(); +protected: + /// Implementation of QIODevice::readData(). + virtual qint64 readData(char *data, qint64 maxSize); + /// Implementation of QIODevice::writeData(). + virtual qint64 writeData(const char *data, qint64 maxSize); +private: + // not implemented by design to disable copy + QuaGzipFile(const QuaGzipFile &that); + QuaGzipFile& operator=(const QuaGzipFile &that); + QuaGzipFilePrivate *d; +}; + +#endif // QUAZIP_QUAGZIPFILE_H diff --git a/libraries/include/quaziodevice.h b/libraries/include/quaziodevice.h new file mode 100644 index 0000000..3adb8b9 --- /dev/null +++ b/libraries/include/quaziodevice.h @@ -0,0 +1,103 @@ +#ifndef QUAZIP_QUAZIODEVICE_H +#define QUAZIP_QUAZIODEVICE_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include +#include "quazip_global.h" + +#include + +class QuaZIODevicePrivate; + +/// A class to compress/decompress QIODevice. +/** + This class can be used to compress any data written to QIODevice or + decompress it back. Compressing data sent over a QTcpSocket is a good + example. + */ +class QUAZIP_EXPORT QuaZIODevice: public QIODevice { + friend class QuaZIODevicePrivate; + Q_OBJECT +public: + /// Constructor. + /** + \param io The QIODevice to read/write. + \param parent The parent object, as per QObject logic. + */ + QuaZIODevice(QIODevice *io, QObject *parent = nullptr); + /// Destructor. + ~QuaZIODevice(); + /// Flushes data waiting to be written. + /** + Unfortunately, as QIODevice doesn't support flush() by itself, the + only thing this method does is write the compressed data into the + device using Z_SYNC_FLUSH mode. If you need the compressed data to + actually be flushed from the buffer of the underlying QIODevice, you + need to call its flush() method as well, providing it supports it + (like QTcpSocket does). Example: + \code + QuaZIODevice dev(&sock); + dev.open(QIODevice::Write); + dev.write(yourDataGoesHere); + dev.flush(); + sock->flush(); // this actually sends data to network + \endcode + + This may change in the future versions of %QuaZip by implementing an + ugly hack: trying to cast the QIODevice using qobject_cast to known + flush()-supporting subclasses, and calling flush if the resulting + pointer is not zero. + */ + virtual bool flush(); + /// Opens the device. + /** + \param mode Neither QIODevice::ReadWrite nor QIODevice::Append are + not supported. + */ + virtual bool open(QIODevice::OpenMode mode); + /// Closes this device, but not the underlying one. + /** + The underlying QIODevice is not closed in case you want to write + something else to it. + */ + virtual void close(); + /// Returns the underlying device. + QIODevice *getIoDevice() const; + /// Returns true. + virtual bool isSequential() const; + /// Returns true iff the end of the compressed stream is reached. + virtual bool atEnd() const; + /// Returns the number of the bytes buffered. + virtual qint64 bytesAvailable() const; +protected: + /// Implementation of QIODevice::readData(). + virtual qint64 readData(char *data, qint64 maxSize); + /// Implementation of QIODevice::writeData(). + virtual qint64 writeData(const char *data, qint64 maxSize); +private: + QuaZIODevicePrivate *d; +}; +#endif // QUAZIP_QUAZIODEVICE_H diff --git a/libraries/include/quazip.h b/libraries/include/quazip.h new file mode 100644 index 0000000..488c3a9 --- /dev/null +++ b/libraries/include/quazip.h @@ -0,0 +1,616 @@ +#ifndef QUA_ZIP_H +#define QUA_ZIP_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant, see +quazip/(un)zip.h files for details, basically it's zlib license. + **/ + +#include +#include +#include "quazip_qt_compat.h" + +#include "zip.h" +#include "unzip.h" + +#include "quazip_global.h" +#include "quazipfileinfo.h" + +// just in case it will be defined in the later versions of the ZIP/UNZIP +#ifndef UNZ_OPENERROR +// define additional error code +#define UNZ_OPENERROR -1000 +#endif + +class QuaZipPrivate; + +/// ZIP archive. +/** \class QuaZip quazip.h + * This class implements basic interface to the ZIP archive. It can be + * used to read table contents of the ZIP archive and retreiving + * information about the files inside it. + * + * You can also use this class to open files inside archive by passing + * pointer to the instance of this class to the constructor of the + * QuaZipFile class. But see QuaZipFile::QuaZipFile(QuaZip*, QObject*) + * for the possible pitfalls. + * + * This class is indended to provide interface to the ZIP subpackage of + * the ZIP/UNZIP package as well as to the UNZIP subpackage. But + * currently it supports only UNZIP. + * + * The use of this class is simple - just create instance using + * constructor, then set ZIP archive file name using setFile() function + * (if you did not passed the name to the constructor), then open() and + * then use different functions to work with it! Well, if you are + * paranoid, you may also wish to call close before destructing the + * instance, to check for errors on close. + * + * You may also use getUnzFile() and getZipFile() functions to get the + * ZIP archive handle and use it with ZIP/UNZIP package API directly. + * + * This class supports localized file names inside ZIP archive, but you + * have to set up proper codec with setCodec() function. By default, + * locale codec will be used, which is probably ok for UNIX systems, but + * will almost certainly fail with ZIP archives created in Windows. This + * is because Windows ZIP programs have strange habit of using DOS + * encoding for file names in ZIP archives. For example, ZIP archive + * with cyrillic names created in Windows will have file names in \c + * IBM866 encoding instead of \c WINDOWS-1251. I think that calling one + * function is not much trouble, but for true platform independency it + * would be nice to have some mechanism for file name encoding auto + * detection using locale information. Does anyone know a good way to do + * it? + **/ +class QUAZIP_EXPORT QuaZip { + friend class QuaZipPrivate; + public: + /// Useful constants. + enum Constants { + MAX_FILE_NAME_LENGTH=256 /**< Maximum file name length. Taken from + \c UNZ_MAXFILENAMEINZIP constant in + unzip.c. */ + }; + /// Open mode of the ZIP file. + enum Mode { + mdNotOpen, ///< ZIP file is not open. This is the initial mode. + mdUnzip, ///< ZIP file is open for reading files inside it. + mdCreate, ///< ZIP file was created with open() call. + mdAppend, /**< ZIP file was opened in append mode. This refers to + * \c APPEND_STATUS_CREATEAFTER mode in ZIP/UNZIP package + * and means that zip is appended to some existing file + * what is useful when that file contains + * self-extractor code. This is obviously \em not what + * you whant to use to add files to the existing ZIP + * archive. + **/ + mdAdd ///< ZIP file was opened for adding files in the archive. + }; + /// Case sensitivity for the file names. + /** This is what you specify when accessing files in the archive. + * Works perfectly fine with any characters thanks to Qt's great + * unicode support. This is different from ZIP/UNZIP API, where + * only US-ASCII characters was supported. + **/ + enum CaseSensitivity { + csDefault=0, ///< Default for platform. Case sensitive for UNIX, not for Windows. + csSensitive=1, ///< Case sensitive. + csInsensitive=2 ///< Case insensitive. + }; + /// Returns the actual case sensitivity for the specified QuaZip one. + /** + \param cs The value to convert. + \returns If CaseSensitivity::csDefault, then returns the default + file name case sensitivity for the platform. Otherwise, just + returns the appropriate value from the Qt::CaseSensitivity enum. + */ + static Qt::CaseSensitivity convertCaseSensitivity( + CaseSensitivity cs); + private: + QuaZipPrivate *p; + // not (and will not be) implemented + QuaZip(const QuaZip& that); + // not (and will not be) implemented + QuaZip& operator=(const QuaZip& that); + public: + /// Constructs QuaZip object. + /** Call setName() before opening constructed object. */ + QuaZip(); + /// Constructs QuaZip object associated with ZIP file \a zipName. + QuaZip(const QString& zipName); + /// Constructs QuaZip object associated with ZIP file represented by \a ioDevice. + /** The IO device must be seekable, otherwise an error will occur when opening. */ + QuaZip(QIODevice *ioDevice); + /// Destroys QuaZip object. + /** Calls close() if necessary. */ + ~QuaZip(); + /// Opens ZIP file. + /** + * Argument \a mode specifies open mode of the ZIP archive. See Mode + * for details. Note that there is zipOpen2() function in the + * ZIP/UNZIP API which accepts \a globalcomment argument, but it + * does not use it anywhere, so this open() function does not have this + * argument. See setComment() if you need to set global comment. + * + * If the ZIP file is accessed via explicitly set QIODevice, then + * this device is opened in the necessary mode. If the device was + * already opened by some other means, then QuaZip checks if the + * open mode is compatible to the mode needed for the requested operation. + * If necessary, seeking is performed to position the device properly. + * + * \return \c true if successful, \c false otherwise. + * + * \note ZIP/UNZIP API open calls do not return error code - they + * just return \c null indicating an error. But to make things + * easier, quazip.h header defines additional error code \c + * UNZ_ERROROPEN and getZipError() will return it if the open call + * of the ZIP/UNZIP API returns \c null. + * + * Argument \a ioApi specifies IO function set for ZIP/UNZIP + * package to use. See unzip.h, zip.h and ioapi.h for details. Note + * that IO API for QuaZip is different from the original package. + * The file path argument was changed to be of type \c voidpf, and + * QuaZip passes a QIODevice pointer there. This QIODevice is either + * set explicitly via setIoDevice() or the QuaZip(QIODevice*) + * constructor, or it is created internally when opening the archive + * by its file name. The default API (qioapi.cpp) just delegates + * everything to the QIODevice API. Not only this allows to use a + * QIODevice instead of file name, but also has a nice side effect + * of raising the file size limit from 2G to 4G (in non-zip64 archives). + * + * \note If the zip64 support is needed, the ioApi argument \em must be null + * because due to the backwards compatibility issues it can be used to + * provide a 32-bit API only. + * + * \note If the \ref QuaZip::setAutoClose() "no-auto-close" feature is used, + * then the \a ioApi argument \em should be null because the old API + * doesn't support the 'fake close' operation, causing slight memory leaks + * and other possible troubles (like closing the output device in case + * when an error occurs during opening). + * + * In short: just forget about the \a ioApi argument and you'll be + * fine. + **/ + bool open(Mode mode, zlib_filefunc_def *ioApi =nullptr); + /// Closes ZIP file. + /** Call getZipError() to determine if the close was successful. + * + * If the file was opened by name, then the underlying QIODevice is closed + * and deleted. + * + * If the underlying QIODevice was set explicitly using setIoDevice() or + * the appropriate constructor, then it is closed if the auto-close flag + * is set (which it is by default). Call setAutoClose() to clear the + * auto-close flag if this behavior is undesirable. + * + * Since Qt 5.1, the QSaveFile was introduced. It breaks the QIODevice API + * by making close() private and crashing the application if it is called + * from the base class where it is public. It is an excellent example + * of poor design that illustrates why you should never ever break + * an is-a relationship between the base class and a subclass. QuaZip + * works around this bug by checking if the QIODevice is an instance + * of QSaveFile, using qobject_cast<>, and if it is, calls + * QSaveFile::commit() instead of close(). It is a really ugly hack, + * but at least it makes your programs work instead of crashing. Note that + * if the auto-close flag is cleared, then this is a non-issue, and + * commit() isn't called. + * + * Closing an already closed (or never opened) instance is safe, + * regardless of whether the first close attempt was successful. + * This second close does nothing, but is considered a success, + * as far as getZipError() is concerned. + */ + void close(); + /// Sets the codec used to encode/decode file names inside archive. + /** This is necessary to access files in the ZIP archive created + * under Windows with non-latin characters in file names. For + * example, file names with cyrillic letters will be in \c IBM866 + * encoding. + **/ + void setFileNameCodec(QTextCodec *fileNameCodec); + /// Sets the codec used to encode/decode file names inside archive. + /** \overload + * Equivalent to calling setFileNameCodec(QTextCodec::codecForName(codecName)); + **/ + void setFileNameCodec(const char *fileNameCodecName); + /// Sets the OS code (highest 8 bits of the “version made by” field) for new files. + /** There is currently no way to specify this for each file individually, + except by calling this function before opening each file. If this function is not called, + then the default OS code will be used. The default code is set by calling + setDefaultOsCode(). The default value at the moment of QuaZip creation will be used. */ + void setOsCode(uint osCode); + /// Returns the OS code for new files. + uint getOsCode() const; + /// Returns the codec used to encode/decode comments inside archive. + QTextCodec* getFileNameCodec() const; + /// Sets the codec used to encode/decode comments inside archive. + /** This codec defaults to locale codec, which is probably ok. + **/ + void setCommentCodec(QTextCodec *commentCodec); + /// Sets the codec used to encode/decode comments inside archive. + /** \overload + * Equivalent to calling setCommentCodec(QTextCodec::codecForName(codecName)); + **/ + void setCommentCodec(const char *commentCodecName); + /// Returns the codec used to encode/decode comments inside archive. + QTextCodec* getCommentCodec() const; + /// Returns the name of the ZIP file. + /** Returns null string if no ZIP file name has been set, for + * example when the QuaZip instance is set up to use a QIODevice + * instead. + * \sa setZipName(), setIoDevice(), getIoDevice() + **/ + QString getZipName() const; + /// Sets the name of the ZIP file. + /** Does nothing if the ZIP file is open. + * + * Does not reset error code returned by getZipError(). + * \sa setIoDevice(), getIoDevice(), getZipName() + **/ + void setZipName(const QString& zipName); + /// Returns the device representing this ZIP file. + /** Returns null string if no device has been set explicitly, for + * example when opening a ZIP file by name. + * \sa setIoDevice(), getZipName(), setZipName() + **/ + QIODevice *getIoDevice() const; + /// Sets the device representing the ZIP file. + /** Does nothing if the ZIP file is open. + * + * Does not reset error code returned by getZipError(). + * \sa getIoDevice(), getZipName(), setZipName() + **/ + void setIoDevice(QIODevice *ioDevice); + /// Returns the mode in which ZIP file was opened. + Mode getMode() const; + /// Returns \c true if ZIP file is open, \c false otherwise. + bool isOpen() const; + /// Returns the error code of the last operation. + /** Returns \c UNZ_OK if the last operation was successful. + * + * Error code resets to \c UNZ_OK every time you call any function + * that accesses something inside ZIP archive, even if it is \c + * const (like getEntriesCount()). open() and close() calls reset + * error code too. See documentation for the specific functions for + * details on error detection. + **/ + int getZipError() const; + /// Returns number of the entries in the ZIP central directory. + /** Returns negative error code in the case of error. The same error + * code will be returned by subsequent getZipError() call. + **/ + int getEntriesCount() const; + /// Returns global comment in the ZIP file. + QString getComment() const; + /// Sets the global comment in the ZIP file. + /** The comment will be written to the archive on close operation. + * QuaZip makes a distinction between a null QByteArray() comment + * and an empty "" comment in the QuaZip::mdAdd mode. + * A null comment is the default and it means "don't change + * the comment". An empty comment removes the original comment. + * + * \sa open() + **/ + void setComment(const QString& comment); + /// Sets the current file to the first file in the archive. + /** Returns \c true on success, \c false otherwise. Call + * getZipError() to get the error code. + **/ + bool goToFirstFile(); + /// Sets the current file to the next file in the archive. + /** Returns \c true on success, \c false otherwise. Call + * getZipError() to determine if there was an error. + * + * Should be used only in QuaZip::mdUnzip mode. + * + * \note If the end of file was reached, getZipError() will return + * \c UNZ_OK instead of \c UNZ_END_OF_LIST_OF_FILE. This is to make + * things like this easier: + * \code + * for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { + * // do something + * } + * if(zip.getZipError()==UNZ_OK) { + * // ok, there was no error + * } + * \endcode + **/ + bool goToNextFile(); + /// Sets current file by its name. + /** Returns \c true if successful, \c false otherwise. Argument \a + * cs specifies case sensitivity of the file name. Call + * getZipError() in the case of a failure to get error code. + * + * This is not a wrapper to unzLocateFile() function. That is + * because I had to implement locale-specific case-insensitive + * comparison. + * + * Here are the differences from the original implementation: + * + * - If the file was not found, error code is \c UNZ_OK, not \c + * UNZ_END_OF_LIST_OF_FILE (see also goToNextFile()). + * - If this function fails, it unsets the current file rather than + * resetting it back to what it was before the call. + * + * If \a fileName is null string then this function unsets the + * current file and return \c true. Note that you should close the + * file first if it is open! See + * QuaZipFile::QuaZipFile(QuaZip*,QObject*) for the details. + * + * Should be used only in QuaZip::mdUnzip mode. + * + * \sa setFileNameCodec(), CaseSensitivity + **/ + bool setCurrentFile(const QString& fileName, CaseSensitivity cs =csDefault); + /// Returns \c true if the current file has been set. + bool hasCurrentFile() const; + /// Retrieves information about the current file. + /** Fills the structure pointed by \a info. Returns \c true on + * success, \c false otherwise. In the latter case structure pointed + * by \a info remains untouched. If there was an error, + * getZipError() returns error code. + * + * Should be used only in QuaZip::mdUnzip mode. + * + * Does nothing and returns \c false in any of the following cases. + * - ZIP is not open; + * - ZIP does not have current file. + * + * In both cases getZipError() returns \c UNZ_OK since there + * is no ZIP/UNZIP API call. + * + * This overload doesn't support zip64, but will work OK on zip64 archives + * except that if one of the sizes (compressed or uncompressed) is greater + * than 0xFFFFFFFFu, it will be set to exactly 0xFFFFFFFFu. + * + * \sa getCurrentFileInfo(QuaZipFileInfo64* info)const + * \sa QuaZipFileInfo64::toQuaZipFileInfo(QuaZipFileInfo&)const + **/ + bool getCurrentFileInfo(QuaZipFileInfo* info)const; + /// Retrieves information about the current file. + /** \overload + * + * This function supports zip64. If the archive doesn't use zip64, it is + * completely equivalent to getCurrentFileInfo(QuaZipFileInfo* info) + * except for the argument type. + * + * \sa + **/ + bool getCurrentFileInfo(QuaZipFileInfo64* info)const; + /// Returns the current file name. + /** Equivalent to calling getCurrentFileInfo() and then getting \c + * name field of the QuaZipFileInfo structure, but faster and more + * convenient. + * + * Should be used only in QuaZip::mdUnzip mode. + **/ + QString getCurrentFileName()const; + /// Returns \c unzFile handle. + /** You can use this handle to directly call UNZIP part of the + * ZIP/UNZIP package functions (see unzip.h). + * + * \warning When using the handle returned by this function, please + * keep in mind that QuaZip class is unable to detect any changes + * you make in the ZIP file state (e. g. changing current file, or + * closing the handle). So please do not do anything with this + * handle that is possible to do with the functions of this class. + * Or at least return the handle in the original state before + * calling some another function of this class (including implicit + * destructor calls and calls from the QuaZipFile objects that refer + * to this QuaZip instance!). So if you have changed the current + * file in the ZIP archive - then change it back or you may + * experience some strange behavior or even crashes. + **/ + unzFile getUnzFile(); + /// Returns \c zipFile handle. + /** You can use this handle to directly call ZIP part of the + * ZIP/UNZIP package functions (see zip.h). Warnings about the + * getUnzFile() function also apply to this function. + **/ + zipFile getZipFile(); + /// Changes the data descriptor writing mode. + /** + According to the ZIP format specification, a file inside archive + may have a data descriptor immediately following the file + data. This is reflected by a special flag in the local file header + and in the central directory. By default, QuaZip sets this flag + and writes the data descriptor unless both method and level were + set to 0, in which case it operates in 1.0-compatible mode and + never writes data descriptors. + + By setting this flag to false, it is possible to disable data + descriptor writing, thus increasing compatibility with archive + readers that don't understand this feature of the ZIP file format. + + Setting this flag affects all the QuaZipFile instances that are + opened after this flag is set. + + The data descriptor writing mode is enabled by default. + + Note that if the ZIP archive is written into a QIODevice for which + QIODevice::isSequential() returns \c true, then the data descriptor + is mandatory and will be written even if this flag is set to false. + + \param enabled If \c true, enable local descriptor writing, + disable it otherwise. + + \sa QuaZipFile::isDataDescriptorWritingEnabled() + */ + void setDataDescriptorWritingEnabled(bool enabled); + /// Returns the data descriptor default writing mode. + /** + \sa setDataDescriptorWritingEnabled() + */ + bool isDataDescriptorWritingEnabled() const; + /// Returns a list of files inside the archive. + /** + \return A list of file names or an empty list if there + was an error or if the archive is empty (call getZipError() to + figure out which). + \sa getFileInfoList() + */ + QStringList getFileNameList() const; + /// Returns information list about all files inside the archive. + /** + \return A list of QuaZipFileInfo objects or an empty list if there + was an error or if the archive is empty (call getZipError() to + figure out which). + + This function doesn't support zip64, but will still work with zip64 + archives, converting results using QuaZipFileInfo64::toQuaZipFileInfo(). + If all file sizes are below 4 GB, it will work just fine. + + \sa getFileNameList() + \sa getFileInfoList64() + */ + QList getFileInfoList() const; + /// Returns information list about all files inside the archive. + /** + \overload + + This function supports zip64. + + \sa getFileNameList() + \sa getFileInfoList() + */ + QList getFileInfoList64() const; + /// Enables the zip64 mode. + /** + * @param zip64 If \c true, the zip64 mode is enabled, disabled otherwise. + * + * Once this is enabled, all new files (until the mode is disabled again) + * will be created in the zip64 mode, thus enabling the ability to write + * files larger than 4 GB. By default, the zip64 mode is off due to + * compatibility reasons. + * + * Note that this does not affect the ability to read zip64 archives in any + * way. + * + * \sa isZip64Enabled() + */ + void setZip64Enabled(bool zip64); + /// Returns whether the zip64 mode is enabled. + /** + * @return \c true if and only if the zip64 mode is enabled. + * + * \sa setZip64Enabled() + */ + bool isZip64Enabled() const; + /// Enables the use of UTF-8 encoding for file names and comments text. + /** + * @param utf8 If \c true, the UTF-8 mode is enabled, disabled otherwise. + * + * Once this is enabled, the names of all new files and comments text (until + * the mode is disabled again) will be encoded in UTF-8 encoding, and the + * version to extract will be set to 6.3 (63) in ZIP header. By default, + * the UTF-8 mode is off due to compatibility reasons. + * + * Note that when extracting ZIP archives, the UTF-8 mode is determined from + * ZIP file header, not from this flag. + * + * \sa isUtf8Enabled() + */ + void setUtf8Enabled(bool utf8); + /// Returns whether the UTF-8 encoding mode is enabled. + /** + * @return \c true if and only if the UTF-8 mode is enabled. + * + * \sa setUtf8Enabled() + */ + bool isUtf8Enabled() const; + /// Returns the auto-close flag. + /** + @sa setAutoClose() + */ + bool isAutoClose() const; + /// Sets or unsets the auto-close flag. + /** + By default, QuaZip opens the underlying QIODevice when open() is called, + and closes it when close() is called. In some cases, when the device + is set explicitly using setIoDevice(), it may be desirable to + leave the device open. If the auto-close flag is unset using this method, + then the device isn't closed automatically if it was set explicitly. + + If it is needed to clear this flag, it is recommended to do so before + opening the archive because otherwise QuaZip may close the device + during the open() call if an error is encountered after the device + is opened. + + If the device was not set explicitly, but rather the setZipName() or + the appropriate constructor was used to set the ZIP file name instead, + then the auto-close flag has no effect, and the internal device + is closed nevertheless because there is no other way to close it. + + @sa isAutoClose() + @sa setIoDevice() + */ + void setAutoClose(bool autoClose) const; + /// Sets the default file name codec to use. + /** + * The default codec is used by the constructors, so calling this function + * won't affect the QuaZip instances already created at that moment. + * + * The codec specified here can be overriden by calling setFileNameCodec(). + * If neither function is called, QTextCodec::codecForLocale() will be used + * to decode or encode file names. Use this function with caution if + * the application uses other libraries that depend on QuaZip. Those + * libraries can either call this function by themselves, thus overriding + * your setting or can rely on the default encoding, thus failing + * mysteriously if you change it. For these reasons, it isn't recommended + * to use this function if you are developing a library, not an application. + * Instead, ask your library users to call it in case they need specific + * encoding. + * + * In most cases, using setFileNameCodec() instead is the right choice. + * However, if you depend on third-party code that uses QuaZip, then the + * reasons stated above can actually become a reason to use this function + * in case the third-party code in question fails because it doesn't + * understand the encoding you need and doesn't provide a way to specify it. + * This applies to the JlCompress class as well, as it was contributed and + * doesn't support explicit encoding parameters. + * + * In short: use setFileNameCodec() when you can, resort to + * setDefaultFileNameCodec() when you don't have access to the QuaZip + * instance. + * + * @param codec The codec to use by default. If null, resets to default. + */ + static void setDefaultFileNameCodec(QTextCodec *codec); + /** + * @overload + * Equivalent to calling + * setDefaultFileNameCodec(QTextCodec::codecForName(codecName)). + */ + static void setDefaultFileNameCodec(const char *codecName); + /// Sets default OS code. + /** + * @sa setOsCode() + */ + static void setDefaultOsCode(uint osCode); + /// Returns default OS code. + /** + * @sa getOsCode() + */ + static uint getDefaultOsCode(); +}; + +#endif diff --git a/libraries/include/quazip_global.h b/libraries/include/quazip_global.h new file mode 100644 index 0000000..a719901 --- /dev/null +++ b/libraries/include/quazip_global.h @@ -0,0 +1,63 @@ +#ifndef QUAZIP_GLOBAL_H +#define QUAZIP_GLOBAL_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include + +/** + This is automatically defined when building a static library, but when + including QuaZip sources directly into a project, QUAZIP_STATIC should + be defined explicitly to avoid possible troubles with unnecessary + importing/exporting. + */ +#ifdef QUAZIP_STATIC +#define QUAZIP_EXPORT +#else +/** + * When building a DLL with MSVC, QUAZIP_BUILD must be defined. + * qglobal.h takes care of defining Q_DECL_* correctly for msvc/gcc. + */ +#if defined(QUAZIP_BUILD) + #define QUAZIP_EXPORT Q_DECL_EXPORT +#else + #define QUAZIP_EXPORT Q_DECL_IMPORT +#endif +#endif // QUAZIP_STATIC + +#ifdef __GNUC__ +#define QUAZIP_UNUSED __attribute__((__unused__)) +#else +#define QUAZIP_UNUSED +#endif + +#define QUAZIP_EXTRA_NTFS_MAGIC 0x000Au +#define QUAZIP_EXTRA_NTFS_TIME_MAGIC 0x0001u +#define QUAZIP_EXTRA_EXT_TIME_MAGIC 0x5455u +#define QUAZIP_EXTRA_EXT_MOD_TIME_FLAG 1 +#define QUAZIP_EXTRA_EXT_AC_TIME_FLAG 2 +#define QUAZIP_EXTRA_EXT_CR_TIME_FLAG 4 + +#endif // QUAZIP_GLOBAL_H diff --git a/libraries/include/quazip_qt_compat.h b/libraries/include/quazip_qt_compat.h new file mode 100644 index 0000000..48024be --- /dev/null +++ b/libraries/include/quazip_qt_compat.h @@ -0,0 +1,145 @@ +#ifndef QUAZIP_QT_COMPAT_H +#define QUAZIP_QT_COMPAT_H + +/* + * For some reason, Qt 5.14 and 5.15 introduced a whole mess of seemingly random + * moves and deprecations. To avoid populating code with #ifs, + * we handle this stuff here, as well as some other compatibility issues. + * + * Some includes are repeated just in case we want to split this file later. + */ + +#include +#include + +// Legacy encodings are still everywhere, but the Qt team decided we +// don't need them anymore and moved them out of Core in Qt 6. +#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) +# include +#else +# include +#endif + +// QSaveFile terribly breaks the is-a idiom (Liskov substitution principle): +// QSaveFile is-a QIODevice, but it makes close() private and aborts +// if you call it through the base class. Hence this ugly hack: +#if (QT_VERSION >= 0x050100) +#include +inline bool quazip_close(QIODevice *device) { + QSaveFile *file = qobject_cast(device); + if (file != nullptr) { + // We have to call the ugly commit() instead: + return file->commit(); + } else { + device->close(); + return true; + } +} +#else +inline bool quazip_close(QIODevice *device) { + device->close(); + return true; +} +#endif + +// this is yet another stupid move and deprecation +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) +using Qt::SkipEmptyParts; +#else +#include +const auto SkipEmptyParts = QString::SplitBehavior::SkipEmptyParts; +#endif + +// and yet another... (why didn't they just make qSort delegate to std::sort?) +#include +#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)) +#include +template +inline void quazip_sort(T begin, T end, C comparator) { + std::sort(begin, end, comparator); +} +#else +#include +template +inline void quazip_sort(T begin, T end, C comparator) { + qSort(begin, end, comparator); +} +#endif + +// this is a stupid rename... +#include +#include +#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) +inline QDateTime quazip_ctime(const QFileInfo &fi) { + return fi.birthTime(); +} +#else +inline QDateTime quazip_ctime(const QFileInfo &fi) { + return fi.created(); +} +#endif + +// this is just a slightly better alternative +#include +#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) +inline bool quazip_is_symlink(const QFileInfo &fi) { + return fi.isSymbolicLink(); +} +#else +inline bool quazip_is_symlink(const QFileInfo &fi) { + // also detects *.lnk on Windows, but better than nothing + return fi.isSymLink(); +} +#endif + +// I'm not even sure what this one is, but nevertheless +#include +#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) +inline QString quazip_symlink_target(const QFileInfo &fi) { + return fi.symLinkTarget(); +} +#else +inline QString quazip_symlink_target(const QFileInfo &fi) { + return fi.readLink(); // What's the difference? I've no idea. +} +#endif + +// this is not a deprecation but an improvement, for a change +#include +#if (QT_VERSION >= 0x040700) +inline quint64 quazip_ntfs_ticks(const QDateTime &time, int fineTicks) { + QDateTime base(QDate(1601, 1, 1), QTime(0, 0), Qt::UTC); + return base.msecsTo(time) * 10000 + fineTicks; +} +#else +inline quint64 quazip_ntfs_ticks(const QDateTime &time, int fineTicks) { + QDateTime base(QDate(1601, 1, 1), QTime(0, 0), Qt::UTC); + QDateTime utc = time.toUTC(); + return (static_cast(base.date().daysTo(utc.date())) + * Q_INT64_C(86400000) + + static_cast(base.time().msecsTo(utc.time()))) + * Q_INT64_C(10000) + fineTicks; +} +#endif + +// yet another improvement... +#include +#if QT_VERSION >= QT_VERSION_CHECK(5, 8, 0) // Yay! Finally a way to get time as qint64! +inline qint64 quazip_to_time64_t(const QDateTime &time) { + return time.toSecsSinceEpoch(); +} +#else +inline qint64 quazip_to_time64_t(const QDateTime &time) { + return static_cast(time.toTime_t()); // 32 bits only, but better than nothing +} +#endif + +#include +// and another stupid move +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) +const auto quazip_endl = Qt::endl; +#else +const auto quazip_endl = endl; +#endif + +#endif // QUAZIP_QT_COMPAT_H diff --git a/libraries/include/quazipdir.h b/libraries/include/quazipdir.h new file mode 100644 index 0000000..a4922b9 --- /dev/null +++ b/libraries/include/quazipdir.h @@ -0,0 +1,223 @@ +#ifndef QUAZIP_QUAZIPDIR_H +#define QUAZIP_QUAZIPDIR_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +class QuaZipDirPrivate; + +#include "quazip.h" +#include "quazipfileinfo.h" +#include +#include +#include + +/// Provides ZIP archive navigation. +/** +* This class is modelled after QDir, and is designed to provide similar +* features for ZIP archives. +* +* The only significant difference from QDir is that the root path is not +* '/', but an empty string since that's how the file paths are stored in +* the archive. However, QuaZipDir understands the paths starting with +* '/'. It is important in a few places: +* +* - In the cd() function. +* - In the constructor. +* - In the exists() function. +* - In the relativePath() function. +* +* Note that since ZIP uses '/' on all platforms, the '\' separator is +* not supported. +*/ +class QUAZIP_EXPORT QuaZipDir { +private: + QSharedDataPointer d; +public: + /// The copy constructor. + QuaZipDir(const QuaZipDir &that); + /// Constructs a QuaZipDir instance pointing to the specified directory. + /** + If \a dir is not specified, points to the root of the archive. + The same happens if the \a dir is "/". + */ + QuaZipDir(QuaZip *zip, const QString &dir = QString()); + /// Destructor. + ~QuaZipDir(); + /// The assignment operator. + bool operator==(const QuaZipDir &that); + /// operator!= + /** + \return \c true if either this and \a that use different QuaZip + instances or if they point to different directories. + */ + inline bool operator!=(const QuaZipDir &that) {return !operator==(that);} + /// operator== + /** + \return \c true if both this and \a that use the same QuaZip + instance and point to the same directory. + */ + QuaZipDir& operator=(const QuaZipDir &that); + /// Returns the name of the entry at the specified position. + QString operator[](int pos) const; + /// Returns the current case sensitivity mode. + QuaZip::CaseSensitivity caseSensitivity() const; + /// Changes the 'current' directory. + /** + * If the path starts with '/', it is interpreted as an absolute + * path from the root of the archive. Otherwise, it is interpreted + * as a path relative to the current directory as was set by the + * previous cd() or the constructor. + * + * Note that the subsequent path() call will not return a path + * starting with '/' in all cases. + */ + bool cd(const QString &dirName); + /// Goes up. + bool cdUp(); + /// Returns the number of entries in the directory. + uint count() const; + /// Returns the current directory name. + /** + The name doesn't include the path. + */ + QString dirName() const; + /// Returns the list of the entries in the directory. + /** + \param nameFilters The list of file patterns to list, uses the same + syntax as QDir. + \param filters The entry type filters, only Files and Dirs are + accepted. + \param sort Sorting mode. + */ + QList entryInfoList(const QStringList &nameFilters, + QDir::Filters filters = QDir::NoFilter, + QDir::SortFlags sort = QDir::NoSort) const; + /// Returns the list of the entries in the directory. + /** + \overload + + The same as entryInfoList(QStringList(), filters, sort). + */ + QList entryInfoList(QDir::Filters filters = QDir::NoFilter, + QDir::SortFlags sort = QDir::NoSort) const; + /// Returns the list of the entries in the directory with zip64 support. + /** + \param nameFilters The list of file patterns to list, uses the same + syntax as QDir. + \param filters The entry type filters, only Files and Dirs are + accepted. + \param sort Sorting mode. + */ + QList entryInfoList64(const QStringList &nameFilters, + QDir::Filters filters = QDir::NoFilter, + QDir::SortFlags sort = QDir::NoSort) const; + /// Returns the list of the entries in the directory with zip64 support. + /** + \overload + + The same as entryInfoList64(QStringList(), filters, sort). + */ + QList entryInfoList64(QDir::Filters filters = QDir::NoFilter, + QDir::SortFlags sort = QDir::NoSort) const; + /// Returns the list of the entry names in the directory. + /** + The same as entryInfoList(nameFilters, filters, sort), but only + returns entry names. + */ + QStringList entryList(const QStringList &nameFilters, + QDir::Filters filters = QDir::NoFilter, + QDir::SortFlags sort = QDir::NoSort) const; + /// Returns the list of the entry names in the directory. + /** + \overload + + The same as entryList(QStringList(), filters, sort). + */ + QStringList entryList(QDir::Filters filters = QDir::NoFilter, + QDir::SortFlags sort = QDir::NoSort) const; + /// Returns \c true if the entry with the specified name exists. + /** + The ".." is considered to exist if the current directory + is not root. The "." and "/" are considered to + always exist. Paths starting with "/" are relative to + the archive root, other paths are relative to the current dir. + */ + bool exists(const QString &fileName) const; + /// Return \c true if the directory pointed by this QuaZipDir exists. + bool exists() const; + /// Returns the full path to the specified file. + /** + Doesn't check if the file actually exists. + */ + QString filePath(const QString &fileName) const; + /// Returns the default filter. + QDir::Filters filter(); + /// Returns if the QuaZipDir points to the root of the archive. + /** + Not that the root path is the empty string, not '/'. + */ + bool isRoot() const; + /// Return the default name filter. + QStringList nameFilters() const; + /// Returns the path to the current dir. + /** + The path never starts with '/', and the root path is an empty + string. + */ + QString path() const; + /// Returns the path to the specified file relative to the current dir. + /** + * This function is mostly useless, provided only for the sake of + * completeness. + * + * @param fileName The path to the file, should start with "/" + * if relative to the archive root. + * @return Path relative to the current dir. + */ + QString relativeFilePath(const QString &fileName) const; + /// Sets the default case sensitivity mode. + void setCaseSensitivity(QuaZip::CaseSensitivity caseSensitivity); + /// Sets the default filter. + void setFilter(QDir::Filters filters); + /// Sets the default name filter. + void setNameFilters(const QStringList &nameFilters); + /// Goes to the specified path. + /** + The difference from cd() is that this function never checks if the + path actually exists and doesn't use relative paths, so it's + possible to go to the root directory with setPath(""). + + Note that this function still chops the trailing and/or leading + '/' and treats a single '/' as the root path (path() will still + return an empty string). + */ + void setPath(const QString &path); + /// Sets the default sorting mode. + void setSorting(QDir::SortFlags sort); + /// Returns the default sorting mode. + QDir::SortFlags sorting() const; +}; + +#endif // QUAZIP_QUAZIPDIR_H diff --git a/libraries/include/quazipfile.h b/libraries/include/quazipfile.h new file mode 100644 index 0000000..b49c50b --- /dev/null +++ b/libraries/include/quazipfile.h @@ -0,0 +1,508 @@ +#ifndef QUA_ZIPFILE_H +#define QUA_ZIPFILE_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant, see +quazip/(un)zip.h files for details, basically it's zlib license. + **/ + +#include + +#include "quazip_global.h" +#include "quazip.h" +#include "quazipnewinfo.h" + +class QuaZipFilePrivate; + +/// A file inside ZIP archive. +/** \class QuaZipFile quazipfile.h + * This is the most interesting class. Not only it provides C++ + * interface to the ZIP/UNZIP package, but also integrates it with Qt by + * subclassing QIODevice. This makes possible to access files inside ZIP + * archive using QTextStream or QDataStream, for example. Actually, this + * is the main purpose of the whole QuaZip library. + * + * You can either use existing QuaZip instance to create instance of + * this class or pass ZIP archive file name to this class, in which case + * it will create internal QuaZip object. See constructors' descriptions + * for details. Writing is only possible with the existing instance. + * + * Note that due to the underlying library's limitation it is not + * possible to use multiple QuaZipFile instances to open several files + * in the same archive at the same time. If you need to write to + * multiple files in parallel, then you should write to temporary files + * first, then pack them all at once when you have finished writing. If + * you need to read multiple files inside the same archive in parallel, + * you should extract them all into a temporary directory first. + * + * \section quazipfile-sequential Sequential or random-access? + * + * At the first thought, QuaZipFile has fixed size, the start and the + * end and should be therefore considered random-access device. But + * there is one major obstacle to making it random-access: ZIP/UNZIP API + * does not support seek() operation and the only way to implement it is + * through reopening the file and re-reading to the required position, + * but this is prohibitively slow. + * + * Therefore, QuaZipFile is considered to be a sequential device. This + * has advantage of availability of the ungetChar() operation (QIODevice + * does not implement it properly for non-sequential devices unless they + * support seek()). Disadvantage is a somewhat strange behaviour of the + * size() and pos() functions. This should be kept in mind while using + * this class. + * + **/ +class QUAZIP_EXPORT QuaZipFile: public QIODevice { + friend class QuaZipFilePrivate; + Q_OBJECT + private: + QuaZipFilePrivate *p; + // these are not supported nor implemented + QuaZipFile(const QuaZipFile& that); + QuaZipFile& operator=(const QuaZipFile& that); + protected: + /// Implementation of the QIODevice::readData(). + qint64 readData(char *data, qint64 maxSize); + /// Implementation of the QIODevice::writeData(). + qint64 writeData(const char *data, qint64 maxSize); + public: + /// Constructs a QuaZipFile instance. + /** You should use setZipName() and setFileName() or setZip() before + * trying to call open() on the constructed object. + **/ + QuaZipFile(); + /// Constructs a QuaZipFile instance. + /** \a parent argument specifies this object's parent object. + * + * You should use setZipName() and setFileName() or setZip() before + * trying to call open() on the constructed object. + **/ + QuaZipFile(QObject *parent); + /// Constructs a QuaZipFile instance. + /** \a parent argument specifies this object's parent object and \a + * zipName specifies ZIP archive file name. + * + * You should use setFileName() before trying to call open() on the + * constructed object. + * + * QuaZipFile constructed by this constructor can be used for read + * only access. Use QuaZipFile(QuaZip*,QObject*) for writing. + **/ + QuaZipFile(const QString& zipName, QObject *parent =nullptr); + /// Constructs a QuaZipFile instance. + /** \a parent argument specifies this object's parent object, \a + * zipName specifies ZIP archive file name and \a fileName and \a cs + * specify a name of the file to open inside archive. + * + * QuaZipFile constructed by this constructor can be used for read + * only access. Use QuaZipFile(QuaZip*,QObject*) for writing. + * + * \sa QuaZip::setCurrentFile() + **/ + QuaZipFile(const QString& zipName, const QString& fileName, + QuaZip::CaseSensitivity cs =QuaZip::csDefault, QObject *parent =nullptr); + /// Constructs a QuaZipFile instance. + /** \a parent argument specifies this object's parent object. + * + * \a zip is the pointer to the existing QuaZip object. This + * QuaZipFile object then can be used to read current file in the + * \a zip or to write to the file inside it. + * + * \warning Using this constructor for reading current file can be + * tricky. Let's take the following example: + * \code + * QuaZip zip("archive.zip"); + * zip.open(QuaZip::mdUnzip); + * zip.setCurrentFile("file-in-archive"); + * QuaZipFile file(&zip); + * file.open(QIODevice::ReadOnly); + * // ok, now we can read from the file + * file.read(somewhere, some); + * zip.setCurrentFile("another-file-in-archive"); // oops... + * QuaZipFile anotherFile(&zip); + * anotherFile.open(QIODevice::ReadOnly); + * anotherFile.read(somewhere, some); // this is still ok... + * file.read(somewhere, some); // and this is NOT + * \endcode + * So, what exactly happens here? When we change current file in the + * \c zip archive, \c file that references it becomes invalid + * (actually, as far as I understand ZIP/UNZIP sources, it becomes + * closed, but QuaZipFile has no means to detect it). + * + * Summary: do not close \c zip object or change its current file as + * long as QuaZipFile is open. Even better - use another constructors + * which create internal QuaZip instances, one per object, and + * therefore do not cause unnecessary trouble. This constructor may + * be useful, though, if you already have a QuaZip instance and do + * not want to access several files at once. Good example: + * \code + * QuaZip zip("archive.zip"); + * zip.open(QuaZip::mdUnzip); + * // first, we need some information about archive itself + * QByteArray comment=zip.getComment(); + * // and now we are going to access files inside it + * QuaZipFile file(&zip); + * for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { + * file.open(QIODevice::ReadOnly); + * // do something cool with file here + * file.close(); // do not forget to close! + * } + * zip.close(); + * \endcode + **/ + QuaZipFile(QuaZip *zip, QObject *parent =nullptr); + /// Destroys a QuaZipFile instance. + /** Closes file if open, destructs internal QuaZip object (if it + * exists and \em is internal, of course). + **/ + virtual ~QuaZipFile(); + /// Returns the ZIP archive file name. + /** If this object was created by passing QuaZip pointer to the + * constructor, this function will return that QuaZip's file name + * (or null string if that object does not have file name yet). + * + * Otherwise, returns associated ZIP archive file name or null + * string if there are no name set yet. + * + * \sa setZipName() getFileName() + **/ + QString getZipName()const; + /// Returns a pointer to the associated QuaZip object. + /** Returns \c NULL if there is no associated QuaZip or it is + * internal (so you will not mess with it). + **/ + QuaZip* getZip()const; + /// Returns file name. + /** This function returns file name you passed to this object either + * by using + * QuaZipFile(const QString&,const QString&,QuaZip::CaseSensitivity,QObject*) + * or by calling setFileName(). Real name of the file may differ in + * case if you used case-insensitivity. + * + * Returns null string if there is no file name set yet. This is the + * case when this QuaZipFile operates on the existing QuaZip object + * (constructor QuaZipFile(QuaZip*,QObject*) or setZip() was used). + * + * \sa getActualFileName + **/ + QString getFileName() const; + /// Returns case sensitivity of the file name. + /** This function returns case sensitivity argument you passed to + * this object either by using + * QuaZipFile(const QString&,const QString&,QuaZip::CaseSensitivity,QObject*) + * or by calling setFileName(). + * + * Returns unpredictable value if getFileName() returns null string + * (this is the case when you did not used setFileName() or + * constructor above). + * + * \sa getFileName + **/ + QuaZip::CaseSensitivity getCaseSensitivity() const; + /// Returns the actual file name in the archive. + /** This is \em not a ZIP archive file name, but a name of file inside + * archive. It is not necessary the same name that you have passed + * to the + * QuaZipFile(const QString&,const QString&,QuaZip::CaseSensitivity,QObject*), + * setFileName() or QuaZip::setCurrentFile() - this is the real file + * name inside archive, so it may differ in case if the file name + * search was case-insensitive. + * + * Equivalent to calling getCurrentFileName() on the associated + * QuaZip object. Returns null string if there is no associated + * QuaZip object or if it does not have a current file yet. And this + * is the case if you called setFileName() but did not open the + * file yet. So this is perfectly fine: + * \code + * QuaZipFile file("somezip.zip"); + * file.setFileName("somefile"); + * QString name=file.getName(); // name=="somefile" + * QString actual=file.getActualFileName(); // actual is null string + * file.open(QIODevice::ReadOnly); + * QString actual=file.getActualFileName(); // actual can be "SoMeFiLe" on Windows + * \endcode + * + * \sa getZipName(), getFileName(), QuaZip::CaseSensitivity + **/ + QString getActualFileName()const; + /// Sets the ZIP archive file name. + /** Automatically creates internal QuaZip object and destroys + * previously created internal QuaZip object, if any. + * + * Will do nothing if this file is already open. You must close() it + * first. + **/ + void setZipName(const QString& zipName); + /// Returns \c true if the file was opened in raw mode. + /** If the file is not open, the returned value is undefined. + * + * \sa open(OpenMode,int*,int*,bool,const char*) + **/ + bool isRaw() const; + /// Binds to the existing QuaZip instance. + /** This function destroys internal QuaZip object, if any, and makes + * this QuaZipFile to use current file in the \a zip object for any + * further operations. See QuaZipFile(QuaZip*,QObject*) for the + * possible pitfalls. + * + * Will do nothing if the file is currently open. You must close() + * it first. + **/ + void setZip(QuaZip *zip); + /// Sets the file name. + /** Will do nothing if at least one of the following conditions is + * met: + * - ZIP name has not been set yet (getZipName() returns null + * string). + * - This QuaZipFile is associated with external QuaZip. In this + * case you should call that QuaZip's setCurrentFile() function + * instead! + * - File is already open so setting the name is meaningless. + * + * \sa QuaZip::setCurrentFile + **/ + void setFileName(const QString& fileName, QuaZip::CaseSensitivity cs =QuaZip::csDefault); + /// Opens a file for reading. + /** Returns \c true on success, \c false otherwise. + * Call getZipError() to get error code. + * + * \note Since ZIP/UNZIP API provides buffered reading only, + * QuaZipFile does not support unbuffered reading. So do not pass + * QIODevice::Unbuffered flag in \a mode, or open will fail. + **/ + virtual bool open(OpenMode mode); + /// Opens a file for reading. + /** \overload + * Argument \a password specifies a password to decrypt the file. If + * it is NULL then this function behaves just like open(OpenMode). + **/ + inline bool open(OpenMode mode, const char *password) + {return open(mode, nullptr, nullptr, false, password);} + /// Opens a file for reading. + /** \overload + * Argument \a password specifies a password to decrypt the file. + * + * An integers pointed by \a method and \a level will receive codes + * of the compression method and level used. See unzip.h. + * + * If raw is \c true then no decompression is performed. + * + * \a method should not be \c NULL. \a level can be \c NULL if you + * don't want to know the compression level. + **/ + bool open(OpenMode mode, int *method, int *level, bool raw, const char *password =nullptr); + /// Opens a file for writing. + /** \a info argument specifies information about file. It should at + * least specify a correct file name. Also, it is a good idea to + * specify correct timestamp (by default, current time will be + * used). See QuaZipNewInfo. + * + * The \a password argument specifies the password for crypting. Pass NULL + * if you don't need any crypting. The \a crc argument was supposed + * to be used for crypting too, but then it turned out that it's + * false information, so you need to set it to 0 unless you want to + * use the raw mode (see below). + * + * Arguments \a method and \a level specify compression method and + * level. The only method supported is Z_DEFLATED, but you may also + * specify 0 for no compression. If all of the files in the archive + * use both method 0 and either level 0 is explicitly specified or + * data descriptor writing is disabled with + * QuaZip::setDataDescriptorWritingEnabled(), then the + * resulting archive is supposed to be compatible with the 1.0 ZIP + * format version, should you need that. Except for this, \a level + * has no other effects with method 0. + * + * If \a raw is \c true, no compression is performed. In this case, + * \a crc and uncompressedSize field of the \a info are required. + * + * Arguments \a windowBits, \a memLevel, \a strategy provide zlib + * algorithms tuning. See deflateInit2() in zlib. + **/ + bool open(OpenMode mode, const QuaZipNewInfo& info, + const char *password =nullptr, quint32 crc =0, + int method =Z_DEFLATED, int level =Z_DEFAULT_COMPRESSION, bool raw =false, + int windowBits =-MAX_WBITS, int memLevel =DEF_MEM_LEVEL, int strategy =Z_DEFAULT_STRATEGY); + /// Returns \c true, but \ref quazipfile-sequential "beware"! + virtual bool isSequential()const; + /// Returns current position in the file. + /** Implementation of the QIODevice::pos(). When reading, this + * function is a wrapper to the ZIP/UNZIP unztell(), therefore it is + * unable to keep track of the ungetChar() calls (which is + * non-virtual and therefore is dangerous to reimplement). So if you + * are using ungetChar() feature of the QIODevice, this function + * reports incorrect value until you get back characters which you + * ungot. + * + * When writing, pos() returns number of bytes already written + * (uncompressed unless you use raw mode). + * + * \note Although + * \ref quazipfile-sequential "QuaZipFile is a sequential device" + * and therefore pos() should always return zero, it does not, + * because it would be misguiding. Keep this in mind. + * + * This function returns -1 if the file or archive is not open. + * + * Error code returned by getZipError() is not affected by this + * function call. + **/ + virtual qint64 pos()const; + /// Returns \c true if the end of file was reached. + /** This function returns \c false in the case of error. This means + * that you called this function on either not open file, or a file + * in the not open archive or even on a QuaZipFile instance that + * does not even have QuaZip instance associated. Do not do that + * because there is no means to determine whether \c false is + * returned because of error or because end of file was reached. + * Well, on the other side you may interpret \c false return value + * as "there is no file open to check for end of file and there is + * no end of file therefore". + * + * When writing, this function always returns \c true (because you + * are always writing to the end of file). + * + * Error code returned by getZipError() is not affected by this + * function call. + **/ + virtual bool atEnd()const; + /// Returns file size. + /** This function returns csize() if the file is open for reading in + * raw mode, usize() if it is open for reading in normal mode and + * pos() if it is open for writing. + * + * Returns -1 on error, call getZipError() to get error code. + * + * \note This function returns file size despite that + * \ref quazipfile-sequential "QuaZipFile is considered to be sequential device", + * for which size() should return bytesAvailable() instead. But its + * name would be very misguiding otherwise, so just keep in mind + * this inconsistence. + **/ + virtual qint64 size()const; + /// Returns compressed file size. + /** Equivalent to calling getFileInfo() and then getting + * compressedSize field, but more convenient and faster. + * + * File must be open for reading before calling this function. + * + * Returns -1 on error, call getZipError() to get error code. + **/ + qint64 csize()const; + /// Returns uncompressed file size. + /** Equivalent to calling getFileInfo() and then getting + * uncompressedSize field, but more convenient and faster. See + * getFileInfo() for a warning. + * + * File must be open for reading before calling this function. + * + * Returns -1 on error, call getZipError() to get error code. + **/ + qint64 usize()const; + /// Gets information about current file. + /** This function does the same thing as calling + * QuaZip::getCurrentFileInfo() on the associated QuaZip object, + * but you can not call getCurrentFileInfo() if the associated + * QuaZip is internal (because you do not have access to it), while + * you still can call this function in that case. + * + * File must be open for reading before calling this function. + * + * \return \c false in the case of an error. + * + * This function doesn't support zip64, but will still work fine on zip64 + * archives if file sizes are below 4 GB, otherwise the values will be set + * as if converted using QuaZipFileInfo64::toQuaZipFileInfo(). + * + * \sa getFileInfo(QuaZipFileInfo64*) + **/ + bool getFileInfo(QuaZipFileInfo *info); + /// Gets information about current file with zip64 support. + /** + * @overload + * + * \sa getFileInfo(QuaZipFileInfo*) + */ + bool getFileInfo(QuaZipFileInfo64 *info); + /// Closes the file. + /** Call getZipError() to determine if the close was successful. + **/ + virtual void close(); + /// Returns the error code returned by the last ZIP/UNZIP API call. + int getZipError() const; + /// Returns the number of bytes available for reading. + virtual qint64 bytesAvailable() const; + /// Returns the local extra field + /** + There are two (optional) local extra fields associated with a file. + One is located in the central header and is available along + with the rest of the file information in @ref QuaZipFileInfo64::extra. + Another is located before the file itself, + and is returned by this function. The file must be open first. + + @return the local extra field, or an empty array if there is none + (or file is not open) + */ + QByteArray getLocalExtraField(); + /// Returns the extended modification timestamp + /** + * The getExt*Time() functions only work if there is an extended timestamp + * extra field (ID 0x5455) present. Otherwise, they all return invalid null + * timestamps. + * + * Modification time, but not other times, can also be accessed through + * @ref QuaZipFileInfo64 without the need to open the file first. + * + * @sa dateTime + * @sa QuaZipFileInfo64::getExtModTime() + * @sa getExtAcTime() + * @sa getExtCrTime() + * @return The extended modification time, UTC + */ + QDateTime getExtModTime(); + /// Returns the extended access timestamp + /** + * The getExt*Time() functions only work if there is an extended timestamp + * extra field (ID 0x5455) present. Otherwise, they all return invalid null + * timestamps. + * @sa dateTime + * @sa QuaZipFileInfo64::getExtModTime() + * @sa getExtModTime() + * @sa getExtCrTime() + * @return The extended access time, UTC + */ + QDateTime getExtAcTime(); + /// Returns the extended creation timestamp + /** + * The getExt*Time() functions only work if there is an extended timestamp + * extra field (ID 0x5455) present. Otherwise, they all return invalid null + * timestamps. + * @sa dateTime + * @sa QuaZipFileInfo64::getExtModTime() + * @sa getExtModTime() + * @sa getExtAcTime() + * @return The extended creation time, UTC + */ + QDateTime getExtCrTime(); +}; + +#endif diff --git a/libraries/include/quazipfileinfo.h b/libraries/include/quazipfileinfo.h new file mode 100644 index 0000000..1083f8b --- /dev/null +++ b/libraries/include/quazipfileinfo.h @@ -0,0 +1,232 @@ +#ifndef QUA_ZIPFILEINFO_H +#define QUA_ZIPFILEINFO_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant and contributors, +see quazip/(un)zip.h files for details. Basically it's the zlib license. +*/ + +#include +#include +#include +#include + +#include "quazip_global.h" + +/// The typedef to store extra field parse results +typedef QHash > QuaExtraFieldHash; + +/// Information about a file inside archive. +/** + * \deprecated Use QuaZipFileInfo64 instead. Not only it supports large files, + * but also more convenience methods as well. + * + * Call QuaZip::getCurrentFileInfo() or QuaZipFile::getFileInfo() to + * fill this structure. */ +struct QUAZIP_EXPORT QuaZipFileInfo { + /// File name. + QString name; + /// Version created by. + quint16 versionCreated; + /// Version needed to extract. + quint16 versionNeeded; + /// General purpose flags. + quint16 flags; + /// Compression method. + quint16 method; + /// Last modification date and time. + QDateTime dateTime; + /// CRC. + quint32 crc; + /// Compressed file size. + quint32 compressedSize; + /// Uncompressed file size. + quint32 uncompressedSize; + /// Disk number start. + quint16 diskNumberStart; + /// Internal file attributes. + quint16 internalAttr; + /// External file attributes. + quint32 externalAttr; + /// Comment. + QString comment; + /// Extra field. + QByteArray extra; + /// Get the file permissions. + /** + Returns the high 16 bits of external attributes converted to + QFile::Permissions. + */ + QFile::Permissions getPermissions() const; +}; + +/// Information about a file inside archive (with zip64 support). +/** Call QuaZip::getCurrentFileInfo() or QuaZipFile::getFileInfo() to + * fill this structure. */ +struct QUAZIP_EXPORT QuaZipFileInfo64 { + /// File name. + QString name; + /// Version created by. + quint16 versionCreated; + /// Version needed to extract. + quint16 versionNeeded; + /// General purpose flags. + quint16 flags; + /// Compression method. + quint16 method; + /// Last modification date and time. + /** + * This is the time stored in the standard ZIP header. This format only allows + * to store time with 2-second precision, so the seconds will always be even + * and the milliseconds will always be zero. If you need more precise + * date and time, you can try to call the getNTFSmTime() function or + * its siblings, provided that the archive itself contains these NTFS times. + */ + QDateTime dateTime; + /// CRC. + quint32 crc; + /// Compressed file size. + quint64 compressedSize; + /// Uncompressed file size. + quint64 uncompressedSize; + /// Disk number start. + quint16 diskNumberStart; + /// Internal file attributes. + quint16 internalAttr; + /// External file attributes. + quint32 externalAttr; + /// Comment. + QString comment; + /// Extra field. + QByteArray extra; + /// Get the file permissions. + /** + Returns the high 16 bits of external attributes converted to + QFile::Permissions. + */ + QFile::Permissions getPermissions() const; + /// Checks whether the file is a symbolic link. + /** + Returns true iff the highest 16 bits of the external attributes + indicate that the file is a symbolic link according to Unix file mode. + */ + bool isSymbolicLink() const; + /// Converts to QuaZipFileInfo + /** + If any of the fields are greater than 0xFFFFFFFFu, they are set to + 0xFFFFFFFFu exactly, not just truncated. This function should be mainly used + for compatibility with the old code expecting QuaZipFileInfo, in the cases + when it's impossible or otherwise unadvisable (due to ABI compatibility + reasons, for example) to modify that old code to use QuaZipFileInfo64. + + \return \c true if all fields converted correctly, \c false if an overflow + occured. + */ + bool toQuaZipFileInfo(QuaZipFileInfo &info) const; + /// Returns the NTFS modification time + /** + * The getNTFS*Time() functions only work if there is an NTFS extra field + * present. Otherwise, they all return invalid null timestamps. + * @param fineTicks If not null, the fractional part of milliseconds returned + * there, measured in 100-nanosecond ticks. Will be set to + * zero if there is no NTFS extra field. + * @sa dateTime + * @sa getNTFSaTime() + * @sa getNTFScTime() + * @return The NTFS modification time, UTC + */ + QDateTime getNTFSmTime(int *fineTicks = nullptr) const; + /// Returns the NTFS access time + /** + * The getNTFS*Time() functions only work if there is an NTFS extra field + * present. Otherwise, they all return invalid null timestamps. + * @param fineTicks If not null, the fractional part of milliseconds returned + * there, measured in 100-nanosecond ticks. Will be set to + * zero if there is no NTFS extra field. + * @sa dateTime + * @sa getNTFSmTime() + * @sa getNTFScTime() + * @return The NTFS access time, UTC + */ + QDateTime getNTFSaTime(int *fineTicks = nullptr) const; + /// Returns the NTFS creation time + /** + * The getNTFS*Time() functions only work if there is an NTFS extra field + * present. Otherwise, they all return invalid null timestamps. + * @param fineTicks If not null, the fractional part of milliseconds returned + * there, measured in 100-nanosecond ticks. Will be set to + * zero if there is no NTFS extra field. + * @sa dateTime + * @sa getNTFSmTime() + * @sa getNTFSaTime() + * @return The NTFS creation time, UTC + */ + QDateTime getNTFScTime(int *fineTicks = nullptr) const; + /// Returns the extended modification timestamp + /** + * The getExt*Time() functions only work if there is an extended timestamp + * extra field (ID 0x5455) present. Otherwise, they all return invalid null + * timestamps. + * + * QuaZipFileInfo64 only contains the modification time because it's extracted + * from @ref extra, which contains the global extra field, and access and + * creation time are in the local header which can be accessed through + * @ref QuaZipFile. + * + * @sa dateTime + * @sa QuaZipFile::getExtModTime() + * @sa QuaZipFile::getExtAcTime() + * @sa QuaZipFile::getExtCrTime() + * @return The extended modification time, UTC + */ + QDateTime getExtModTime() const; + /// Checks whether the file is encrypted. + bool isEncrypted() const {return (flags & 1) != 0;} + /// Parses extra field + /** + * The returned hash table contains a list of data blocks for every header ID + * in the provided extra field. The number of data blocks in a hash table value + * equals to the number of occurrences of the appropriate header id. In most cases, + * a block with a specific header ID only occurs once, and therefore the returned + * hash table will contain a list consisting of a single element for that header ID. + * + * @param extraField extra field to parse + * @return header id to list of data block hash + */ + static QuaExtraFieldHash parseExtraField(const QByteArray &extraField); + /// Extracts extended time from the extra field + /** + * Utility function used by various getExt*Time() functions, but can be used directly + * if the extra field is obtained elsewhere (from a third party library, for example). + * + * @param extra the extra field for a file + * @param flag 1 - modification time, 2 - access time, 4 - creation time + * @return the extracted time or null QDateTime if not present + * @sa getExtModTime() + * @sa QuaZipFile::getExtModTime() + * @sa QuaZipFile::getExtAcTime() + * @sa QuaZipFile::getExtCrTime() + */ + static QDateTime getExtTime(const QByteArray &extra, int flag); +}; + +#endif diff --git a/libraries/include/quazipnewinfo.h b/libraries/include/quazipnewinfo.h new file mode 100644 index 0000000..bad70c2 --- /dev/null +++ b/libraries/include/quazipnewinfo.h @@ -0,0 +1,208 @@ +#ifndef QUA_ZIPNEWINFO_H +#define QUA_ZIPNEWINFO_H + +/* +Copyright (C) 2005-2014 Sergey A. Tachenov + +This file is part of QuaZip. + +QuaZip is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 2.1 of the License, or +(at your option) any later version. + +QuaZip 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with QuaZip. If not, see . + +See COPYING file for the full LGPL text. + +Original ZIP package is copyrighted by Gilles Vollant, see +quazip/(un)zip.h files for details, basically it's zlib license. + **/ + +#include +#include +#include + +#include "quazip_global.h" + +#include "quazipfileinfo.h" + +/// Information about a file to be created. +/** This structure holds information about a file to be created inside + * ZIP archive. At least name should be set to something correct before + * passing this structure to + * QuaZipFile::open(OpenMode,const QuaZipNewInfo&,int,int,bool). + * + * Zip64 support of this structure is slightly limited: in the raw mode (when + * a pre-compressed file is written into a ZIP file as-is), it is necessary + * to specify the uncompressed file size and the appropriate field is 32 bit. + * Since the raw mode is used extremely rare, there is no real need to have + * a separate QuaZipNewInfo64 structure like QuaZipFileInfo64. It may be added + * in the future though, if there is a demand for the raw mode with zip64 + * archives. + **/ +struct QUAZIP_EXPORT QuaZipNewInfo { + /// File name. + /** This field holds file name inside archive, including path relative + * to archive root. + **/ + QString name; + /// File timestamp. + /** This is the last file modification date and time. Will be stored + * in the archive central directory. It is a good practice to set it + * to the source file timestamp instead of archive creating time. Use + * setFileDateTime() or QuaZipNewInfo(const QString&, const QString&). + **/ + QDateTime dateTime; + /// File internal attributes. + quint16 internalAttr; + /// File external attributes. + /** + The highest 16 bits contain Unix file permissions and type (dir or + file). The constructor QuaZipNewInfo(const QString&, const QString&) + takes permissions from the provided file. + */ + quint32 externalAttr; + /// File comment. + /** Will be encoded in UTF-8 encoding. + **/ + QString comment; + /// File local extra field. + QByteArray extraLocal; + /// File global extra field. + QByteArray extraGlobal; + /// Uncompressed file size. + /** This is only needed if you are using raw file zipping mode, i. e. + * adding precompressed file in the zip archive. + **/ + ulong uncompressedSize; + /// Constructs QuaZipNewInfo instance. + /** Initializes name with \a name, dateTime with current date and + * time. Attributes are initialized with zeros, comment and extra + * field with null values. + **/ + QuaZipNewInfo(const QString& name); + /// Constructs QuaZipNewInfo instance. + /** Initializes name with \a name. Timestamp and permissions are taken + * from the specified file. If the \a file does not exists or its timestamp + * is inaccessible (e. g. you do not have read permission for the + * directory file in), uses current time and zero permissions. Other attributes are + * initialized with zeros, comment and extra field with null values. + * + * \sa setFileDateTime() + **/ + QuaZipNewInfo(const QString& name, const QString& file); + /// Initializes the new instance from existing file info. + /** Mainly used when copying files between archives. + * + * Both extra fields are initialized to existing.extra. + * @brief QuaZipNewInfo + * @param existing + */ + QuaZipNewInfo(const QuaZipFileInfo &existing); + /// Initializes the new instance from existing file info. + /** Mainly used when copying files between archives. + * + * Both extra fields are initialized to existing.extra. + * @brief QuaZipNewInfo + * @param existing + */ + QuaZipNewInfo(const QuaZipFileInfo64 &existing); + /// Sets the file timestamp from the existing file. + /** Use this function to set the file timestamp from the existing + * file. Use it like this: + * \code + * QuaZipFile zipFile(&zip); + * QFile file("file-to-add"); + * file.open(QIODevice::ReadOnly); + * QuaZipNewInfo info("file-name-in-archive"); + * info.setFileDateTime("file-to-add"); // take the timestamp from file + * zipFile.open(QIODevice::WriteOnly, info); + * \endcode + * + * This function does not change dateTime if some error occured (e. g. + * file is inaccessible). + **/ + void setFileDateTime(const QString& file); + /// Sets the file permissions from the existing file. + /** + Takes permissions from the file and sets the high 16 bits of + external attributes. Uses QFileInfo to get permissions on all + platforms. + */ + void setFilePermissions(const QString &file); + /// Sets the file permissions. + /** + Modifies the highest 16 bits of external attributes. The type part + is set to dir if the name ends with a slash, and to regular file + otherwise. + */ + void setPermissions(QFile::Permissions permissions); + /// Sets the NTFS times from an existing file. + /** + * If the file doesn't exist, a warning is printed to the stderr and nothing + * is done. Otherwise, all three times, as reported by + * QFileInfo::lastModified(), QFileInfo::lastRead() and + * QFileInfo::birthTime() (>=Qt5.10) or QFileInfo::created(), are written to + * the NTFS extra field record. + * + * The NTFS record is written to + * both the local and the global extra fields, updating the existing record + * if there is one, or creating a new one and appending it to the end + * of each extra field. + * + * The microseconds will be zero, as they aren't reported by QFileInfo. + * @param fileName + */ + void setFileNTFSTimes(const QString &fileName); + /// Sets the NTFS modification time. + /** + * The time is written into the NTFS record in + * both the local and the global extra fields, updating the existing record + * if there is one, or creating a new one and appending it to the end + * of each extra field. When updating an existing record, all other fields + * are left intact. + * @param mTime The new modification time. + * @param fineTicks The fractional part of milliseconds, in 100-nanosecond + * ticks (i. e. 9999 ticks = 999.9 microsecond). Values greater than + * 9999 will add milliseconds or even seconds, but this can be + * confusing and therefore is discouraged. + */ + void setFileNTFSmTime(const QDateTime &mTime, int fineTicks = 0); + /// Sets the NTFS access time. + /** + * The time is written into the NTFS record in + * both the local and the global extra fields, updating the existing record + * if there is one, or creating a new one and appending it to the end + * of each extra field. When updating an existing record, all other fields + * are left intact. + * @param aTime The new access time. + * @param fineTicks The fractional part of milliseconds, in 100-nanosecond + * ticks (i. e. 9999 ticks = 999.9 microsecond). Values greater than + * 9999 will add milliseconds or even seconds, but this can be + * confusing and therefore is discouraged. + */ + void setFileNTFSaTime(const QDateTime &aTime, int fineTicks = 0); + /// Sets the NTFS creation time. + /** + * The time is written into the NTFS record in + * both the local and the global extra fields, updating the existing record + * if there is one, or creating a new one and appending it to the end + * of each extra field. When updating an existing record, all other fields + * are left intact. + * @param cTime The new creation time. + * @param fineTicks The fractional part of milliseconds, in 100-nanosecond + * ticks (i. e. 9999 ticks = 999.9 microsecond). Values greater than + * 9999 will add milliseconds or even seconds, but this can be + * confusing and therefore is discouraged. + */ + void setFileNTFScTime(const QDateTime &cTime, int fineTicks = 0); +}; + +#endif diff --git a/libraries/include/unzip.h b/libraries/include/unzip.h new file mode 100644 index 0000000..e898332 --- /dev/null +++ b/libraries/include/unzip.h @@ -0,0 +1,461 @@ +/* unzip.h -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------------- + + Changes + + See header of unzip64.c + + --------------------------------------------------------------------------- + + As per the requirement above, this file is plainly marked as modified + by Sergey A. Tachenov. Most modifications include the I/O API redesign + to support QIODevice interface. Some improvements and small fixes were also made. +*/ + +#ifndef _unz64_H +#define _unz64_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _ZLIB_H +#include +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagunzFile__ { int unused; } unzFile__; +typedef unzFile__ *unzFile; +#else +typedef voidp unzFile; +#endif + + +#define UNZ_OK (0) +#define UNZ_END_OF_LIST_OF_FILE (-100) +#define UNZ_ERRNO (Z_ERRNO) +#define UNZ_EOF (0) +#define UNZ_PARAMERROR (-102) +#define UNZ_BADZIPFILE (-103) +#define UNZ_INTERNALERROR (-104) +#define UNZ_CRCERROR (-105) + +#define UNZ_AUTO_CLOSE 0x01u +#define UNZ_DEFAULT_FLAGS UNZ_AUTO_CLOSE +#define UNZ_ENCODING_UTF8 0x0800u + +/* tm_unz contain date/time info */ +typedef struct tm_unz_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_unz; + +/* unz_global_info structure contain global data about the ZIPfile + These data comes from the end of central dir */ +typedef struct unz_global_info64_s +{ + ZPOS64_T number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info64; + +typedef struct unz_global_info_s +{ + uLong number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info; + +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_info64_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + ZPOS64_T compressed_size; /* compressed size 8 bytes */ + ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info64; + +typedef struct unz_file_info_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + uLong compressed_size; /* compressed size 4 bytes */ + uLong uncompressed_size; /* uncompressed size 4 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info; + +extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, + const char* fileName2, + int iCaseSensitivity)); +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) +*/ + + +extern unzFile ZEXPORT unzOpen OF((voidpf file)); +extern unzFile ZEXPORT unzOpen64 OF((voidpf file)); +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer + "zlib/zlib113.zip". + If the zipfile cannot be opened (file don't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. + the "64" function take a const void* pointer, because the path is just the + value passed to the open64_file_func callback. + Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path + is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* + does not describe the reality +*/ + + +extern unzFile ZEXPORT unzOpen2 OF((voidpf file, + zlib_filefunc_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unzOpen, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +extern unzFile ZEXPORT unzOpen2_64 OF((voidpf file, + zlib_filefunc64_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unz64Open, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + + +/* + * Exported by Sergey A. Tachenov to implement some QuaZip features. This + * function MAY change signature in order to implement even more features. + * You have been warned! + * */ +extern unzFile unzOpenInternal (voidpf file, + zlib_filefunc64_32_def* pzlib_filefunc64_32_def, + int is64bitOpenFunction, unsigned flags); + + + +extern int ZEXPORT unzClose OF((unzFile file)); +/* + Close a ZipFile opened with unzipOpen. + If there is files inside the .Zip opened with unzOpenCurrentFile (see later), + these files MUST be closed with unzipCloseCurrentFile before call unzipClose. + return UNZ_OK if there is no problem. */ + +extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, + unz_global_info *pglobal_info)); + +extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file, + unz_global_info64 *pglobal_info)); + +extern int ZEXPORT unzGetFileFlags OF((unzFile file, unsigned* pflags)); +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ + + +extern int ZEXPORT unzGetGlobalComment OF((unzFile file, + char *szComment, + uLong uSizeBuf)); +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ + + +/***************************************************************************/ +/* Unzip package allow you browse the directory of the zipfile */ + +extern int ZEXPORT unzGoToFirstFile OF((unzFile file)); +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ + +extern int ZEXPORT unzGoToNextFile OF((unzFile file)); +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ + +extern int ZEXPORT unzLocateFile OF((unzFile file, + const char *szFileName, + int iCaseSensitivity)); +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ + + +/* ****************************************** */ +/* Ryan supplied functions */ +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_pos_s +{ + uLong pos_in_zip_directory; /* offset in zip file directory */ + uLong num_of_file; /* # of file */ +} unz_file_pos; + +extern int ZEXPORT unzGetFilePos( + unzFile file, + unz_file_pos* file_pos); + +extern int ZEXPORT unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos); + +typedef struct unz64_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */ + ZPOS64_T num_of_file; /* # of file */ +} unz64_file_pos; + +extern int ZEXPORT unzGetFilePos64( + unzFile file, + unz64_file_pos* file_pos); + +extern int ZEXPORT unzGoToFilePos64( + unzFile file, + const unz64_file_pos* file_pos); + +/* ****************************************** */ + +extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); +/* + Get Info about the current file + if pfile_info!=NULL, the *pfile_info structure will contain somes info about + the current file + if szFileName!=NULL, the filemane string will be copied in szFileName + (fileNameBufferSize is the size of the buffer) + if extraField!=NULL, the extra field information will be copied in extraField + (extraFieldBufferSize is the size of the buffer). + This is the Central-header version of the extra field + if szComment!=NULL, the comment string of the file will be copied in szComment + (commentBufferSize is the size of the buffer) +*/ + + +/** Addition for GDAL : START */ + +extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file)); + +/** Addition for GDAL : END */ + + +/***************************************************************************/ +/* for reading the content of the current zipfile, you can open it, read data + from it, and close it (you can close it before reading all the file) + */ + +extern int ZEXPORT unzOpenCurrentFile OF((unzFile file)); +/* + Open for reading data the current file in the zipfile. + If there is no error, the return value is UNZ_OK. +*/ + +extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, + const char* password)); +/* + Open for reading data the current file in the zipfile. + password is a crypting password + If there is no error, the return value is UNZ_OK. +*/ + +extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, + int* method, + int* level, + int raw)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + +extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, + int* method, + int* level, + int raw, + const char* password)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + + +extern int ZEXPORT unzCloseCurrentFile OF((unzFile file)); +/* + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ + +extern int ZEXPORT unzReadCurrentFile OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read bytes from the current file (opened by unzOpenCurrentFile) + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ + +extern z_off_t ZEXPORT unztell OF((unzFile file)); + +extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file)); +/* + Give the current position in uncompressed data +*/ + +extern int ZEXPORT unzeof OF((unzFile file)); +/* + return 1 if the end of file was reached, 0 elsewhere +*/ + +extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read extra field from the current file (opened by unzOpenCurrentFile) + This is the local-header version of the extra field (sometimes, there is + more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ + +/***************************************************************************/ + +/* Get the current file offset */ +extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file); +extern uLong ZEXPORT unzGetOffset (unzFile file); + +/* Set the current file offset */ +extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos); +extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); + +extern int ZEXPORT unzSetFlags(unzFile file, unsigned flags); +extern int ZEXPORT unzClearFlags(unzFile file, unsigned flags); + +#ifdef __cplusplus +} +#endif + +#endif /* _unz64_H */ diff --git a/libraries/include/zconf.h b/libraries/include/zconf.h new file mode 100644 index 0000000..77398c1 --- /dev/null +++ b/libraries/include/zconf.h @@ -0,0 +1,534 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/libraries/include/zip.h b/libraries/include/zip.h new file mode 100644 index 0000000..5837d95 --- /dev/null +++ b/libraries/include/zip.h @@ -0,0 +1,391 @@ +/* zip.h -- IO on .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------- + + Changes + + See header of zip.h + + --------------------------------------------------------------------------- + + As per the requirement above, this file is plainly marked as modified + by Sergey A. Tachenov. Most modifications include the I/O API redesign + to support QIODevice interface. Some improvements and small fixes were also made. + +*/ + +#ifndef _zip12_H +#define _zip12_H + +#ifdef __cplusplus +extern "C" { +#endif + +//#define HAVE_BZIP2 + +#ifndef _ZLIB_H +#include +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagzipFile__ { int unused; } zipFile__; +typedef zipFile__ *zipFile; +#else +typedef voidp zipFile; +#endif + +#define ZIP_OK (0) +#define ZIP_EOF (0) +#define ZIP_ERRNO (Z_ERRNO) +#define ZIP_PARAMERROR (-102) +#define ZIP_BADZIPFILE (-103) +#define ZIP_INTERNALERROR (-104) + +#define ZIP_WRITE_DATA_DESCRIPTOR 0x8u +#define ZIP_AUTO_CLOSE 0x1u +#define ZIP_SEQUENTIAL 0x2u +#define ZIP_ENCODING_UTF8 0x0800u +#define ZIP_DEFAULT_FLAGS (ZIP_AUTO_CLOSE | ZIP_WRITE_DATA_DESCRIPTOR) + +#ifndef DEF_MEM_LEVEL +# if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +# else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +# endif +#endif +/* default memLevel */ + +/* tm_zip contain date/time info */ +typedef struct tm_zip_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_zip; + +typedef struct +{ + tm_zip tmz_date; /* date in understandable format */ + uLong dosDate; /* if dos_date == 0, tmu_date is used */ +/* uLong flag; */ /* general purpose bit flag 2 bytes */ + + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ +} zip_fileinfo; + +typedef const char* zipcharpc; + + +#define APPEND_STATUS_CREATE (0) +#define APPEND_STATUS_CREATEAFTER (1) +#define APPEND_STATUS_ADDINZIP (2) + +extern zipFile ZEXPORT zipOpen OF((voidpf file, int append)); +extern zipFile ZEXPORT zipOpen64 OF((voidpf file, int append)); +/* + Create a zipfile. + the file argument depends on the API used, for QuaZip it's a QIODevice + pointer. + if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip + will be created at the end of the file. + (useful if the file contain a self extractor code) + if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will + add files in existing zip (be sure you don't add file that doesn't exist) + If the zipfile cannot be opened, the return value is NULL. + Else, the return value is a zipFile Handle, usable with other function + of this zip package. +*/ + +/* Note : there is no delete function into a zipfile. + If you want delete file into a zipfile, you must open a zipfile, and create another + Of couse, you can use RAW reading and writing to copy the file you did not want delte +*/ + +extern zipFile ZEXPORT zipOpen2 OF((voidpf file, + int append, + zipcharpc* globalcomment, + zlib_filefunc_def* pzlib_filefunc_def)); + +extern zipFile ZEXPORT zipOpen2_64 OF((voidpf file, + int append, + zipcharpc* globalcomment, + zlib_filefunc64_def* pzlib_filefunc_def)); + +/* + * Exported by Sergey A. Tachenov to suit the needs of QuaZip. + * Note that this function MAY change signature in order to + * provide new QuaZip features. You have been warned! + * */ +extern zipFile ZEXPORT zipOpen3 (voidpf file, + int append, + zipcharpc* globalcomment, + zlib_filefunc64_32_def* pzlib_filefunc64_32_def, + unsigned flags); + +extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level)); + +extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int zip64)); + +/* + Open a file in the ZIP for writing. + filename : the filename in zip (if NULL, '-' without quote will be used + *zipfi contain supplemental information + if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local + contains the extrafield data the the local header + if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global + contains the extrafield data the the local header + if comment != NULL, comment contain the comment string + method contain the compression method (0 for store, Z_DEFLATED for deflate) + level contain the level of compression (can be Z_DEFAULT_COMPRESSION) + zip64 is set to 1 if a zip64 extended information block should be added to the local file header. + this MUST be '1' if the uncompressed size is >= 0xffffffff. + +*/ + + +extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw)); + + +extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int zip64)); +/* + Same than zipOpenNewFileInZip, except if raw=1, we write raw file + */ + +extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting)); + +extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + int zip64 + )); + +/* + Same than zipOpenNewFileInZip2, except + windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 + password : crypting password (NULL for no crypting) + crcForCrypting : crc of file to compress (needed for crypting) + */ + +extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + uLong versionMadeBy, + uLong flagBase + )); + + +extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + uLong versionMadeBy, + uLong flagBase, + int zip64 + )); +/* + Same than zipOpenNewFileInZip4, except + versionMadeBy : value for Version made by field + flag : value for flag field (compression level info will be added) + */ + + +extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, + const void* buf, + unsigned len)); +/* + Write data in the zipfile +*/ + +extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); +/* + Close the current file in the zipfile +*/ + +extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, + uLong uncompressed_size, + uLong crc32)); + +extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file, + ZPOS64_T uncompressed_size, + uLong crc32)); + +/* + Close the current file in the zipfile, for file opened with + parameter raw=1 in zipOpenNewFileInZip2 + uncompressed_size and crc32 are value for the uncompressed size +*/ + +extern int ZEXPORT zipClose OF((zipFile file, + const char* global_comment)); +/* + Close the zipfile +*/ + + +extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader)); +/* + zipRemoveExtraInfoBlock - Added by Mathias Svensson + + Remove extra information block from a extra information data for the local file header or central directory header + + It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode. + + 0x0001 is the signature header for the ZIP64 extra information blocks + + usage. + Remove ZIP64 Extra information from a central director extra field data + zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001); + + Remove ZIP64 Extra information from a Local File Header extra field data + zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001); +*/ + +/* + Added by Sergey A. Tachenov to tweak zipping behaviour. +*/ +extern int ZEXPORT zipSetFlags(zipFile file, unsigned flags); +extern int ZEXPORT zipClearFlags(zipFile file, unsigned flags); + +#ifdef __cplusplus +} +#endif + +#endif /* _zip64_H */ diff --git a/libraries/include/zlib.h b/libraries/include/zlib.h new file mode 100644 index 0000000..f09cdaf --- /dev/null +++ b/libraries/include/zlib.h @@ -0,0 +1,1912 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.11" +#define ZLIB_VERNUM 0x12b0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 11 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more ouput + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if any input has been consumed in a previous + deflate() call, then the input available so far is compressed with the old + level and strategy using deflate(strm, Z_BLOCK). There are three approaches + for the compression levels 0, 1..3, and 4..9 respectively. The new level + and strategy will take effect at the next call of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will not automatically decode concatenated gzip streams. + inflate() will return Z_STREAM_END at the end of the gzip stream. The state + would need to be reset to continue decoding a subsequent gzip stream. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Three times that size in buffer space is allocated. A larger buffer + size of, for example, 64K or 128K bytes will noticeably increase the speed + of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. Previously provided + data is flushed before the parameter change. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read up to nitems items of size size from file to buf, otherwise operating + as gzread() does. This duplicates the interface of stdio's fread(), with + size_t request and return types. If the library defines size_t, then + z_size_t is identical to size_t. If not, then z_size_t is an unsigned + integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevetheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, reseting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + gzfwrite() writes nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/libraries/src/quazip-1.3.tar.gz b/libraries/src/quazip-1.3.tar.gz new file mode 100644 index 0000000..1ad635a Binary files /dev/null and b/libraries/src/quazip-1.3.tar.gz differ diff --git a/libraries/src/quazip-1.3.tar.gz.sha256 b/libraries/src/quazip-1.3.tar.gz.sha256 new file mode 100644 index 0000000..427c5e6 --- /dev/null +++ b/libraries/src/quazip-1.3.tar.gz.sha256 @@ -0,0 +1 @@ +c1239559cd6860cab80a0fd81f4204e606f9324f702dab6166b0960676ee1754 quazip-1.3.tar.gz diff --git a/libraries/src/zlib-1.2.11.tar.gz b/libraries/src/zlib-1.2.11.tar.gz new file mode 100644 index 0000000..a4873ba Binary files /dev/null and b/libraries/src/zlib-1.2.11.tar.gz differ diff --git a/libraries/src/zlib-1.2.11.tar.gz.md5 b/libraries/src/zlib-1.2.11.tar.gz.md5 new file mode 100644 index 0000000..00e8803 --- /dev/null +++ b/libraries/src/zlib-1.2.11.tar.gz.md5 @@ -0,0 +1 @@ +0095d2d2d1f3442ce1318336637b695f zlib-1.2.11.tar.gz diff --git a/libraries/unix/quazip/libquazip1-qt5.so b/libraries/unix/quazip/libquazip1-qt5.so new file mode 120000 index 0000000..9835706 --- /dev/null +++ b/libraries/unix/quazip/libquazip1-qt5.so @@ -0,0 +1 @@ +libquazip1-qt5.so.1.3.0 \ No newline at end of file diff --git a/libraries/unix/quazip/libquazip1-qt5.so.1.3 b/libraries/unix/quazip/libquazip1-qt5.so.1.3 new file mode 100755 index 0000000..f4fceed Binary files /dev/null and b/libraries/unix/quazip/libquazip1-qt5.so.1.3 differ diff --git a/libraries/unix/quazip/libquazip1-qt5.so.1.3.0 b/libraries/unix/quazip/libquazip1-qt5.so.1.3.0 new file mode 120000 index 0000000..8b3e22c --- /dev/null +++ b/libraries/unix/quazip/libquazip1-qt5.so.1.3.0 @@ -0,0 +1 @@ +libquazip1-qt5.so.1.3 \ No newline at end of file diff --git a/libraries/unix/quazip/libz.so b/libraries/unix/quazip/libz.so new file mode 120000 index 0000000..95e0ebd --- /dev/null +++ b/libraries/unix/quazip/libz.so @@ -0,0 +1 @@ +libz.so.1.2.11 \ No newline at end of file diff --git a/libraries/unix/quazip/libz.so.1 b/libraries/unix/quazip/libz.so.1 new file mode 120000 index 0000000..95e0ebd --- /dev/null +++ b/libraries/unix/quazip/libz.so.1 @@ -0,0 +1 @@ +libz.so.1.2.11 \ No newline at end of file diff --git a/libraries/unix/quazip/libz.so.1.2.11 b/libraries/unix/quazip/libz.so.1.2.11 new file mode 100755 index 0000000..a1acc0e Binary files /dev/null and b/libraries/unix/quazip/libz.so.1.2.11 differ diff --git a/libraries/unix/quazip/pre-built_quazip/quazip-1.3-qt5-x64-linux.tar.gz b/libraries/unix/quazip/pre-built_quazip/quazip-1.3-qt5-x64-linux.tar.gz new file mode 100644 index 0000000..c537087 Binary files /dev/null and b/libraries/unix/quazip/pre-built_quazip/quazip-1.3-qt5-x64-linux.tar.gz differ diff --git a/libraries/unix/quazip/pre-built_quazip/quazip-1.3-qt5-x64-linux.tar.gz.md5 b/libraries/unix/quazip/pre-built_quazip/quazip-1.3-qt5-x64-linux.tar.gz.md5 new file mode 100644 index 0000000..45cda0a --- /dev/null +++ b/libraries/unix/quazip/pre-built_quazip/quazip-1.3-qt5-x64-linux.tar.gz.md5 @@ -0,0 +1 @@ +aef27a5cbe1a20c8083cdf886f7b7f69 quazip-1.3-qt5-x64-linux.tar.gz diff --git a/libraries/win/quazip/libquazip1-qt5.dll b/libraries/win/quazip/libquazip1-qt5.dll new file mode 100644 index 0000000..5b3d0b4 Binary files /dev/null and b/libraries/win/quazip/libquazip1-qt5.dll differ diff --git a/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt5-x86-win.zip b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt5-x86-win.zip new file mode 100644 index 0000000..41fde87 Binary files /dev/null and b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt5-x86-win.zip differ diff --git a/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt5-x86-win.zip.md5 b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt5-x86-win.zip.md5 new file mode 100644 index 0000000..f2c377e --- /dev/null +++ b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt5-x86-win.zip.md5 @@ -0,0 +1 @@ +05c286bd790e4911d321cde3d578726a quazip-1.3-qt5-x86-win.zip diff --git a/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt6-x64-win.zip b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt6-x64-win.zip new file mode 100644 index 0000000..7a97a6c Binary files /dev/null and b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt6-x64-win.zip differ diff --git a/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt6-x64-win.zip.md5 b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt6-x64-win.zip.md5 new file mode 100644 index 0000000..08caeda --- /dev/null +++ b/libraries/win/quazip/pre-built_quazip/quazip-1.3-qt6-x64-win.zip.md5 @@ -0,0 +1 @@ +f68705b21236ed94765518dc4d6791e5 quazip-1.3-qt6-x64-win.zip diff --git a/libraries/win/quazip/zlib1.dll b/libraries/win/quazip/zlib1.dll new file mode 100644 index 0000000..54d5911 Binary files /dev/null and b/libraries/win/quazip/zlib1.dll differ diff --git a/resources/fonts/LICENSE b/resources/fonts/LICENSE new file mode 100644 index 0000000..ae3f041 --- /dev/null +++ b/resources/fonts/LICENSE @@ -0,0 +1,97 @@ +Copyright (c) 2016, Saber Rastikerdar (saber.rastikerdar@gmail.com), + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + + +---------------------------------------------- +Non-Arabic glyphs and data are borrowed from Open Sans font under the Apache License, Version 2.0 \ No newline at end of file diff --git a/resources/fonts/README.md b/resources/fonts/README.md new file mode 100644 index 0000000..3b64658 --- /dev/null +++ b/resources/fonts/README.md @@ -0,0 +1,133 @@ +# Sahel-Font +A Persian (Farsi) Font with variable version + +![Sahel-VF](./sample-variable.gif) + +فونت فارسی ساحل +[نمایش فونت](http://rastikerdar.github.io/sahel-font/) +[صفحه دریافت (دانلود) بسته فونت شامل فایل های ttf,woff,eot](https://github.com/rastikerdar/sahel-font/releases) +با تشکر از برنامه [FontForge](https://fontforge.github.io) +نسخه وریبل فونت با نام `Sahel-VF‍` در بسته فونت موجود می‌باشد. +نسخه‌های بدون حروف لاتین یا تمام ارقام فارسی درون بسته فشرده موجود می‌باشد. +فرآیند تولید بسته نهایی شامل انواع نسخه‌ها و فرمت‌ها توسط ابزار [fontbuilder](https://github.com/rastikerdar/fontbuilder) انجام می‌شود. + +## Known problems for variable version +- mark placement distortion. + +## To Do (variable) +- [x] Adding all 3 Weights as masters to variable version. +- [ ] Font testing page +- [ ] Latin section is empty. It's better to use an opensource variable font with a wide range. +- [ ] Testing font in all supported programs. +- [ ] Adding other axes. + +## طریقه استفاده در صفحات وب + +

+کد زیر را در قسمت style یا فایل css وارد نمایید: +

+ + +```css +@font-face { + font-family: Sahel; + src: url('Sahel.eot'); + src: url('Sahel.eot?#iefix') format('embedded-opentype'), + url('Sahel.woff2') format('woff2'), + url('Sahel.woff') format('woff'), + url('Sahel.ttf') format('truetype'); + font-weight: normal; +} + +@font-face { + font-family: Sahel; + src: url('Sahel-Bold.eot'); + src: url('Sahel-Bold.eot?#iefix') format('embedded-opentype'), + url('Sahel-Bold.woff2') format('woff2'), + url('Sahel-Bold.woff') format('woff'), + url('Sahel-Bold.ttf') format('truetype'); + font-weight: bold; +} + +@font-face { + font-family: Sahel; + src: url('Sahel-Light.eot'); + src: url('Sahel-Light.eot?#iefix') format('embedded-opentype'), + url('Sahel-Light.woff2') format('woff2'), + url('Sahel-Light.woff') format('woff'), + url('Sahel-Light.ttf') format('truetype'); + font-weight: 300; +} + +@font-face { + font-family: Sahel; + src: url('Sahel-SemiBold.eot'); + src: url('Sahel-SemiBold.eot?#iefix') format('embedded-opentype'), + url('Sahel-SemiBold.woff2') format('woff2'), + url('Sahel-SemiBold.woff') format('woff'), + url('Sahel-SemiBold.ttf') format('truetype'); + font-weight: 600; +} + +@font-face { + font-family: Sahel; + src: url('Sahel-Black.eot'); + src: url('Sahel-Black.eot?#iefix') format('embedded-opentype'), + url('Sahel-Black.woff2') format('woff2'), + url('Sahel-Black.woff') format('woff'), + url('Sahel-Black.ttf') format('truetype'); + font-weight: 900; +} +``` + +## طریقه استفاده از نسخه متغیر variable + +```css +@font-face { + font-family: Sahel VF; + src: url('Sahel-VF.woff2') format('woff2'); +} + +.foo { + font-family: Sahel VF; + font-variation-settings: "wght" 600; +} + +.bar { + font-family: Sahel VF; + font-variation-settings: "wght" 900; +} + +``` + +## Install + +Grab the [latest release](https://github.com/rastikerdar/sahel-font/releases/latest) file. + +Or [RawGit](https://rawgit.com) CDN: + +```html + +``` + +Replace [X.Y.Z] with the latest version (e.g. 3.4.0) and integrate the font into your CSS: + +``` +font-family: 'Sahel', sans-serif; +``` + +#### Arch Linux + +Arch user's could use [sahel-fonts](https://aur.archlinux.org/packages/sahel-fonts/) package from [AUR](https://aur.archlinux.org/) repository to install sahel font. Use your favorite [AUR helper](https://wiki.archlinux.org/index.php/AUR_helpers) like pacaur or yaourt for installing package: + +```shell +pacaur -S sahel-fonts +``` + +## Contributors + +- Amin Abedi [@aminabedi68](https://github.com/aminabedi68) + +## License +2016 Saber Rastikerdar ([@rastikerdar](https://github.com/rastikerdar)). See the `LICENSE` file. + diff --git a/resources/fonts/Sahel-Bold-FD.ttf b/resources/fonts/Sahel-Bold-FD.ttf new file mode 100644 index 0000000..e8a98f8 Binary files /dev/null and b/resources/fonts/Sahel-Bold-FD.ttf differ diff --git a/resources/fonts/Sahel-Bold.ttf b/resources/fonts/Sahel-Bold.ttf new file mode 100644 index 0000000..107ba11 Binary files /dev/null and b/resources/fonts/Sahel-Bold.ttf differ diff --git a/resources/fonts/Sahel-FD.ttf b/resources/fonts/Sahel-FD.ttf new file mode 100644 index 0000000..b9a8140 Binary files /dev/null and b/resources/fonts/Sahel-FD.ttf differ diff --git a/resources/fonts/Sahel.ttf b/resources/fonts/Sahel.ttf new file mode 100644 index 0000000..3b65334 Binary files /dev/null and b/resources/fonts/Sahel.ttf differ diff --git a/resources/html/about_author.html b/resources/html/about_author.html new file mode 100644 index 0000000..1ef47af --- /dev/null +++ b/resources/html/about_author.html @@ -0,0 +1,20 @@ + + +

بعد از قبولی در دانشگاه در سال ۹۱، علاقه زیادی به شعر پیدا کردم. سایت گنجور، از بهترین منابع برای دوست‌داران شعر و ادبیات است. از آنجا که همیشه جست‌وجوی دقیق در اطلاعات و دسترسی به آن برایم بسیار مهم بوده، و نرم‌افزار مستقل و مناسبی برای مطالعه شعر در لینوکس (گنو/لینوکس) پیدا نکردم، به همین دلیل تصمیم به نوشتن ${AppNameFa} گرفتم. حدود ۲ ماه نوشتن آن در دوره دانشجویی طول کشید. بعد از اتمام آن، از این نرم‌افزار استفاده شخصی می‌کردم. در واقع هیچ‌گاه انتشار آن به ذهنم خطور نکرد. دانشگاه تمام شد و وارد دوره سربازی شدم. بعد از اتمام دوره سربازی، برای مدتی سردرگم، و نسبت به آینده نگران بودم. تا اینکه تصمیم قطعی به شرکت در آزمون دستیاری پزشکی گرفتم. در همین حین بیت زیبای زیر از حافظ را دیدم:

+

مزرع سبز فلک دیدم و داس مه نو
یادم از کشته خویش آمد و هنگام درو

+

ناخودآگاه یاد نرم‌افزار ${AppNameFa}، و فکر انتشار آن افتادم. بنابراین تصمیم گرفتم که در کنار درس خواندن، ${AppNameFa} را در قالب AppImage منتشر کنم، که Dependency به پکیج‌های دیگری نداشته باشد و به راحتی در اکثر توزیع‌های لینوکس اجرا شود. در واقع ایده اصلی قالب AppImage، یک برنامه = یک فایل (one app = one file) است. در این مدت، توابع منسوخ مورد استفاده در ${AppNameFa} را با توابع جدید چارچوب Qt به‌روز، و ${AppNameFa} را با Qt5 و Qt6 سازگار کردم.

+

امیدوارم این نرم‌افزار مورد علاقه کاربران قرار گیرد.

+

ابوطالب روشن، اردیبهشت ۱۴۰۱

+ diff --git a/resources/html/about_ghazal.html b/resources/html/about_ghazal.html new file mode 100644 index 0000000..ed4ae0e --- /dev/null +++ b/resources/html/about_ghazal.html @@ -0,0 +1,42 @@ + + +

${AppNameFa}

+

نسخه: ${AppVersion}

+

تاریخ ساخت: ${AppBuildDate}

+

${AppNameFa} یک کتابخانه شعر فارسی و برنامه‌ای رایگان و متن‌باز است. ${AppNameFa} به زبان ++C و با استفاده از چارچوب Qt نوشته شده است. این برنامه از پایگاه داده گنجور بهره می‌برد. این برنامه از کتابخانه Qt، نسخهٔ ${QtVersion} استفاده می‌کند.

+

آدرس‌ها:

+

Publisher: ${Rosybit} (${RosybitUrl})

+

${AppName}: ${AppUrl}

+

GitHub: ${GitHub}

+

Email: ${Email}

+

تشکر ویژه از:

+

حمیدرضا محمدی (بنیانگذار سایت گنجور)

+

صابر راستی‌کردار (سازندهٔ فونت ساحل)

+

سیمون پیتر (به انگلیسی: Simon Peter) (سازنده و توسعه‌دهندهٔ قالب AppImage)

+

پروانه:

+

این برنامه تحت مجوز ام‌آی‌تی (MIT) است.

+

This program is licensed under MIT.

+ diff --git a/resources/html/search_examples.html b/resources/html/search_examples.html new file mode 100644 index 0000000..9e1a532 --- /dev/null +++ b/resources/html/search_examples.html @@ -0,0 +1,47 @@ + + +

روش‌های جست‌وجو:

+

۱. برای جست‌وجوی عین کلمه یا عبارت، آن را بین Double Quotation ("") قرار دهید.
+۲. برای جست‌وجوی رکوردهایی که شامل کلمات مشخصی باشند، بین کلمات علامت مثبت (+) قرار دهید.
+۳. برای جست‌وجوی رکوردهایی که می‌خواهید کلمات مشخصی در آن‌ها نباشند، قبل از آن علامت منفی (-) قرار دهید.
+۴. برای جست‌وجوی رکوردهایی که شامل کلمات مشخصی با ترتیب مشخص باشند، بین کلمات دو علامت مثبت (++) قرار دهید.
+۵. برای جست‌وجوی رکوردهایی که حداقل یکی از کلمات مشخص را داشته باشند، بین کلمات علامت Pipe (|) قرار دهید.
+۶. برای شمارش تعداد یک کلمه یا عبارت، قبل از آن، علامت Hash (#) قرار دهید. در انتها نیز رکوردهایی که بیشتر از یک کلمه یا عبارت را دارند، در جدول قرار می‌گیرند.

+

نمونه‌ها:

+

عشق++یار | حرمان
+عشق + داستان | کمال + جمال - عشق
+سلمی | سلیمی | "سعاد"
+سر + منزل + جانان | سر + منزل + مقصود
+ناظر + منظور | خادم + مخدوم | قاتل + مقتول | قاصد + مقصود | شاهد + مشهود | راغب + مرغوب | حافظ + محفوظ
+الف + دوست
+"سخن عشق" + زبان
+سخن + عشق + زبان
+سخن++عاشق++زبان
+سیمین + سنگین
+#او در
+#"سلام"
+#نام او
+#هزاران
+#سرود
+حرمان - "هنر"
+حرمان - هنر
+#"یار"
+#"حق"
+خسرو + شیرین | وامق + عذرا | زهره + منوچهر | لیلی + مجنون | بیژن + منیژه | زال + رودابه | شیرین + فرهاد | ناظر + منظور | ویس + رامین | عروه + عفرا | دعد + رباب | یوسف + زلیخا | رابعه + بکتاش | سلامان + آبسال

+ diff --git a/resources/images/ghazal-128x128.png b/resources/images/ghazal-128x128.png new file mode 100644 index 0000000..c3371bb Binary files /dev/null and b/resources/images/ghazal-128x128.png differ diff --git a/resources/images/ghazal-16x16.png b/resources/images/ghazal-16x16.png new file mode 100644 index 0000000..0f9e513 Binary files /dev/null and b/resources/images/ghazal-16x16.png differ diff --git a/resources/images/ghazal-24x24.png b/resources/images/ghazal-24x24.png new file mode 100644 index 0000000..c6eecef Binary files /dev/null and b/resources/images/ghazal-24x24.png differ diff --git a/resources/images/ghazal-256x256.png b/resources/images/ghazal-256x256.png new file mode 100644 index 0000000..e2f57e8 Binary files /dev/null and b/resources/images/ghazal-256x256.png differ diff --git a/resources/images/ghazal-32x32.png b/resources/images/ghazal-32x32.png new file mode 100644 index 0000000..114ac5a Binary files /dev/null and b/resources/images/ghazal-32x32.png differ diff --git a/resources/images/ghazal-48x48.png b/resources/images/ghazal-48x48.png new file mode 100644 index 0000000..b46c7af Binary files /dev/null and b/resources/images/ghazal-48x48.png differ diff --git a/resources/images/ghazal-512x512.png b/resources/images/ghazal-512x512.png new file mode 100644 index 0000000..fc82d28 Binary files /dev/null and b/resources/images/ghazal-512x512.png differ diff --git a/resources/images/ghazal-64x64.png b/resources/images/ghazal-64x64.png new file mode 100644 index 0000000..c67f056 Binary files /dev/null and b/resources/images/ghazal-64x64.png differ diff --git a/resources/images/ghazal.ico b/resources/images/ghazal.ico new file mode 100644 index 0000000..87743ad Binary files /dev/null and b/resources/images/ghazal.ico differ diff --git a/resources/images/hafez-white.svg b/resources/images/hafez-white.svg new file mode 100644 index 0000000..bb6c8ab --- /dev/null +++ b/resources/images/hafez-white.svg @@ -0,0 +1,576 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/images/hafez.svg b/resources/images/hafez.svg new file mode 100644 index 0000000..3ae4676 --- /dev/null +++ b/resources/images/hafez.svg @@ -0,0 +1,550 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/resource.qrc b/resources/resource.qrc new file mode 100644 index 0000000..45335e3 --- /dev/null +++ b/resources/resource.qrc @@ -0,0 +1,14 @@ + + + fonts/Sahel.ttf + fonts/Sahel-Bold.ttf + fonts/Sahel-FD.ttf + fonts/Sahel-Bold-FD.ttf + html/about_author.html + html/about_ghazal.html + html/search_examples.html + images/ghazal-256x256.png + images/hafez.svg + images/hafez-white.svg + + diff --git a/resources/resource_win.rc b/resources/resource_win.rc new file mode 100644 index 0000000..b2d3e9a --- /dev/null +++ b/resources/resource_win.rc @@ -0,0 +1,36 @@ +IDI_ICON1 ICON "images/ghazal.ico" + +#include + +VS_VERSION_INFO VERSIONINFO +FILEVERSION 1,4,0,0 +PRODUCTVERSION 1,4,0,0 + +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + BEGIN + VALUE "CompanyName", "Rosybit" + VALUE "FileDescription", "Ghazal: The library of persian poetry" + VALUE "FileVersion", "1.4.0.0" + VALUE "InternalName", "Ghazal" + VALUE "LegalCopyright", "Copyright (c) 2012-2022 Aboutaleb Roshan" + VALUE "LegalTrademarks1", "This program is licensed under MIT" + VALUE "OriginalFilename", "Ghazal.exe" + VALUE "ProductName", "Ghazal" + VALUE "ProductVersion", "1.4" + END + END + + BLOCK "VarFileInfo" + BEGIN + /* The following line should only be modified for localized versions. */ + /* It consists of any number of WORD,WORD pairs, with each pair */ + /* describing a language,codepage combination supported by the file. */ + /* */ + /* For example, a file might have values "0x409,1252" indicating that it */ + /* supports English language (0x409) in the Windows ANSI codepage (1252). */ + VALUE "Translation", 0x409, 1252 + END +END diff --git a/resources/themes/darkstyle.qrc b/resources/themes/darkstyle.qrc new file mode 100644 index 0000000..1bcbdf7 --- /dev/null +++ b/resources/themes/darkstyle.qrc @@ -0,0 +1,28 @@ + + + darkstyle/darkstyle.qss + darkstyle/icon_close.png + darkstyle/icon_restore.png + darkstyle/icon_undock.png + darkstyle/icon_branch_closed.png + darkstyle/icon_branch_end.png + darkstyle/icon_branch_more.png + darkstyle/icon_branch_open.png + darkstyle/icon_vline.png + darkstyle/icon_checkbox_checked.png + darkstyle/icon_checkbox_indeterminate.png + darkstyle/icon_checkbox_unchecked.png + darkstyle/icon_checkbox_checked_pressed.png + darkstyle/icon_checkbox_indeterminate_pressed.png + darkstyle/icon_checkbox_unchecked_pressed.png + darkstyle/icon_checkbox_checked_disabled.png + darkstyle/icon_checkbox_indeterminate_disabled.png + darkstyle/icon_checkbox_unchecked_disabled.png + darkstyle/icon_radiobutton_checked.png + darkstyle/icon_radiobutton_unchecked.png + darkstyle/icon_radiobutton_checked_pressed.png + darkstyle/icon_radiobutton_unchecked_pressed.png + darkstyle/icon_radiobutton_checked_disabled.png + darkstyle/icon_radiobutton_unchecked_disabled.png + + diff --git a/resources/themes/darkstyle/darkstyle.qss b/resources/themes/darkstyle/darkstyle.qss new file mode 100644 index 0000000..04dbe60 --- /dev/null +++ b/resources/themes/darkstyle/darkstyle.qss @@ -0,0 +1,312 @@ +QToolTip{ + color:#ffffff; + background-color:palette(base); + border:1px solid palette(highlight); + border-radius:4px; +} +QStatusBar{ + background-color:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + color:palette(mid); +} +QMenuBar{ + background-color:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border-bottom:2px solid rgba(25,25,25,75); +} +QMenuBar::item{ + spacing:2px; + padding:3px 4px; + background:transparent; +} +QMenuBar::item:selected{ + background-color:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(106,106,106,255),stop:1 rgba(106,106,106,255)); +} +QMenuBar::item:pressed{ + background-color:palette(highlight); +} +QToolBar::top{ + background-color:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border-bottom:3px solid qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); +} +QToolBar::bottom{ + background-color:qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border-top:3px solid qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); +} +QToolBar::left{ + background-color:qlineargradient(x1:0,y1:0,x2:1,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border-right:3px solid qlineargradient(x1:0,y1:0,x2:1,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); +} +QToolBar::right{ + background-color:qlineargradient(x1:1,y1:0,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border-left:3px solid qlineargradient(x1:1,y1:0,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); +} +QMainWindow::separator{ + width:6px; + height:5px; + padding:2px; +} +QSplitter::handle:horizontal{ + width:10px; +} +QSplitter::handle:vertical{ + height:10px; +} +QMainWindow::separator:hover,QSplitter::handle:hover{ + background:palette(highlight); +} +QDockWidget::title{ + padding:4px; + background-color:qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border:1px solid rgba(25,25,25,75); + border-bottom:2px solid rgba(25,25,25,75); +} +QDockWidget{ + titlebar-close-icon:url(:/darkstyle/icon_close.png); + titlebar-normal-icon:url(:/darkstyle/icon_restore.png); +} +QDockWidget::close-button,QDockWidget::float-button{ + subcontrol-position:top right; + subcontrol-origin:margin; + position:absolute; + top:3px; + bottom:0px; + width:20px; + height:20px; +} +QDockWidget::close-button{ + right:3px; +} +QDockWidget::float-button{ + right:25px; +} +QGroupBox{ + background-color:rgba(66,66,66,50%); + margin-top:27px; + border:1px solid rgba(25,25,25,127); + border-radius:4px; +} +QGroupBox::title{ + subcontrol-origin:margin; + subcontrol-position:left top; + padding:4px 6px; + margin-left:3px; + background-color:qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border:1px solid rgba(25,25,25,75); + border-bottom:2px solid rgb(127,127,127); + border-top-left-radius:4px; + border-top-right-radius:4px; +} +QTabWidget::pane{ + background-color:rgba(66,66,66,50%); + border-top:1px solid rgba(25,25,25,50%); +} +QTabWidget::tab-bar{ + left:3px; + top:1px; +} +QTabBar{ + background-color:transparent; + qproperty-drawBase:0; + border-bottom:1px solid rgba(25,25,25,50%); +} +QTabBar::tab{ + padding:4px 6px; + background-color:qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border:1px solid rgba(25,25,25,75); + border-top-left-radius:4px; + border-top-right-radius:4px; +} +QTabBar::tab:selected,QTabBar::tab:hover{ + background-color:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(53,53,53,127),stop:1 rgba(66,66,66,50%)); + border-bottom-color:rgba(66,66,66,75%); +} +QTabBar::tab:selected{ + border-bottom:2px solid palette(highlight); +} +QTabBar::tab::selected:disabled{ + border-bottom:2px solid rgb(127,127,127); +} +QTabBar::tab:!selected{ + margin-top:2px; +} +QTabBar::close-button { + image:url(:/darkstyle/icon_close.png); + border:1px solid transparent; + border-radius:2px; +} +QTabBar::close-button:hover { + background-color:qlineargradient(x1:0,y1:0,x2:0,y2:1,stop:0 rgba(106,106,106,255),stop:1 rgba(106,106,106,75)); + border:1px solid palette(base); +} +QTabBar::close-button:pressed { + background-color:qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border:1px solid palette(base); +} +QCheckBox::indicator{ + width:18px; + height:18px; +} +QCheckBox::indicator:checked,QTreeView::indicator:checked,QTableView::indicator:checked,QListWidget::indicator:checked,QTableWidget::indicator:checked,QGroupBox::indicator:checked{ + image:url(:/darkstyle/icon_checkbox_checked.png); +} +QCheckBox::indicator:checked:pressed,QTreeView::indicator:checked:pressed,QTableView::indicator:checked:pressed,QListWidget::indicator:checked:pressed,QTableWidget::indicator:checked:pressed,QGroupBox::indicator:checked:pressed{ + image:url(:/darkstyle/icon_checkbox_checked_pressed.png); +} +QCheckBox::indicator:checked:disabled,QTreeView::indicator:checked:disabled,QTableView::indicator:checked:disabled,QListWidget::indicator:checked:disabled,QTableWidget::indicator:checked:disabled,QGroupBox::indicator:checked:disabled{ + image:url(:/darkstyle/icon_checkbox_checked_disabled.png); +} +QCheckBox::indicator:unchecked,QTreeView::indicator:unchecked,QTableView::indicator:unchecked,QListWidget::indicator:unchecked,QTableWidget::indicator:unchecked,QGroupBox::indicator:unchecked{ + image:url(:/darkstyle/icon_checkbox_unchecked.png); +} +QCheckBox::indicator:unchecked:pressed,QTreeView::indicator:unchecked:pressed,QTableView::indicator:unchecked:pressed,QListWidget::indicator:unchecked:pressed,QTableWidget::indicator:unchecked:pressed,QGroupBox::indicator:unchecked:pressed{ + image:url(:/darkstyle/icon_checkbox_unchecked_pressed.png); +} +QCheckBox::indicator:unchecked:disabled,QTreeView::indicator:unchecked:disabled,QTableView::indicator:unchecked:disabled,QListWidget::indicator:unchecked:disabled,QTableWidget::indicator:unchecked:disabled,QGroupBox::indicator:unchecked:disabled{ + image:url(:/darkstyle/icon_checkbox_unchecked_disabled.png); +} +QCheckBox::indicator:indeterminate,QTreeView::indicator:indeterminate,QTableView::indicator:indeterminate,QListWidget::indicator:indeterminate,QTableWidget::indicator:indeterminate,QGroupBox::indicator:indeterminate{ + image:url(:/darkstyle/icon_checkbox_indeterminate.png); +} +QCheckBox::indicator:indeterminate:pressed,QTreeView::indicator:indeterminate:pressed,QTableView::indicator:indeterminate:pressed,QListWidget::indicator:indeterminate:pressed,QTableWidget::indicator:indeterminate:pressed,QGroupBox::indicator:indeterminate:pressed{ + image:url(:/darkstyle/icon_checkbox_indeterminate_pressed.png); +} +QCheckBox::indicator:indeterminate:disabled,QTreeView::indicator:indeterminate:disabled,QTableView::indicator:indeterminate:disabled,QListWidget::indicator:indeterminate:disabled,QTableWidget::indicator:indeterminate:disabled,QGroupBox::indicator:indeterminate:disabled{ + image:url(:/darkstyle/icon_checkbox_indeterminate_disabled.png); +} +QRadioButton::indicator{ + width:18px; + height:18px; +} +QRadioButton::indicator:checked{ + image:url(:/darkstyle/icon_radiobutton_checked.png); +} +QRadioButton::indicator:checked:pressed{ + image:url(:/darkstyle/icon_radiobutton_checked_pressed.png); +} +QRadioButton::indicator:checked:disabled{ + image:url(:/darkstyle/icon_radiobutton_checked_disabled.png); +} +QRadioButton::indicator:unchecked{ + image:url(:/darkstyle/icon_radiobutton_unchecked.png); +} +QRadioButton::indicator:unchecked:pressed{ + image:url(:/darkstyle/icon_radiobutton_unchecked_pressed.png); +} +QRadioButton::indicator:unchecked:disabled{ + image:url(:/darkstyle/icon_radiobutton_unchecked_disabled.png); +} +QTreeView, QTableView{ + alternate-background-color:palette(window); + background:palette(base); +} +QTreeView QHeaderView::section, QTableView QHeaderView::section{ + background-color:qlineargradient(x1:0,y1:1,x2:0,y2:0,stop:0 rgba(25,25,25,127),stop:1 rgba(53,53,53,75)); + border-style:none; + border-bottom:1px solid palette(dark); + padding-left:5px; + padding-right:5px; +} +QTreeView::item:selected:disabled, QTableView::item:selected:disabled{ + background:rgb(80,80,80); +} +QTreeView::branch{ + background-color:palette(base); +} +QTreeView::branch:has-siblings:!adjoins-item{ + border-image:url(:/darkstyle/icon_vline.png) 0; +} +QTreeView::branch:has-siblings:adjoins-item{ + border-image:url(:/darkstyle/icon_branch_more.png) 0; +} +QTreeView::branch:!has-children:!has-siblings:adjoins-item{ + border-image:url(:/darkstyle/icon_branch_end.png) 0; +} +QTreeView::branch:has-children:!has-siblings:closed, +QTreeView::branch:closed:has-children:has-siblings{ + border-image:none; + image:url(:/darkstyle/icon_branch_closed.png); +} +QTreeView::branch:open:has-children:!has-siblings, +QTreeView::branch:open:has-children:has-siblings{ + border-image:none; + image:url(:/darkstyle/icon_branch_open.png); +} +QScrollBar:vertical{ + background:palette(base); + border-top-right-radius:2px; + border-bottom-right-radius:2px; + width:16px; + margin:0px; +} +QScrollBar::handle:vertical{ + background-color:palette(alternate-base); + border-radius:2px; + min-height:20px; + margin:2px 4px 2px 4px; +} +QScrollBar::handle:vertical:hover{ + background-color:palette(highlight); +} +QScrollBar::add-line:vertical{ + background:none; + height:0px; + subcontrol-position:right; + subcontrol-origin:margin; +} +QScrollBar::sub-line:vertical{ + background:none; + height:0px; + subcontrol-position:left; + subcontrol-origin:margin; +} +QScrollBar:horizontal{ + background:palette(base); + height:16px; + margin:0px; +} +QScrollBar::handle:horizontal{ + background-color:palette(alternate-base); + border-radius:2px; + min-width:20px; + margin:4px 2px 4px 2px; +} +QScrollBar::handle:horizontal:hover{ + background-color:palette(highlight); +} +QScrollBar::add-line:horizontal{ + background:none; + width:0px; + subcontrol-position:bottom; + subcontrol-origin:margin; +} +QScrollBar::sub-line:horizontal{ + background:none; + width:0px; + subcontrol-position:top; + subcontrol-origin:margin; +} +QSlider::handle:horizontal{ + border-radius:4px; + border:1px solid rgba(25,25,25,255); + background-color:palette(alternate-base); + min-height:20px; + margin:0 -4px; +} +QSlider::handle:horizontal:hover{ + background:palette(highlight); +} +QSlider::add-page:horizontal{ + background:palette(base); +} +QSlider::sub-page:horizontal{ + background:palette(highlight); +} +QSlider::sub-page:horizontal:disabled{ + background:rgb(80,80,80); +} +QPushButton::checked{ + background-color: rgb(42, 130, 218); +} +QPushButton::checked:disabled{ + background-color: rgb(40, 40, 40); + color: rgb(170, 170, 170); +} diff --git a/resources/themes/darkstyle/icon_branch_closed.png b/resources/themes/darkstyle/icon_branch_closed.png new file mode 100644 index 0000000..fa785cc Binary files /dev/null and b/resources/themes/darkstyle/icon_branch_closed.png differ diff --git a/resources/themes/darkstyle/icon_branch_end.png b/resources/themes/darkstyle/icon_branch_end.png new file mode 100644 index 0000000..d90a04c Binary files /dev/null and b/resources/themes/darkstyle/icon_branch_end.png differ diff --git a/resources/themes/darkstyle/icon_branch_more.png b/resources/themes/darkstyle/icon_branch_more.png new file mode 100644 index 0000000..bdbe4ed Binary files /dev/null and b/resources/themes/darkstyle/icon_branch_more.png differ diff --git a/resources/themes/darkstyle/icon_branch_open.png b/resources/themes/darkstyle/icon_branch_open.png new file mode 100644 index 0000000..9dd05d6 Binary files /dev/null and b/resources/themes/darkstyle/icon_branch_open.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_checked.png b/resources/themes/darkstyle/icon_checkbox_checked.png new file mode 100644 index 0000000..fa22907 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_checked.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_checked_disabled.png b/resources/themes/darkstyle/icon_checkbox_checked_disabled.png new file mode 100644 index 0000000..441d0d9 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_checked_disabled.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_checked_pressed.png b/resources/themes/darkstyle/icon_checkbox_checked_pressed.png new file mode 100644 index 0000000..7b508c8 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_checked_pressed.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_indeterminate.png b/resources/themes/darkstyle/icon_checkbox_indeterminate.png new file mode 100644 index 0000000..87ebf23 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_indeterminate.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_indeterminate_disabled.png b/resources/themes/darkstyle/icon_checkbox_indeterminate_disabled.png new file mode 100644 index 0000000..ee7d112 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_indeterminate_disabled.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_indeterminate_pressed.png b/resources/themes/darkstyle/icon_checkbox_indeterminate_pressed.png new file mode 100644 index 0000000..562c482 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_indeterminate_pressed.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_unchecked.png b/resources/themes/darkstyle/icon_checkbox_unchecked.png new file mode 100644 index 0000000..c3c14dd Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_unchecked.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_unchecked_disabled.png b/resources/themes/darkstyle/icon_checkbox_unchecked_disabled.png new file mode 100644 index 0000000..3ac26d8 Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_unchecked_disabled.png differ diff --git a/resources/themes/darkstyle/icon_checkbox_unchecked_pressed.png b/resources/themes/darkstyle/icon_checkbox_unchecked_pressed.png new file mode 100644 index 0000000..c24130c Binary files /dev/null and b/resources/themes/darkstyle/icon_checkbox_unchecked_pressed.png differ diff --git a/resources/themes/darkstyle/icon_close.png b/resources/themes/darkstyle/icon_close.png new file mode 100644 index 0000000..ece7c28 Binary files /dev/null and b/resources/themes/darkstyle/icon_close.png differ diff --git a/resources/themes/darkstyle/icon_radiobutton_checked.png b/resources/themes/darkstyle/icon_radiobutton_checked.png new file mode 100644 index 0000000..f747f49 Binary files /dev/null and b/resources/themes/darkstyle/icon_radiobutton_checked.png differ diff --git a/resources/themes/darkstyle/icon_radiobutton_checked_disabled.png b/resources/themes/darkstyle/icon_radiobutton_checked_disabled.png new file mode 100644 index 0000000..fa554cb Binary files /dev/null and b/resources/themes/darkstyle/icon_radiobutton_checked_disabled.png differ diff --git a/resources/themes/darkstyle/icon_radiobutton_checked_pressed.png b/resources/themes/darkstyle/icon_radiobutton_checked_pressed.png new file mode 100644 index 0000000..7b4bb11 Binary files /dev/null and b/resources/themes/darkstyle/icon_radiobutton_checked_pressed.png differ diff --git a/resources/themes/darkstyle/icon_radiobutton_unchecked.png b/resources/themes/darkstyle/icon_radiobutton_unchecked.png new file mode 100644 index 0000000..e74f040 Binary files /dev/null and b/resources/themes/darkstyle/icon_radiobutton_unchecked.png differ diff --git a/resources/themes/darkstyle/icon_radiobutton_unchecked_disabled.png b/resources/themes/darkstyle/icon_radiobutton_unchecked_disabled.png new file mode 100644 index 0000000..87d1846 Binary files /dev/null and b/resources/themes/darkstyle/icon_radiobutton_unchecked_disabled.png differ diff --git a/resources/themes/darkstyle/icon_radiobutton_unchecked_pressed.png b/resources/themes/darkstyle/icon_radiobutton_unchecked_pressed.png new file mode 100644 index 0000000..8f4d548 Binary files /dev/null and b/resources/themes/darkstyle/icon_radiobutton_unchecked_pressed.png differ diff --git a/resources/themes/darkstyle/icon_restore.png b/resources/themes/darkstyle/icon_restore.png new file mode 100644 index 0000000..be29650 Binary files /dev/null and b/resources/themes/darkstyle/icon_restore.png differ diff --git a/resources/themes/darkstyle/icon_undock.png b/resources/themes/darkstyle/icon_undock.png new file mode 100644 index 0000000..25e317e Binary files /dev/null and b/resources/themes/darkstyle/icon_undock.png differ diff --git a/resources/themes/darkstyle/icon_vline.png b/resources/themes/darkstyle/icon_vline.png new file mode 100644 index 0000000..14228c8 Binary files /dev/null and b/resources/themes/darkstyle/icon_vline.png differ diff --git a/src/abjad_class.cpp b/src/abjad_class.cpp new file mode 100644 index 0000000..49892ca --- /dev/null +++ b/src/abjad_class.cpp @@ -0,0 +1,284 @@ +/* + C++ class for the Abjad Calculator: + by Aboutaleb Roshan + 18 Tir, 1393 (11 Ramadan, 1435) (9 July, 2014) + ab.roshan39@gmail.com +*/ + +#include "abjad_class.h" + +const wstring abjad::abjadCharacters = L"آاأإٱءبپجچدهةۀوؤزژحطیيئىﻯﻱکكگلمنسعفصقرشتثخذضظغ"; +const wstring abjad::diacritics = L"\u064E\u0650\u064F\u0652\u064B\u064D\u064C\u0651\u0654\u0655\u0670\u0656\u0653\u0640"; +const wchar_t abjad::zwnj = 0x200C; +const wchar_t abjad::zwj = 0x200D; + +// DIACRITICS: +// A << E << O << SOKUN << AN << EN << ON << TASHDID << HAMZE << HAMZE_ZIR << ALEF_KHANJARI << ALEF_KHANJARI_ZIR << MADD << KESHIDE + +void abjad::init(const wstring &str) +{ + abStr = str; + value = 0; + harf = 0; + noghte = 0; + calculated = false; + pCHN = false; +} + +int abjad::abChar(const wchar_t &ch, abjadType abt) +{ + int a = 0; + + switch(ch) + { + case L'آ': + case L'ا': + case L'أ': + case L'إ': + case L'ٱ': + case L'ء': a = 1; break; + case L'ب': + case L'پ': a = 2; break; + case L'ج': + case L'چ': a = 3; break; + case L'د': a = 4; break; + case L'ه': + case L'ة': + case L'ۀ': a = 5; break; + case L'و': + case L'ؤ': a = 6; break; + case L'ز': + case L'ژ': a = 7; break; + case L'ح': a = 8; break; + case L'ط': a = 9; break; + case L'ی': + case L'ي': + case L'ئ': + case L'ى': + case L'ﻯ': + case L'ﻱ': a = 10; break; + case L'ک': + case L'ك': + case L'گ': a = 20; break; + case L'ل': a = 30; break; + case L'م': a = 40; break; + case L'ن': a = 50; break; + case L'س': a = 60; break; + case L'ع': a = 70; break; + case L'ف': a = 80; break; + case L'ص': a = 90; break; + case L'ق': a = 100; break; + case L'ر': a = 200; break; + case L'ش': a = 300; break; + case L'ت': a = 400; break; + case L'ث': a = 500; break; + case L'خ': a = 600; break; + case L'ذ': a = 700; break; + case L'ض': a = 800; break; + case L'ظ': a = 900; break; + case L'غ': a = 1000; break; + default: return 0; + } + + switch(abt) + { + case KABIR: + return a; + case SAGIR: + if(ch == L'س' || ch == L'ش' || ch == L'خ' || ch == L'ظ') + return 0; + return a % 12; + case VASIT: + if(a <= 10) + return a; + else if(a > 10 && a <= 100) + return (a / 10) + 9; + else if(a > 100 && a <= 1000) + return (a / 100) + 18; + break; + case MAKUS: + if(a >= 1 && a <= 10) + return (11 - a) * 100; + else if(a >= 20 && a <= 100) + return 110 - a; + else if(a >= 200 && a <= 1000) + return 11 - (a / 100); + break; + case SAGIR2: + if(ch == L'ط' || ch == L'ص' || ch == L'ظ') + return 0; + return a % 9; + } + + return 0; +} + +int abjad::abCharMofassal(const wchar_t &ch, abjadType abt) +{ + wstring charName(L""); + int c = 0; + + if(abt == SAGIR && (ch == L'س' || ch == L'ش' || ch == L'خ' || ch == L'ظ')) + return 0; + if(abt == SAGIR2 && (ch == L'ط' || ch == L'ص' || ch == L'ظ')) + return 0; + + switch(ch) + { + case L'آ': + case L'ا': + case L'أ': + case L'إ': + case L'ٱ': + case L'ء': charName = L"ألف"; break; + case L'ب': + case L'پ': charName = L"باء"; break; + case L'ج': + case L'چ': charName = L"جيم"; break; + case L'د': charName = L"دال"; break; + case L'ه': + case L'ة': + case L'ۀ': charName = L"هاء"; break; + case L'و': + case L'ؤ': charName = L"واو"; break; + case L'ز': + case L'ژ': charName = L"زاي"; break; + case L'ح': charName = L"حاء"; break; + case L'ط': charName = L"طاء"; break; + case L'ی': + case L'ي': + case L'ئ': + case L'ى': + case L'ﻯ': + case L'ﻱ': charName = L"ياء"; break; + case L'ک': + case L'ك': + case L'گ': charName = L"كاف"; break; + case L'ل': charName = L"لام"; break; + case L'م': charName = L"ميم"; break; + case L'ن': charName = L"نون"; break; + case L'س': charName = L"سين"; break; + case L'ع': charName = L"عين"; break; + case L'ف': charName = L"فاء"; break; + case L'ص': charName = L"صاد"; break; + case L'ق': charName = L"قاف"; break; + case L'ر': charName = L"راء"; break; + case L'ش': charName = L"شين"; break; + case L'ت': charName = L"تاء"; break; + case L'ث': charName = L"ثاء"; break; + case L'خ': charName = L"خاء"; break; + case L'ذ': charName = L"ذال"; break; + case L'ض': charName = L"ضاد"; break; + case L'ظ': charName = L"ظاء"; break; + case L'غ': charName = L"غين"; break; + default: return 0; + } + + for(unsigned int i = 0; i < charName.length(); i++) + c += abChar(charName[i], abt); + + return c; +} + +int abjad::abCharNoghte(const wchar_t &ch) +{ + switch(ch) + { + case L'ب': return 1; + case L'پ': return 3; + case L'ج': return 1; + case L'چ': return 3; + case L'ة': return 2; + case L'ز': return 1; + case L'ژ': return 3; + case L'ی': + case L'ي': + case L'ئ': + case L'ى': + case L'ﻯ': + case L'ﻱ': return 2; + case L'ن': return 1; + case L'ف': return 1; + case L'ق': return 2; + case L'ش': return 3; + case L'ت': return 2; + case L'ث': return 3; + case L'خ': return 1; + case L'ذ': return 1; + case L'ض': return 1; + case L'ظ': return 1; + case L'غ': return 1; + } + + return 0; +} + +int abjad::abHesab(const wstring &str, abjadType abt, typeMojmMofa tmm) +{ + int c = 0; + if(tmm == MOJMAL) + for(unsigned int i = 0; i < str.length(); i++) + c += abChar(str[i], abt); + else + for(unsigned int i = 0; i < str.length(); i++) + c += abCharMofassal(str[i], abt); + return c; +} + +int abjad::abHesab(abjadType abt, typeMojmMofa tmm) +{ + value = 0; + calculated = false; + calculate(abStr, abt, tmm); + return value; +} + +int abjad::abHarf() +{ + calculate(abStr, KABIR, MOJMAL); + return harf; +} + +int abjad::abNoghte() +{ + calculate(abStr, KABIR, MOJMAL); + return noghte; +} + +void abjad::calculate(const wstring &str, abjadType abt, typeMojmMofa tmm) +{ + if(!calculated) + { + int tc = 0, strLen = str.length(); + if(tmm == MOJMAL) + { + for(int i = 0; i < strLen; i++) + { + value += abChar(str[i], abt); + if(!pCHN) + { + tc = abChar(str[i], KABIR); + if(tc != 0) + harf += 1; + noghte += abCharNoghte(str[i]); + } + } + } + else + { + for(int i = 0; i < strLen; i++) + { + value += abCharMofassal(str[i], abt); + if(!pCHN) + { + tc = abChar(str[i], KABIR); + if(tc != 0) + harf += 1; + noghte += abCharNoghte(str[i]); + } + } + } + calculated = true; + pCHN = true; + } +} diff --git a/src/abjad_class.h b/src/abjad_class.h new file mode 100644 index 0000000..65fdf20 --- /dev/null +++ b/src/abjad_class.h @@ -0,0 +1,56 @@ +/* + C++ class for the Abjad Calculator: + by Aboutaleb Roshan + 18 Tir, 1393 (11 Ramadan, 1435) (9 July, 2014) + ab.roshan39@gmail.com +*/ + +#ifndef ABJADCLASS_H +#define ABJADCLASS_H + +#include +#include + +using std::wstring; + +class abjad +{ +public: + enum abjadType {KABIR, SAGIR, VASIT, MAKUS, SAGIR2}; + enum typeMojmMofa {MOJMAL, MOFASSAL}; + static const wstring abjadCharacters; + static const wstring diacritics; + static const wchar_t zwnj; + static const wchar_t zwj; + +public: + abjad() {init();} + abjad(const wstring &str) {init(str);} + ~abjad() {;} + + static int abChar(const wchar_t &ch, abjadType = KABIR); + static int abCharMofassal(const wchar_t &ch, abjadType = KABIR); + static int abCharNoghte(const wchar_t &ch); + static int abHesab(const wstring &str, abjadType = KABIR, typeMojmMofa = MOJMAL); + int abHesab(abjadType = KABIR, typeMojmMofa = MOJMAL); + int abHarf(); + int abNoghte(); + + wstring assign(const wstring &str) {init(str); return abStr;} + wstring text() {return abStr;} + void clear() {init();} + bool empty() const {return abStr.empty();} + size_t size() const {return abStr.size();} + size_t length() const {return abStr.length();} + void operator=(const wstring &str) {init(str);} + +private: + void init(const wstring &str = L""); + void calculate(const wstring &str, abjadType, typeMojmMofa); + +private: + wstring abStr; + int value, harf, noghte; + bool calculated, pCHN; +}; +#endif // ABJADCLASS_H diff --git a/src/abjadform.cpp b/src/abjadform.cpp new file mode 100644 index 0000000..83738f1 --- /dev/null +++ b/src/abjadform.cpp @@ -0,0 +1,330 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "abjadform.h" +#include "ui_abjadform.h" +#include "abjad_class.h" +#include "event_functions.h" + +AbjadForm::AbjadForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AbjadForm) +{ + ui->setupUi(this); +} + +AbjadForm::AbjadForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AbjadForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + appSettings->isOpenAbjadForm = true; + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("محاسبه‌گر ابجد"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + ui->comboBox->setCurrentIndex(ui->comboBox->count() - 1); + + connect(new ZWNJPress(ui->textEdit), &ZWNJPress::zwnjPressed, this, &AbjadForm::textEditZWNJPressed); +} + +AbjadForm::~AbjadForm() +{ + delete ui; +} + +void AbjadForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) + on_btnCalculate_clicked(); + if(e->key() == Qt::Key_Escape) + on_btnExit_clicked(); +} + +void AbjadForm::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); // (void)event; + appSettings->isOpenAbjadForm = false; +} + +void AbjadForm::on_btnCalculate_clicked() +{ + wstring text(ui->textEdit->toPlainText().toStdWString()); + abjad ab(text); + + if(option == 1) ui->lineEdit->setText(QString::number(ab.abHesab(ab.KABIR, ab.MOJMAL))); + else if(option == 2) ui->lineEdit->setText(QString::number(ab.abHesab(ab.KABIR, ab.MOFASSAL))); + else if(option == 3) ui->lineEdit->setText(QString::number(ab.abHesab(ab.SAGIR, ab.MOJMAL))); + else if(option == 4) ui->lineEdit->setText(QString::number(ab.abHesab(ab.SAGIR, ab.MOFASSAL))); + else if(option == 5) ui->lineEdit->setText(QString::number(ab.abHesab(ab.VASIT, ab.MOJMAL))); + else if(option == 6) ui->lineEdit->setText(QString::number(ab.abHesab(ab.VASIT, ab.MOFASSAL))); + else if(option == 7) ui->lineEdit->setText(QString::number(ab.abHesab(ab.MAKUS, ab.MOJMAL))); + else if(option == 8) ui->lineEdit->setText(QString::number(ab.abHesab(ab.MAKUS, ab.MOFASSAL))); + else if(option == 9) ui->lineEdit->setText(QString::number(ab.abHesab(ab.SAGIR2, ab.MOJMAL))); + else if(option == 10) ui->lineEdit->setText(QString::number(ab.abHesab(ab.SAGIR2, ab.MOFASSAL))); + + if(ui->checkBox_4->isChecked()) + { + ui->label_12->setText(QString::number(ab.abHarf())); + ui->label_14->setText(QString::number(ab.abNoghte())); + } + + if(ui->checkBox_1->isChecked()) + { + ui->label_1->setText(QString::number(abjad::abHesab(text))); + ui->label_2->setText(QString::number(abjad::abHesab(text, abjad::KABIR, abjad::MOFASSAL))); + ui->label_3->setText(QString::number(abjad::abHesab(text, abjad::SAGIR))); + ui->label_4->setText(QString::number(abjad::abHesab(text, abjad::SAGIR, abjad::MOFASSAL))); + ui->label_5->setText(QString::number(abjad::abHesab(text, abjad::VASIT))); + ui->label_6->setText(QString::number(abjad::abHesab(text, abjad::VASIT, abjad::MOFASSAL))); + if(ui->checkBox_5->isChecked()) + { + ui->label_7->setText(QString::number(abjad::abHesab(text, abjad::MAKUS))); + ui->label_8->setText(QString::number(abjad::abHesab(text, abjad::MAKUS, abjad::MOFASSAL))); + } + ui->label_9->setText(QString::number(abjad::abHesab(text, abjad::SAGIR2))); + ui->label_10->setText(QString::number(abjad::abHesab(text, abjad::SAGIR2, abjad::MOFASSAL))); + } + + if(ui->checkBox_3->isChecked()) + { + QString abjadText(ui->textEdit->toPlainText()); + QString diacritics(QString::fromStdWString(abjad::diacritics)); + if(ui->checkBox_9->isChecked()) + { + QRegularExpression regex("[" + diacritics + "]"); + abjadText.remove(regex); + diacritics.clear(); + } + if(ui->checkBox_8->isChecked()) + { + QString abChars(QString::fromStdWString(abjad::abjadCharacters)); + QRegularExpression regex("[^" + abChars + diacritics + QChar(abjad::zwnj) + QChar(abjad::zwj) + "\\s]"); + abjadText.remove(regex); + } + QStringList list(abjadText.split(QRegularExpression("[\\s]"), SKIP_EMPTY_PARTS)); + QString space(" "); + QString strResult; + + ui->textBrowser->clear(); + space = space.repeated(ui->spinBox->value()); + + for(int i = 0; i < list.size(); i++) + { + wstring word(list[i].toStdWString()); + QString value; + + if (option == 1) value = QString::number(abjad::abHesab(word, abjad::KABIR, abjad::MOJMAL)); + else if(option == 2) value = QString::number(abjad::abHesab(word, abjad::KABIR, abjad::MOFASSAL)); + else if(option == 3) value = QString::number(abjad::abHesab(word, abjad::SAGIR, abjad::MOJMAL)); + else if(option == 4) value = QString::number(abjad::abHesab(word, abjad::SAGIR, abjad::MOFASSAL)); + else if(option == 5) value = QString::number(abjad::abHesab(word, abjad::VASIT, abjad::MOJMAL)); + else if(option == 6) value = QString::number(abjad::abHesab(word, abjad::VASIT, abjad::MOFASSAL)); + else if(option == 7) value = QString::number(abjad::abHesab(word, abjad::MAKUS, abjad::MOJMAL)); + else if(option == 8) value = QString::number(abjad::abHesab(word, abjad::MAKUS, abjad::MOFASSAL)); + else if(option == 9) value = QString::number(abjad::abHesab(word, abjad::SAGIR2, abjad::MOJMAL)); + else if(option == 10) value = QString::number(abjad::abHesab(word, abjad::SAGIR2, abjad::MOFASSAL)); + + strResult += list[i] + "(" + value + ")" + space; + } + ui->textBrowser->setText(strResult.trimmed()); + } + + if(ui->checkBox_7->isChecked()) + { + QString abjadText(ui->textEdit->toPlainText()); + QString abChars(QString::fromStdWString(abjad::abjadCharacters)); + QRegularExpression regex("[^" + abChars + "]"); + abjadText.remove(regex); + + QStringList list(abjadText.split("", SKIP_EMPTY_PARTS)); + QString space(" "); + QString strResult; + + ui->textBrowser->clear(); + space = space.repeated(ui->spinBox->value()); + + for(int i = 0; i < list.size(); i++) + { + wchar_t ch = list[i][0].unicode(); + QString value; + + if (option == 1) value = QString::number(abjad::abChar(ch, abjad::KABIR)); + else if(option == 2) value = QString::number(abjad::abCharMofassal(ch, abjad::KABIR)); + else if(option == 3) value = QString::number(abjad::abChar(ch, abjad::SAGIR)); + else if(option == 4) value = QString::number(abjad::abCharMofassal(ch, abjad::SAGIR)); + else if(option == 5) value = QString::number(abjad::abChar(ch, abjad::VASIT)); + else if(option == 6) value = QString::number(abjad::abCharMofassal(ch, abjad::VASIT)); + else if(option == 7) value = QString::number(abjad::abChar(ch, abjad::MAKUS)); + else if(option == 8) value = QString::number(abjad::abCharMofassal(ch, abjad::MAKUS)); + else if(option == 9) value = QString::number(abjad::abChar(ch, abjad::SAGIR2)); + else if(option == 10) value = QString::number(abjad::abCharMofassal(ch, abjad::SAGIR2)); + + strResult += list[i] + "(" + value + ")" + space; + } + ui->textBrowser->setText(strResult.trimmed()); + } +} + +void AbjadForm::on_btnExit_clicked() +{ + close(); +} + +void AbjadForm::on_radioButton_1_clicked() {option = 1; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_2_clicked() {option = 2; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_3_clicked() {option = 3; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_4_clicked() {option = 4; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_5_clicked() {option = 5; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_6_clicked() {option = 6; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_7_clicked() {option = 7; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_8_clicked() {option = 8; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_9_clicked() {option = 9; on_btnCalculate_clicked();} +void AbjadForm::on_radioButton_10_clicked() {option = 10; on_btnCalculate_clicked();} +void AbjadForm::on_spinBox_valueChanged(int arg1) {Q_UNUSED(arg1); on_btnCalculate_clicked();} + +void AbjadForm::on_textEdit_textChanged() +{ + if(ui->checkBox_2->isChecked()) on_btnCalculate_clicked(); + + if(ui->textEdit->toPlainText().trimmed().isEmpty()) + { + on_checkBox_1_clicked(false); + ui->label_12->clear(); + ui->label_14->clear(); + ui->lineEdit->clear(); + } +} + +void AbjadForm::on_checkBox_1_clicked(bool checked) +{ + if(checked) + { + on_btnCalculate_clicked(); + } + else + { + ui->label_1->clear(); + ui->label_2->clear(); + ui->label_3->clear(); + ui->label_4->clear(); + ui->label_5->clear(); + ui->label_6->clear(); + ui->label_7->clear(); + ui->label_8->clear(); + ui->label_9->clear(); + ui->label_10->clear(); + } +} + +void AbjadForm::on_checkBox_2_clicked(bool checked) +{ + if(checked) on_btnCalculate_clicked(); +} + +void AbjadForm::on_checkBox_3_clicked(bool checked) +{ + if(checked) + { + ui->textBrowser->setEnabled(true); + ui->checkBox_7->setChecked(false); + if(ui->checkBox_2->isChecked() && !ui->textEdit->toPlainText().trimmed().isEmpty()) + on_btnCalculate_clicked(); + } + else if(!checked && !ui->checkBox_7->isChecked()) + { + ui->textBrowser->clear(); + ui->textBrowser->setEnabled(false); + } +} + +void AbjadForm::on_checkBox_3_toggled(bool checked) +{ + ui->checkBox_8->setEnabled(checked); + ui->checkBox_9->setEnabled(checked); +} + +void AbjadForm::on_checkBox_4_clicked(bool checked) +{ + if(!checked) + { + ui->label_12->clear(); + ui->label_14->clear(); + } +} + +void AbjadForm::on_checkBox_5_clicked(bool checked) +{ + if(checked) + { + ui->radioButton_7->setEnabled(true); + ui->radioButton_8->setEnabled(true); + } + else + { + ui->radioButton_7->setEnabled(false); + ui->radioButton_8->setEnabled(false); + ui->label_7->clear(); + ui->label_8->clear(); + } +} + +void AbjadForm::on_checkBox_6_clicked(bool checked) +{ + ui->comboBox->setEnabled(checked); +} + +void AbjadForm::on_checkBox_7_clicked(bool checked) +{ + if(checked) + { + ui->textBrowser->setEnabled(true); + ui->checkBox_3->setChecked(false); + if(ui->checkBox_2->isChecked() && !ui->textEdit->toPlainText().trimmed().isEmpty()) + on_btnCalculate_clicked(); + } + else if(!checked && !ui->checkBox_3->isChecked()) + { + ui->textBrowser->clear(); + ui->textBrowser->setEnabled(false); + } +} + +void AbjadForm::on_checkBox_8_clicked() +{ + if(ui->checkBox_2->isChecked() && !ui->textEdit->toPlainText().trimmed().isEmpty()) + on_btnCalculate_clicked(); +} + +void AbjadForm::on_checkBox_9_clicked() +{ + if(ui->checkBox_2->isChecked() && !ui->textEdit->toPlainText().trimmed().isEmpty()) + on_btnCalculate_clicked(); +} + +void AbjadForm::slotSelectedText(const QString &text) +{ + ui->textEdit->setText(text); +} + +void AbjadForm::textEditZWNJPressed(QObject *object, Qt::KeyboardModifier key) +{ + Q_UNUSED(object); // (void)object; + + if(ui->checkBox_6->isChecked()) + { + if((ui->comboBox->currentIndex() == ui->comboBox->count() - 1) || + (ui->comboBox->currentIndex() == 0 && key == Qt::ShiftModifier) || + (ui->comboBox->currentIndex() == 1 && key == Qt::ControlModifier)) + ui->textEdit->insertPlainText(QChar(abjad::zwnj)); + } +} diff --git a/src/abjadform.h b/src/abjadform.h new file mode 100644 index 0000000..0adf6d9 --- /dev/null +++ b/src/abjadform.h @@ -0,0 +1,71 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef ABJADFORM_H +#define ABJADFORM_H + +#include +#include "common_functions.h" + +using std::wstring; + +QT_BEGIN_NAMESPACE +namespace Ui { class AbjadForm; } +QT_END_NAMESPACE + +class AbjadForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit AbjadForm(QWidget *parent = nullptr); + AbjadForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~AbjadForm(); + +public slots: + void slotSelectedText(const QString &text); + void textEditZWNJPressed(QObject *object, Qt::KeyboardModifier key); + +private slots: + void on_btnCalculate_clicked(); + void on_btnExit_clicked(); + void on_textEdit_textChanged(); + void on_radioButton_1_clicked(); + void on_radioButton_2_clicked(); + void on_radioButton_3_clicked(); + void on_radioButton_4_clicked(); + void on_radioButton_5_clicked(); + void on_radioButton_6_clicked(); + void on_radioButton_7_clicked(); + void on_radioButton_8_clicked(); + void on_radioButton_9_clicked(); + void on_radioButton_10_clicked(); + void on_spinBox_valueChanged(int arg1); + void on_checkBox_1_clicked(bool checked); + void on_checkBox_2_clicked(bool checked); + void on_checkBox_3_clicked(bool checked); + void on_checkBox_3_toggled(bool checked); + void on_checkBox_4_clicked(bool checked); + void on_checkBox_5_clicked(bool checked); + void on_checkBox_6_clicked(bool checked); + void on_checkBox_7_clicked(bool checked); + void on_checkBox_8_clicked(); + void on_checkBox_9_clicked(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void closeEvent(QCloseEvent *event) override; + +private: + Ui::AbjadForm *ui; + AppSettings *appSettings; + int option = 1; +}; +#endif // ABJADFORM_H diff --git a/src/abjadform.ui b/src/abjadform.ui new file mode 100644 index 0000000..a7fa240 --- /dev/null +++ b/src/abjadform.ui @@ -0,0 +1,1210 @@ + + + AbjadForm + + + + 0 + 0 + 530 + 551 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + متن: + + + + + + + + Sahel FD + 11 + + + + classFD + + + Qt::ScrollBarAlwaysOff + + + true + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Sahel FD'; font-size:11pt; font-weight:400; font-style:normal;"> +<p align="right" dir='rtl' style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + + + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + حساب ابجد: + + + + + + + + Sahel FD + 11 + 50 + false + + + + classFD + + + Qt::AlignCenter + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + Sahel FD + 12 + + + + classFD + + + محاسبه + + + true + + + true + + + + + + + + Sahel FD + 12 + + + + classFD + + + خروج + + + true + + + false + + + + + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + تعداد حروف: + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 60 + 20 + + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + تعداد نقاط: + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + Qt::Horizontal + + + + 60 + 20 + + + + + + + + + + + Sahel FD + 10 + + + + classFDs + + + فاصله هر کلمه: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFDs + + + 100 + + + 1 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 10 + + + + + + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + کبیر مجمل + + + true + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + صغیر مجمل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + وسیط مجمل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + معکوس مجمل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + صغیر (۲) مجمل + + + + + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + کبیر مفصل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + صغیر مفصل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + وسیط مفصل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + معکوس مفصل + + + + + + + + 0 + 0 + + + + + Sahel FD + 11 + + + + classFD + + + Qt::RightToLeft + + + صغیر (۲) مفصل + + + + + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Sahel FD + 11 + + + + classFD + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 10 + + + + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + نمایش کلمه به کلمه + + + true + + + + + + + + Sahel FD + 10 + + + + classFDs + + + نمایش حرف به حرف + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + محاسبه سریع + + + true + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + محاسبه همه + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + نمایش حروف و نقاط + + + true + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + معکوس ابجد کبیر + + + true + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + نیم‌فاصله: + + + true + + + + + + + + Sahel FD + 10 + + + + classFDs + + + Qt::RightToLeft + + + 0 + + + + شیفت+فاصله + + + + + کنترل+فاصله + + + + + هر دو (کنترل/شیفت+فاصله) + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + Sahel FD + 10 + + + + classFDs + + + حذف کاراکترهای اضافه + + + + + + + + Sahel FD + 10 + + + + classFDs + + + حذف حرکت‌ها + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Sahel FD + 11 + + + + classFD + + + false + + + + + + + + + + textEdit + lineEdit + btnCalculate + btnExit + spinBox + radioButton_1 + radioButton_2 + radioButton_3 + radioButton_4 + radioButton_5 + radioButton_6 + radioButton_7 + radioButton_8 + radioButton_9 + radioButton_10 + checkBox_3 + checkBox_7 + checkBox_2 + checkBox_1 + checkBox_4 + checkBox_5 + checkBox_6 + comboBox + checkBox_8 + checkBox_9 + textBrowser + + + + diff --git a/src/abjadformmini.cpp b/src/abjadformmini.cpp new file mode 100644 index 0000000..0bb3d4c --- /dev/null +++ b/src/abjadformmini.cpp @@ -0,0 +1,100 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "abjadformmini.h" +#include "ui_abjadformmini.h" +#include "abjad_class.h" + +AbjadFormMini::AbjadFormMini(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AbjadFormMini) +{ + ui->setupUi(this); +} + +AbjadFormMini::AbjadFormMini(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AbjadFormMini) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + appSettings->isOpenAbjadFormMini = true; + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("حساب ابجد"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + ui->textBrowser->setEnabled(false); + + connect(parent, SIGNAL(sigSelectedText(const QString &)), this, SLOT(slotSelectedText(const QString &))); +} + +AbjadFormMini::~AbjadFormMini() +{ + delete ui; +} + +void AbjadFormMini::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Return) + close(); +} + +void AbjadFormMini::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); // (void)event; + appSettings->isOpenAbjadFormMini = false; +} + +void AbjadFormMini::slotSelectedText(const QString &text) +{ + abjadText = text; + QString abChars(QString::fromStdWString(abjad::abjadCharacters)); + QRegularExpression regex("[^" + abChars + "]"); + abjadText.remove(regex); + int n = abjad::abHesab(abjadText.toStdWString()); + + ui->lineEdit->setText(QString::number(n)); + if(ui->checkBox->isChecked()) + { + if(n) + { + QStringList list(abjadText.split("", SKIP_EMPTY_PARTS)); + QString strResult; + for(int i = 0; i < list.size(); i++) + { + wchar_t ch = list[i][0].unicode(); + QString value(QString::number(abjad::abChar(ch))); + strResult += list[i] + "(" + value + ") + "; + } + strResult = strResult.left(strResult.size() - 3) + "
=
" + QString::number(n); + strResult = QString("

%1

").arg(strResult); + ui->textBrowser->setHtml(strResult); + } + else + { + ui->textBrowser->clear(); + } + } +} + +void AbjadFormMini::on_checkBox_toggled(bool checked) +{ + if(checked) + { + ui->textBrowser->setEnabled(true); + slotSelectedText(abjadText); + } + else + { + ui->textBrowser->clear(); + ui->textBrowser->setEnabled(false); + } +} diff --git a/src/abjadformmini.h b/src/abjadformmini.h new file mode 100644 index 0000000..dea40f1 --- /dev/null +++ b/src/abjadformmini.h @@ -0,0 +1,48 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef ABJADFORMMINI_H +#define ABJADFORMMINI_H + +#include +#include "common_functions.h" + +using std::wstring; + +namespace Ui { +class AbjadFormMini; +} + +class AbjadFormMini : public QMainWindow +{ + Q_OBJECT + +public slots: + void slotSelectedText(const QString &text); + +public: + explicit AbjadFormMini(QWidget *parent = nullptr); + AbjadFormMini(AppSettings *appSettings, QWidget *parent = nullptr); + ~AbjadFormMini(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void closeEvent(QCloseEvent *event) override; + +private slots: + void on_checkBox_toggled(bool checked); + +private: + Ui::AbjadFormMini *ui; + AppSettings *appSettings; + QString abjadText; +}; + +#endif // ABJADFORMMINI_H diff --git a/src/abjadformmini.ui b/src/abjadformmini.ui new file mode 100644 index 0000000..12b54ac --- /dev/null +++ b/src/abjadformmini.ui @@ -0,0 +1,76 @@ + + + AbjadFormMini + + + + 0 + 0 + 309 + 159 + + + + + Sahel + 11 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + + + classFD + + + حساب ابجد: + + + + + + + classFD + + + Qt::AlignCenter + + + true + + + + + + + + + classFD + + + جزئیات + + + + + + + classFD + + + + + + + + + diff --git a/src/aboutauthorform.cpp b/src/aboutauthorform.cpp new file mode 100644 index 0000000..2ec7a54 --- /dev/null +++ b/src/aboutauthorform.cpp @@ -0,0 +1,78 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "aboutauthorform.h" +#include "ui_aboutauthorform.h" + +#include + +AboutAuthorForm::AboutAuthorForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AboutAuthorForm) +{ + ui->setupUi(this); +} + +AboutAuthorForm::AboutAuthorForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AboutAuthorForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + QString backgroundColor = appSettings->isDarkMode ? "background-color:rgb(35,35,35);" : "background-color:rgb(255,255,255);"; + QString hafez = appSettings->isDarkMode ? "image:url(:/files/images/hafez-white.svg);" : "image:url(:/files/images/hafez.svg);"; + resize(1000, 580); + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("درباره نویسنده"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + setStyleSheet(backgroundColor); + ui->label->setStyleSheet(hafez); + ui->label->setFixedSize(ui->label->maximumWidth(), size().height() / 3); + + setHtml(); +} + +AboutAuthorForm::~AboutAuthorForm() +{ + delete ui; +} + +void AboutAuthorForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + close(); +} + +void AboutAuthorForm::resizeEvent(QResizeEvent *event) +{ + Q_UNUSED(event); // (void)event; + ui->label->setFixedSize(ui->label->maximumWidth(), size().height() / 3); +} + +void AboutAuthorForm::setHtml() +{ + QString html; + QString textColor = appSettings->isDarkMode ? "white" : "black"; + QFile file(":/files/html/about_author.html"); + + file.open(QIODevice::ReadOnly | QIODevice::Text); + html = file.readAll(); + file.close(); + + html.replace(QRegularExpression("\\$\\{FontName\\}"), appSettings->viewFN); + html.replace(QRegularExpression("\\$\\{FontSize\\}"), QString::number(appSettings->viewFS.toDouble())); + html.replace(QRegularExpression("\\$\\{TextColor\\}"), textColor); + html.replace(QRegularExpression("\\$\\{AppNameFa\\}"), Constants::AppNameFa); + + ui->textBrowser->setHtml(html); +} diff --git a/src/aboutauthorform.h b/src/aboutauthorform.h new file mode 100644 index 0000000..e96fa63 --- /dev/null +++ b/src/aboutauthorform.h @@ -0,0 +1,42 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef ABOUTAUTHORFORM_H +#define ABOUTAUTHORFORM_H + +#include +#include "common_functions.h" + +namespace Ui { +class AboutAuthorForm; +} + +class AboutAuthorForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit AboutAuthorForm(QWidget *parent = nullptr); + AboutAuthorForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~AboutAuthorForm(); + +public slots: + void setHtml(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void resizeEvent(QResizeEvent *event) override; + +private: + Ui::AboutAuthorForm *ui; + AppSettings *appSettings; +}; + +#endif // ABOUTAUTHORFORM_H diff --git a/src/aboutauthorform.ui b/src/aboutauthorform.ui new file mode 100644 index 0000000..f1be7df --- /dev/null +++ b/src/aboutauthorform.ui @@ -0,0 +1,67 @@ + + + AboutAuthorForm + + + + 0 + 0 + 721 + 415 + + + + + Sahel + 11 + + + + MainWindow + + + + + + + + 0 + 0 + + + + classView + + + + + + + + + + + 0 + 0 + + + + + Sahel + 11 + + + + classView + + + QFrame::NoFrame + + + + + + + + + diff --git a/src/aboutform.cpp b/src/aboutform.cpp new file mode 100644 index 0000000..b7ed4ff --- /dev/null +++ b/src/aboutform.cpp @@ -0,0 +1,84 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "aboutform.h" +#include "ui_aboutform.h" + +#include + +AboutForm::AboutForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AboutForm) +{ + ui->setupUi(this); +} + +AboutForm::AboutForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::AboutForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("درباره برنامه"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + + setHtml(); +} + +AboutForm::~AboutForm() +{ + delete ui; +} + +void AboutForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + close(); +} + +void AboutForm::setHtml() +{ + QString html; + QString textColor = appSettings->isDarkMode ? "white" : "black"; + QString persian_date; + QDate date(QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy")); + QFile file(":/files/html/about_ghazal.html"); + + if(date.isValid()) + persian_date = gregorianToPersian(date.day(), date.month(), date.year()); + else + persian_date = QString(__DATE__).simplified(); + + file.open(QIODevice::ReadOnly | QIODevice::Text); + html = file.readAll(); + file.close(); + + html.replace(QRegularExpression("\\$\\{FontName\\}"), appSettings->viewFN); + html.replace(QRegularExpression("\\$\\{FontSize\\}"), QString::number(appSettings->viewFS.toDouble())); + html.replace(QRegularExpression("\\$\\{TitleFontSize\\}"), ratioFontSize(appSettings->viewFS.toDouble(), 1.5)); + html.replace(QRegularExpression("\\$\\{TopicFontSize\\}"), ratioFontSize(appSettings->viewFS.toDouble(), 1.25)); + html.replace(QRegularExpression("\\$\\{TextColor\\}"), textColor); + html.replace(QRegularExpression("\\$\\{Rosybit\\}"), Constants::Rosybit); + html.replace(QRegularExpression("\\$\\{RosybitUrl\\}"), Constants::RosybitUrl); + html.replace(QRegularExpression("\\$\\{AppName\\}"), Constants::AppName); + html.replace(QRegularExpression("\\$\\{AppNameFa\\}"), Constants::AppNameFa); + html.replace(QRegularExpression("\\$\\{AppVersion\\}"), Constants::AppVersion); + html.replace(QRegularExpression("\\$\\{AppBuildDate\\}"), QString(__TIME__) + " " + persian_date); + html.replace(QRegularExpression("\\$\\{AppUrl\\}"), Constants::AppUrl); + html.replace(QRegularExpression("\\$\\{GitHub\\}"), Constants::GitHub); + html.replace(QRegularExpression("\\$\\{Email\\}"), Constants::Email); + html.replace(QRegularExpression("\\$\\{QtVersion\\}"), QT_VERSION_STR); + + ui->textBrowser->setHtml(html); +} diff --git a/src/aboutform.h b/src/aboutform.h new file mode 100644 index 0000000..e46945d --- /dev/null +++ b/src/aboutform.h @@ -0,0 +1,41 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef ABOUTFORM_H +#define ABOUTFORM_H + +#include +#include "common_functions.h" + +namespace Ui { +class AboutForm; +} + +class AboutForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit AboutForm(QWidget *parent = nullptr); + AboutForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~AboutForm(); + +public slots: + void setHtml(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + +private: + Ui::AboutForm *ui; + AppSettings *appSettings; +}; + +#endif // ABOUTFORM_H diff --git a/src/aboutform.ui b/src/aboutform.ui new file mode 100644 index 0000000..370e1a4 --- /dev/null +++ b/src/aboutform.ui @@ -0,0 +1,54 @@ + + + AboutForm + + + + 0 + 0 + 665 + 370 + + + + + Sahel + 11 + + + + Qt::RightToLeft + + + + + + + + 0 + 0 + + + + + Sahel + 11 + + + + classView + + + QFrame::NoFrame + + + true + + + + + + + + + diff --git a/src/appthemes.cpp b/src/appthemes.cpp new file mode 100644 index 0000000..01937ca --- /dev/null +++ b/src/appthemes.cpp @@ -0,0 +1,102 @@ +/* +############################################################################### +# # +# The MIT License # +# # +# Copyright (C) 2017 by Juergen Skrotzky (JorgenVikingGod@gmail.com) # +# >> https://github.com/Jorgen-VikingGod # +# # +# Sources: https://github.com/Jorgen-VikingGod/Qt-Frameless-Window-DarkStyle # +# # +############################################################################### +*/ + +#include "appthemes.h" + +LightStyle::LightStyle(const QString &additionalStyle) : LightStyle(styleBase()) {addStyle = additionalStyle;} + +LightStyle::LightStyle(QStyle *style) : QProxyStyle(style) {;} + +QStyle *LightStyle::styleBase(QStyle *style) const +{ + QString styleName; + +#if defined Q_OS_WIN + if(QSysInfo::productType().toLower() == "windows" && QSysInfo::productVersion().toLower().contains("xp")) + styleName = "windowsxp"; + else + styleName = "windowsvista"; +#elif defined Q_OS_MACOS + styleName = "macintosh"; +#else + styleName = "fusion"; +#endif + + QStyle *base = !style ? QStyleFactory::create(styleName) : style; + return base; +} + +QStyle *LightStyle::baseStyle() const {return styleBase();} + +void LightStyle::polish(QApplication *app) +{ + if(!app) return; + + // set stylesheet + app->setStyleSheet(addStyle); +} + +DarkStyle::DarkStyle(const QString &additionalStyle) : DarkStyle(styleBase()) {addStyle = additionalStyle;} + +DarkStyle::DarkStyle(QStyle *style) : QProxyStyle(style) {;} + +QStyle *DarkStyle::styleBase(QStyle *style) const +{ + QStyle *base = !style ? QStyleFactory::create("fusion") : style; + return base; +} + +QStyle *DarkStyle::baseStyle() const {return styleBase();} + +void DarkStyle::polish(QPalette &palette) +{ + // modify palette to dark + palette.setColor(QPalette::Window, QColor(53, 53, 53)); + palette.setColor(QPalette::WindowText, Qt::white); + palette.setColor(QPalette::Disabled, QPalette::WindowText, QColor(127, 127, 127)); + palette.setColor(QPalette::Base, QColor(42, 42, 42)); + palette.setColor(QPalette::AlternateBase, QColor(66, 66, 66)); + palette.setColor(QPalette::ToolTipBase, Qt::white); + palette.setColor(QPalette::ToolTipText, QColor(53, 53, 53)); + palette.setColor(QPalette::Text, Qt::white); + palette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127)); + palette.setColor(QPalette::Dark, QColor(35, 35, 35)); + palette.setColor(QPalette::Shadow, QColor(20, 20, 20)); + palette.setColor(QPalette::Button, QColor(53, 53, 53)); + palette.setColor(QPalette::ButtonText, Qt::white); + palette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127)); + palette.setColor(QPalette::BrightText, Qt::red); + palette.setColor(QPalette::Link, QColor(42, 130, 218)); + palette.setColor(QPalette::Highlight, QColor(42, 130, 218)); + palette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(80, 80, 80)); + palette.setColor(QPalette::HighlightedText, Qt::white); + palette.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(127, 127, 127)); +#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) // #if QT_VERSION >= 0x050C00 + palette.setColor(QPalette::PlaceholderText, QColor(127, 127, 127)); +#endif +} + +void DarkStyle::polish(QApplication *app) +{ + if(!app) return; + + // loadstylesheet + QFile qfDarkstyle(QStringLiteral(":/darkstyle/darkstyle.qss")); + if(qfDarkstyle.open(QIODevice::ReadOnly | QIODevice::Text)) + { + // set stylesheet + QString qsStylesheet = QString::fromLatin1(qfDarkstyle.readAll()); + app->setStyleSheet(qsStylesheet + addStyle); + qfDarkstyle.close(); + } +} diff --git a/src/appthemes.h b/src/appthemes.h new file mode 100644 index 0000000..d809d25 --- /dev/null +++ b/src/appthemes.h @@ -0,0 +1,58 @@ +/* +############################################################################### +# # +# The MIT License # +# # +# Copyright (C) 2017 by Juergen Skrotzky (JorgenVikingGod@gmail.com) # +# >> https://github.com/Jorgen-VikingGod # +# # +# Sources: https://github.com/Jorgen-VikingGod/Qt-Frameless-Window-DarkStyle # +# # +############################################################################### +*/ + +#ifndef APPTHEMES_HPP +#define APPTHEMES_HPP + +#include +#include +#include +#include +#include + +class LightStyle : public QProxyStyle +{ + Q_OBJECT + +public: + LightStyle(const QString &additionalStyle = ""); + explicit LightStyle(QStyle *style); + + QStyle *baseStyle() const; + + void polish(QApplication *app) override; + +private: + QStyle *styleBase(QStyle *style = Q_NULLPTR) const; + QString addStyle; +}; + +class DarkStyle : public QProxyStyle +{ + Q_OBJECT + +public: + DarkStyle(const QString &additionalStyle = ""); + explicit DarkStyle(QStyle *style); + + QStyle *baseStyle() const; + + void polish(QPalette &palette) override; + void polish(QApplication *app) override; + +private: + QStyle *styleBase(QStyle *style = Q_NULLPTR) const; + QString addStyle; +}; + +#endif // APPTHEMES_HPP diff --git a/src/common_functions.cpp b/src/common_functions.cpp new file mode 100644 index 0000000..4b52c01 --- /dev/null +++ b/src/common_functions.cpp @@ -0,0 +1,1614 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "common_functions.h" + +const QString Constants::Rosybit = "Rosybit"; +const QString Constants::RosybitFa = "رزی‌بیت"; +const QString Constants::RosybitUrl = "http://www.rosybit.com"; +const QString Constants::Programmer = "Aboutaleb Roshan"; +const QString Constants::ProgrammerFa = "ابوطالب روشن"; +const QString Constants::Email = "ab.roshan39@gmail.com"; +const QString Constants::AppName = "Ghazal"; +const QString Constants::AppNameFa = "غزل"; +const QString Constants::AppVersion = "1.4"; +const QString Constants::GitHub = "https://github.com/abroshan39/ghazal"; +const QString Constants::AppUrl = "http://www.rosybit.com/apps/ghazal"; +const QString Constants::DefaultDBName = "ganjoor.s3db"; +const QString Constants::SettingsFileName = "settings.conf"; +const QString Constants::HistoryFileName = "history.ghl"; + +bool isStdGanjoorDB(const QSqlDatabase &database, DatabaseType databaseType) +{ + QSqlQuery query(database); + + if(databaseType == MainDatabase) + { + if(query.exec("SELECT id, name, cat_id, description FROM poet") && + query.exec("SELECT id, poet_id, text, parent_id, url FROM cat") && + query.exec("SELECT id, cat_id, title, url FROM poem") && + query.exec("SELECT poem_id, vorder, position, text FROM verse")) + return true; + } + else if(databaseType == BookmarkDatabase) + { + if(query.exec("SELECT poem_id, verse_id, pos FROM fav")) + return true; + } + + return false; +} + +bool isStdGanjoorDB(const QString &database, DatabaseType databaseType) +{ + SqliteDB checkDB(database, "checkDatabase"); + bool result = isStdGanjoorDB(checkDB.DB(), databaseType); + checkDB.remove(); + + return result; +} + +void lineEditDirectionCorrector(QLineEdit *lineEdit, Qt::LayoutDirection direction) +{ + // https://stackoverflow.com/questions/10998105/qt-how-to-change-the-direction-of-placeholder-in-a-qlineedit + if(lineEdit) + { + if(direction == Qt::RightToLeft) + { + QKeyEvent e(QEvent::KeyPress, Qt::Key_Direction_R, Qt::NoModifier); + QApplication::sendEvent(lineEdit, &e); + lineEdit->setAlignment(Qt::AlignLeft); + } + else if(direction == Qt::LeftToRight) + { + QKeyEvent e(QEvent::KeyPress, Qt::Key_Direction_L, Qt::NoModifier); + QApplication::sendEvent(lineEdit, &e); + lineEdit->setAlignment(Qt::AlignLeft); + } + } +} + +void listWidgetPoetList(QListWidget *listWidget, const QSqlDatabase &database, bool checkable, const QString &strQuery) +{ + QSqlQuery query(database); + QList poetList; + QString delimiter = "||**|*|**||"; + + listWidget->clear(); + + query.exec(strQuery); + while(query.next()) + { + QString name = query.value(0).toString(); + QString id = query.value(1).toString(); + poetList.append(faReplaceChars(name) + delimiter + name + delimiter + id); + } + + std::sort(poetList.begin(), poetList.end(), faLessThan); + + QListWidgetItem *item; + for(int i = 0; i < poetList.count(); i++) + { + QStringList nameID = poetList[i].split(delimiter); + item = new QListWidgetItem(nameID[1]); + item->setData(Qt::UserRole, nameID[2]); + if(checkable) + item->setCheckState(Qt::Unchecked); + listWidget->addItem(item); + } +} + +bool listWidgetItemList(QListWidget *listWidget, const QSqlDatabase &database, const QString &id) +{ + int space_count = 25; + QString item_space = ""; + QSqlQuery query(database); + + listWidget->clear(); + + query.exec("SELECT text, id FROM cat WHERE parent_id = " + id); + if(query.first()) + { + query.previous(); + QListWidgetItem *item; + while(query.next()) + { + item = new QListWidgetItem(query.value(0).toString()); + item->setData(Qt::UserRole, "2-" + query.value(1).toString()); + listWidget->addItem(item); + } + space_count = 12; + item_space = " "; + } + + query.exec("SELECT title, id FROM poem WHERE cat_id = " + id); + if(query.first()) + { + query.previous(); + QString text, poemID; + QListWidgetItem *item; + while(query.next()) + { + text = query.value(0).toString(); + poemID = query.value(1).toString(); + item = new QListWidgetItem(item_space + listWidgetAddTitle(database, text, poemID, space_count)); + item->setData(Qt::UserRole, "3-" + poemID); + listWidget->addItem(item); + } + } + + return true; +} + +bool importDatabase(QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase, bool removePreVersion, int speed) +{ + QSqlQuery queryMainDB(mainDatabase), query(secondDatabase); + TableValues *tValues = new TableValues; + + if(removePreVersion) + { + removePoet(mainDatabase, commonPoetsID(mainDatabase, secondDatabase)); + } + else + { + if(existsCommonPoet(mainDatabase, secondDatabase)) + { + QStringList uncommonIDs(uncommonPoetsID(mainDatabase, secondDatabase)); + if(!uncommonIDs.isEmpty()) + importDatabaseByIDs(mainDatabase, secondDatabase, uncommonIDs, speed); + delete tValues; + return true; + } + } + + query.exec("SELECT id, name, cat_id, description FROM poet"); + while(query.next()) + { + tValues->clear(); + query.previous(); + for(int i = 0; i < speed; i++) + { + if(query.next()) + tValues->addValue(QString("(%1,'%2',%3,'%4')").arg(query.value(0).toInt()).arg(query.value(1).toString()).arg(query.value(2).toInt()).arg(query.value(3).toString())); + else + break; + } + queryMainDB.exec("INSERT INTO poet (id, name, cat_id, description) VALUES " + tValues->getValues()); + } + + query.exec("SELECT id, poet_id, text, parent_id, url FROM cat"); + while(query.next()) + { + tValues->clear(); + query.previous(); + for(int i = 0; i < speed; i++) + { + if(query.next()) + tValues->addValue(QString("(%1,%2,'%3',%4,'%5')").arg(query.value(0).toInt()).arg(query.value(1).toInt()).arg(query.value(2).toString()).arg(query.value(3).toInt()).arg(query.value(4).toString())); + else + break; + } + queryMainDB.exec("INSERT INTO cat (id, poet_id, text, parent_id, url) VALUES " + tValues->getValues()); + } + + query.exec("SELECT id, cat_id, title, url FROM poem"); + while(query.next()) + { + tValues->clear(); + query.previous(); + for(int i = 0; i < speed; i++) + { + if(query.next()) + tValues->addValue(QString("(%1,%2,'%3','%4')").arg(query.value(0).toInt()).arg(query.value(1).toInt()).arg(query.value(2).toString()).arg(query.value(3).toString())); + else + break; + } + queryMainDB.exec("INSERT INTO poem (id, cat_id, title, url) VALUES " + tValues->getValues()); + } + + query.exec("SELECT poem_id, vorder, position, text FROM verse"); + while(query.next()) + { + tValues->clear(); + query.previous(); + for(int i = 0; i < speed; i++) + { + if(query.next()) + tValues->addValue(QString("(%1,%2,%3,'%4')").arg(query.value(0).toInt()).arg(query.value(1).toInt()).arg(query.value(2).toInt()).arg(query.value(3).toString())); + else + break; + } + queryMainDB.exec("INSERT INTO verse (poem_id, vorder, position, text) VALUES " + tValues->getValues()); + } + + delete tValues; + return true; +} + +bool importDatabase(QSqlDatabase &mainDatabase, const QString &secondDatabase, bool removePreVersion, int speed) +{ + SqliteDB secondDB(secondDatabase, "secondDatabase"); + bool result = importDatabase(mainDatabase, secondDB.DB(), removePreVersion, speed); + secondDB.remove(); + + return result; +} + +bool importDatabaseByIDs(QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase, const QStringList &poetIDs, int speed) +{ + return exportDatabase(secondDatabase, mainDatabase, poetIDs, speed, false); +} + +bool exportDatabase(const QSqlDatabase &mainDatabase, QSqlDatabase &newDatabase, const QStringList &poetIDs, int speed, bool createNewTable) +{ + QSqlQuery queryMainDB(mainDatabase), query(mainDatabase), queryNewDB(newDatabase); + TableValues *tValues = new TableValues; + + if(createNewTable) + createGanjoorTable(newDatabase); + + for(int i = 0; i < poetIDs.count(); i++) + { + QString catID, pIN, vIN; + + queryMainDB.exec("SELECT id FROM cat WHERE poet_id = " + poetIDs[i]); + while(queryMainDB.next()) + { + pIN += (catID = queryMainDB.value(0).toString()) + ","; + query.exec("SELECT id FROM poem WHERE cat_id = " + catID); + while(query.next()) + vIN += query.value(0).toString() + ","; + } + pIN = pIN.left(pIN.size() - 1); + vIN = vIN.left(vIN.size() - 1); + + queryMainDB.exec("SELECT id, name, cat_id, description FROM poet WHERE id = " + poetIDs[i]); + while(queryMainDB.next()) + { + tValues->clear(); + queryMainDB.previous(); + for(int j = 0; j < speed; j++) + { + if(queryMainDB.next()) + tValues->addValue(QString("(%1,'%2',%3,'%4')").arg(queryMainDB.value(0).toInt()).arg(queryMainDB.value(1).toString()).arg(queryMainDB.value(2).toInt()).arg(queryMainDB.value(3).toString())); + else + break; + } + queryNewDB.exec("INSERT INTO poet (id, name, cat_id, description) VALUES " + tValues->getValues()); + } + + queryMainDB.exec("SELECT id, poet_id, text, parent_id, url FROM cat WHERE poet_id = " + poetIDs[i]); + while(queryMainDB.next()) + { + tValues->clear(); + queryMainDB.previous(); + for(int j = 0; j < speed; j++) + { + if(queryMainDB.next()) + tValues->addValue(QString("(%1,%2,'%3',%4,'%5')").arg(queryMainDB.value(0).toInt()).arg(queryMainDB.value(1).toInt()).arg(queryMainDB.value(2).toString()).arg(queryMainDB.value(3).toInt()).arg(queryMainDB.value(4).toString())); + else + break; + } + queryNewDB.exec("INSERT INTO cat (id, poet_id, text, parent_id, url) VALUES " + tValues->getValues()); + } + + queryMainDB.exec("SELECT id, cat_id, title, url FROM poem WHERE cat_id IN (" + pIN + ")"); + while(queryMainDB.next()) + { + tValues->clear(); + queryMainDB.previous(); + for(int j = 0; j < speed; j++) + { + if(queryMainDB.next()) + tValues->addValue(QString("(%1,%2,'%3','%4')").arg(queryMainDB.value(0).toInt()).arg(queryMainDB.value(1).toInt()).arg(queryMainDB.value(2).toString()).arg(queryMainDB.value(3).toString())); + else + break; + } + queryNewDB.exec("INSERT INTO poem (id, cat_id, title, url) VALUES " + tValues->getValues()); + } + + queryMainDB.exec("SELECT poem_id, vorder, position, text FROM verse WHERE poem_id IN (" + vIN + ")"); + while(queryMainDB.next()) + { + tValues->clear(); + queryMainDB.previous(); + for(int j = 0; j < speed; j++) + { + if(queryMainDB.next()) + tValues->addValue(QString("(%1,%2,%3,'%4')").arg(queryMainDB.value(0).toInt()).arg(queryMainDB.value(1).toInt()).arg(queryMainDB.value(2).toInt()).arg(queryMainDB.value(3).toString())); + else + break; + } + queryNewDB.exec("INSERT INTO verse (poem_id, vorder, position, text) VALUES " + tValues->getValues()); + } + } + + delete tValues; + return true; +} + +bool removePoet(QSqlDatabase &database, const QStringList &poetIDs) +{ + QSqlQuery query(database), query2(database); + + for(int i = 0; i < poetIDs.count(); i++) + { + QString catID, pIN, vIN; + + query.exec("SELECT id FROM cat WHERE poet_id = " + poetIDs[i]); + while(query.next()) + { + pIN += (catID = query.value(0).toString()) + ","; + query2.exec("SELECT id FROM poem WHERE cat_id = " + catID); + while(query2.next()) + vIN += query2.value(0).toString() + ","; + } + pIN = pIN.left(pIN.size() - 1); + vIN = vIN.left(vIN.size() - 1); + + query.exec("DELETE FROM verse WHERE poem_id IN (" + vIN + ")"); + query.exec("DELETE FROM poem WHERE cat_id IN (" + pIN + ")"); + query.exec("DELETE FROM cat WHERE poet_id = " + poetIDs[i]); + query.exec("DELETE FROM poet WHERE id = " + poetIDs[i]); + } + + return true; +} + +bool createGanjoorTable(QSqlDatabase &database) +{ + QSqlQuery query(database); + + // TABLES: + query.exec("CREATE TABLE poet (id INTEGER NOT NULL, name NVARCHAR(20), cat_id INTEGER, description TEXT, PRIMARY KEY(id))"); + query.exec("CREATE TABLE cat (id INTEGER NOT NULL, poet_id INTEGER, text NVARCHAR(100), parent_id INTEGER, url NVARCHAR(255), PRIMARY KEY(id))"); + query.exec("CREATE TABLE poem (id INTEGER, cat_id INTEGER, title NVARCHAR(255), url NVARCHAR(255), PRIMARY KEY(id))"); + query.exec("CREATE TABLE verse (poem_id INTEGER, vorder INTEGER, position INTEGER, text TEXT)"); + + query.exec("CREATE TABLE fav (poem_id INTEGER, verse_id INTEGER, pos INTEGER)"); + query.exec("CREATE TABLE poemsnd (poem_id INTEGER NOT NULL, id INTEGER NOT NULL, filepath TEXT, description TEXT, dnldurl TEXT, isdirect INTEGER, syncguid TEXT, fchksum TEXT, isuploaded INTEGER)"); + query.exec("CREATE TABLE sndsync (poem_id INTEGER NOT NULL, snd_id INTEGER NOT NULL, verse_order INTEGER NOT NULL, milisec INTEGER NOT NULL)"); + query.exec("CREATE TABLE gil (cat_id INTEGER)"); + query.exec("CREATE TABLE gver (curver INTEGER)"); + + // INDICES: + query.exec("CREATE INDEX cat_pid ON cat (parent_id ASC)"); + query.exec("CREATE INDEX poem_cid ON poem (cat_id ASC)"); + query.exec("CREATE INDEX verse_pid ON verse (poem_id ASC)"); + + query.exec("CREATE INDEX idx_poem_title ON poem (id ASC, title ASC)"); + query.exec("CREATE UNIQUE INDEX idx_poem_catid ON poem (id ASC, cat_id ASC)"); + query.exec("CREATE UNIQUE INDEX idx_verse ON verse (poem_id ASC, vorder ASC)"); + + return true; +} + +bool createGanjoorTable(const QString &database) +{ + SqliteDB sqliteDB(database, "createGanjoorTable"); + bool result = createGanjoorTable(sqliteDB.DB()); + sqliteDB.remove(); + + return result; +} + +QString getPoetNameByPoetID(const QSqlDatabase &database, const QString &id) +{ + QSqlQuery query("SELECT name FROM poet WHERE id = " + id, database); + if(query.next()) + return query.value(0).toString(); + return QString(); +} + +QString getPoetIDByCatID(const QSqlDatabase &database, const QString &id) +{ + QSqlQuery query("SELECT id FROM poet WHERE cat_id = " + id, database); + if(query.next()) + return query.value(0).toString(); + return QString(); +} + +QString getPositionByPoemIDVorder(const QSqlDatabase &database, const QString &id, const QString &vorder) +{ + QSqlQuery query(QString("SELECT position FROM verse WHERE poem_id = %1 AND vorder = %2").arg(id, vorder), database); + if(query.next()) + return query.value(0).toString(); + return QString(); +} + +QStringList getPoetsIDs(const QSqlDatabase &database) +{ + QSqlQuery query(database); + QStringList poetIDs; + + query.exec("SELECT id FROM poet"); + while(query.next()) + poetIDs << query.value(0).toString(); + + return poetIDs; +} + +bool existsCommonPoet(const QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase) +{ + QSqlQuery query(mainDatabase); + QStringList poetIDs(getPoetsIDs(secondDatabase)); + + for(int i = 0; i < poetIDs.count(); i++) + { + query.exec("SELECT * FROM poet WHERE id = " + poetIDs[i]); + if(query.first()) + return true; + } + + return false; +} + +bool existsCommonPoet(const QSqlDatabase &mainDatabase, const QStringList &poetIDs) +{ + QSqlQuery query(mainDatabase); + + for(int i = 0; i < poetIDs.count(); i++) + { + query.exec("SELECT * FROM poet WHERE id = " + poetIDs[i]); + if(query.first()) + return true; + } + + return false; +} + +QStringList commonPoetsID(const QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase) +{ + QSqlQuery query(mainDatabase); + QStringList poetIDs(getPoetsIDs(secondDatabase)), newPoetIDs; + + for(int i = 0; i < poetIDs.count(); i++) + { + query.exec("SELECT * FROM poet WHERE id = " + poetIDs[i]); + if(query.first()) + newPoetIDs << poetIDs[i]; + } + + return newPoetIDs; +} + +QStringList uncommonPoetsID(const QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase) +{ + QSqlQuery query(mainDatabase); + QStringList poetIDs(getPoetsIDs(secondDatabase)), newPoetIDs; + + for(int i = 0; i < poetIDs.count(); i++) + { + query.exec("SELECT * FROM poet WHERE id = " + poetIDs[i]); + if(!query.first()) + newPoetIDs << poetIDs[i]; + } + + return newPoetIDs; +} + +QString listWidgetAddTitle(const QSqlDatabase &database, const QString &text, const QString &poemID, int spacePermittedNumber) +{ + QString str(text); + QSqlQuery query(database); + query.exec("SELECT text FROM verse WHERE poem_id = " + poemID + " AND vorder = 1"); + query.next(); + str = str + ": " + query.value(0).toString(); + return spaceReplace(str, "…", spacePermittedNumber); +} + +GanjoorPath recursiveIDs(const QSqlDatabase &database, const QString &level, const QString &id) +{ + GanjoorPath gp; + QString parent_id, current_id(id); + QSqlQuery query(database); + + if(level == "3") + { + query.exec("SELECT cat_id, title FROM poem WHERE id = " + current_id); + query.next(); + + gp.text << query.value(1).toString(); + gp.id << current_id; + gp.level << "3"; + + current_id = query.value(0).toString(); + } + + query.exec("SELECT parent_id, text FROM cat WHERE id = " + current_id); + while(query.next()) + { + gp.text << query.value(1).toString(); + gp.id << current_id; + + parent_id = query.value(0).toString(); + if(parent_id == "0") + { + gp.level << "1"; + break; + } + else + { + gp.level << "2"; + } + + current_id = parent_id; + query.exec("SELECT parent_id, text FROM cat WHERE id = " + current_id); + } + + return gp; +} + +GanjoorPath recursiveIDs(const QSqlDatabase &database, const QString &levelID) +{ + QString level(levelID.left(1)), id(levelID.right(levelID.size() - 2)); + return recursiveIDs(database, level, id); +} + +QString idTitle(const QSqlDatabase &database, const QString &level, const QString &id) +{ + QString parent_id, current_id(id); + QSqlQuery query(database); + + if(level == "3") + { + query.exec("SELECT cat_id, title FROM poem WHERE id = " + current_id); + query.next(); + current_id = query.value(0).toString(); + } + + query.exec("SELECT parent_id, text FROM cat WHERE id = " + current_id); + while(query.next()) + { + parent_id = query.value(0).toString(); + if(parent_id == "0") + return query.value(1).toString(); + + current_id = parent_id; + query.exec("SELECT parent_id, text FROM cat WHERE id = " + current_id); + } + + return QString(); +} + +QString idTitle(const QSqlDatabase &database, const QString &levelID) +{ + QString level(levelID.left(1)), id(levelID.right(levelID.size() - 2)); + return idTitle(database, level, id); +} + +QString spaceReplace(const QString &text, const QString &replaceWith, int permittedNumber) +{ + QString str(text); + +// QRegExp regex("(\\s+)"); +// int count = 0, pos = 0; +// while((pos = regex.indexIn(str, pos)) != -1 && (count++) < permittedNumber) +// pos += regex.matchedLength(); + + QRegularExpression regex("(\\s+)"); + QRegularExpressionMatchIterator i = regex.globalMatch(str); + int count = 0, pos = 0; + while(i.hasNext() && count <= permittedNumber) + { + pos = i.next().capturedStart(); + count++; + } + + if(count > permittedNumber) + str = str.left(pos) + replaceWith; + + str = str.replace(QRegularExpression("\\s+"), " "); + + return str; +} + +QList xmlPoetListElements(const QDomElement &root, const QString &tagName) +{ + QList list; + QDomNodeList poetNodeList = root.elementsByTagName(tagName); + + if(!root.tagName().contains("ganjoor", Qt::CaseInsensitive)) + return list; + + for(int i = 0; i < poetNodeList.count(); i++) + { + XmlPoet xmlPoet; + QDomNode poetNode = poetNodeList.at(i); + + xmlPoet.CatName = poetNode.namedItem("CatName").toElement().text(); + xmlPoet.PoetID = poetNode.namedItem("PoetID").toElement().text(); + xmlPoet.CatID = poetNode.namedItem("CatID").toElement().text(); + xmlPoet.DownloadUrl = poetNode.namedItem("DownloadUrl").toElement().text(); + xmlPoet.FileExt = poetNode.namedItem("FileExt").toElement().text(); + xmlPoet.ImageUrl = poetNode.namedItem("ImageUrl").toElement().text(); + xmlPoet.FileSizeInByte = poetNode.namedItem("FileSizeInByte").toElement().text(); + xmlPoet.LowestPoemID = poetNode.namedItem("LowestPoemID").toElement().text(); + xmlPoet.PubDate = poetNode.namedItem("PubDate").toElement().text(); + + list.append(xmlPoet); + } + + return list; +} + +void tableWidgetDownloadList(QTableWidget *tableWidget, const QSqlDatabase &mainDatabase, const QList &list, QList &preInstalled, QList ¬Installed, bool isDarkMode, TableDisplayType tableDisplayType) +{ + tableWidget->clear(); + tableWidget->model()->removeRows(0, tableWidget->model()->rowCount()); + tableWidget->model()->removeColumns(0, tableWidget->model()->columnCount()); + tableWidget->setColumnCount(5); + tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + + QStringList colList; + colList << "نام شاعر یا نویسنده" << "حجم فایل" << "تاریخ انتشار"; + tableWidget->setHorizontalHeaderLabels(colList); + + preInstalled.clear(); + notInstalled.clear(); + int row_count = 0; + for(int i = 0; i < list.count(); i++) + { + QString catName = list[i].CatName; + QString poetID = list[i].PoetID; + long long int fileSize = list[i].FileSizeInByte.toInt(); + QString pubDate = list[i].PubDate; + QString downloadURL = list[i].DownloadUrl; + + bool isPoetExist = false; + if(mainDatabase.isOpen()) + { + QSqlQuery query(mainDatabase); + query.exec("SELECT name FROM poet WHERE id = " + poetID); + isPoetExist = query.first(); + } + + if(tableDisplayType == NotInstalledItems) + if(isPoetExist) + continue; + + if(tableDisplayType == PreInstalledItems) + if(!isPoetExist) + continue; + + tableWidget->insertRow(row_count); + + QStringList dmyList = pubDate.split("-"); + int d = dmyList[2].toInt(), m = dmyList[1].toInt(), y = dmyList[0].toInt(); + pubDate = gregorianToPersian(d, m, y, "/", false, false); + + QTableWidgetItem *item1 = new QTableWidgetItem; + QTableWidgetItem *item2 = new QTableWidgetItem; + QTableWidgetItem *item3 = new QTableWidgetItem; + QTableWidgetItem *item4 = new QTableWidgetItem; + QTableWidgetItem *item5 = new QTableWidgetItem; + + item1->setCheckState(Qt::Unchecked); + item1->setData(Qt::UserRole, poetID); + + if(isPoetExist) + { + preInstalled << row_count; + if(!isDarkMode) + item1->setBackground(QColor(144, 238, 144)); + else + item1->setBackground(QColor(20, 20, 20)); + } + else + { + notInstalled << row_count; + if(!isDarkMode) + item1->setBackground(QColor(255, 153, 153)); + else + item1->setBackground(QColor(60, 60, 60)); + } + + item1->setText(catName); + item2->setText(byteToHuman(fileSize)); + item3->setText(pubDate); + item4->setText(downloadURL); + item5->setText(QString::number(fileSize)); + + tableWidget->setItem(row_count, 0, item1); + tableWidget->setItem(row_count, 1, item2); + tableWidget->setItem(row_count, 2, item3); + tableWidget->setItem(row_count, 3, item4); + tableWidget->setItem(row_count, 4, item5); + + row_count++; + } + tableWidget->hideColumn(3); + tableWidget->hideColumn(4); + tableWidget->horizontalHeader()->setDefaultSectionSize(180); +} + +void dbCloseRemove(QSqlDatabase *database) +{ + QString connection; + connection = database->connectionName(); + database->close(); + *database = QSqlDatabase(); + database->removeDatabase(connection); +} + +void dbCloseRemove(QSqlDatabase &database) +{ + QString connection; + connection = database.connectionName(); + database.close(); + database = QSqlDatabase(); + database.removeDatabase(connection); +} + +QString oldStyleHtml(const QSqlDatabase &database, const QString &poemID, const QString &fontSize, bool isDarkMode, const QStringList &highlightText, bool showAllBookmarks, const QString &bookmarkVerseID) +{ + QSqlQuery query(database), queryIn(database); + QString textColor = isDarkMode ? "white" : "black"; + QString searchHighlightCssClass = "shClass"; + double size = fontSize.toDouble(); + bool preBreak = true; + bool pos2Break = false; + bool highlight = !highlightText.isEmpty(); + bool showBookmark = !bookmarkVerseID.isEmpty(); + + query.exec("SELECT title FROM poem WHERE id = " + poemID); + query.next(); + QString title = query.value(0).toString(); + + QString strHtml; + strHtml = "\n"; + strHtml += "\n"; + strHtml += "

" + title + "

\n"; + + query.exec("SELECT poem_id FROM verse WHERE poem_id = " + poemID); + + int current_row = 0; + while(query.seek(current_row)) + { + QString vorderMain, posMain, textMain; + QString vorderNext, posNext, textNext; + QString hrefMain, hrefNext; + + queryIn.exec("SELECT vorder, position, text FROM verse WHERE poem_id = " + poemID + " AND vorder = " + QString::number(++current_row)); + queryIn.next(); + vorderMain = queryIn.value(0).toString(); + posMain = queryIn.value(1).toString(); + textMain = queryIn.value(2).toString().trimmed(); + hrefMain = "3-" + poemID + "-" + vorderMain; + htmlEntitiesAndNewLine(textMain); + if(showAllBookmarks && !showBookmark && isBookmarked(database, "3", poemID, vorderMain)) + bookmarkHighlighter(textMain); + else if(showBookmark && vorderMain == bookmarkVerseID) + bookmarkHighlighter(textMain); + if(highlight) + searchHighlighter(textMain, highlightText, searchHighlightCssClass); + + if(posMain == "0") + { + queryIn.exec("SELECT vorder, position, text FROM verse WHERE poem_id = " + poemID + " AND vorder = " + QString::number(++current_row)); + if(queryIn.next()) + { + vorderNext = queryIn.value(0).toString(); + posNext = queryIn.value(1).toString(); + textNext = queryIn.value(2).toString().trimmed(); + hrefNext = "3-" + poemID + "-" + vorderNext; + htmlEntitiesAndNewLine(textNext); + if(showAllBookmarks && !showBookmark && isBookmarked(database, "3", poemID, vorderNext)) + bookmarkHighlighter(textNext); + else if(showBookmark && vorderNext == bookmarkVerseID) + bookmarkHighlighter(textNext); + if(highlight) + searchHighlighter(textNext, highlightText, searchHighlightCssClass); + } + } + else if(posMain == "2") + { + queryIn.exec("SELECT vorder, position, text FROM verse WHERE poem_id = " + poemID + " AND vorder = " + QString::number(current_row + 1)); + if(queryIn.next()) + posNext = queryIn.value(1).toString(); + } + + if(posMain == "0" && posNext != "1") + { + textNext = ""; + current_row--; + } + else if(posMain == "1") + { + textNext = textMain; + textMain = ""; + hrefNext = hrefMain; + } + else if(posMain == "2" && posNext != "3") + { + pos2Break = true; + } + + if(posMain == "0" || posMain == "1") + { + strHtml += "

" + lBreakAdder(preBreak) + textMain + "

\n"; + strHtml += "

" + textNext + "

\n"; + preBreak = false; + } + else if(posMain == "-1") + { + strHtml += "

" + lBreakAdder(preBreak) + textMain + "

\n"; + preBreak = true; + } + else if(posMain == "2") + { + strHtml += "

" + lBreakAdder(preBreak) + textMain + (pos2Break ? "
" : "") + "

\n"; + preBreak = pos2Break; + pos2Break = false; + } + else if(posMain == "3") + { + strHtml += "

" + textMain + "

\n"; + preBreak = true; + } + else if(posMain == "4") + { + strHtml += "

" + textMain + "

\n"; + preBreak = false; + } + } + strHtml += ""; + + return strHtml; +} + +QString newStyleHtml(const QSqlDatabase &database, const QString &poemID, const QString &fontSize, bool isDarkMode, const QStringList &highlightText, bool showAllBookmarks, const QString &bookmarkVerseID, int hemistichDistance) +{ + QSqlQuery query(database), queryIn(database); + QString textColor = isDarkMode ? "white" : "black"; + QString searchHighlightCssClass = "shClass"; + double size = fontSize.toDouble(); + bool preBreak = true; + bool pos2Break = false; + bool highlight = !highlightText.isEmpty(); + bool showBookmark = !bookmarkVerseID.isEmpty(); + bool isTableOpen = false; + QString hemistichDis = QString::number(hemistichDistance / 2); + + query.exec("SELECT title FROM poem WHERE id = " + poemID); + query.next(); + QString title = query.value(0).toString(); + + QString strHtml; + strHtml = "\n"; + strHtml += "\n"; + strHtml += "

" + title + "

\n"; + + query.exec("SELECT poem_id FROM verse WHERE poem_id = " + poemID); + + int current_row = 0; + while(query.seek(current_row)) + { + QString vorderMain, posMain, textMain; + QString vorderNext, posNext, textNext; + QString hrefMain, hrefNext; + + queryIn.exec("SELECT vorder, position, text FROM verse WHERE poem_id = " + poemID + " AND vorder = " + QString::number(++current_row)); + queryIn.next(); + vorderMain = queryIn.value(0).toString(); + posMain = queryIn.value(1).toString(); + textMain = queryIn.value(2).toString().trimmed(); + hrefMain = "3-" + poemID + "-" + vorderMain; + htmlEntitiesAndNewLine(textMain); + if(showAllBookmarks && !showBookmark && isBookmarked(database, "3", poemID, vorderMain)) + bookmarkHighlighter(textMain); + else if(showBookmark && vorderMain == bookmarkVerseID) + bookmarkHighlighter(textMain); + if(highlight) + searchHighlighter(textMain, highlightText, searchHighlightCssClass); + + if(posMain == "0") + { + queryIn.exec("SELECT vorder, position, text FROM verse WHERE poem_id = " + poemID + " AND vorder = " + QString::number(++current_row)); + if(queryIn.next()) + { + vorderNext = queryIn.value(0).toString(); + posNext = queryIn.value(1).toString(); + textNext = queryIn.value(2).toString().trimmed(); + hrefNext = "3-" + poemID + "-" + vorderNext; + htmlEntitiesAndNewLine(textNext); + if(showAllBookmarks && !showBookmark && isBookmarked(database, "3", poemID, vorderNext)) + bookmarkHighlighter(textNext); + else if(showBookmark && vorderNext == bookmarkVerseID) + bookmarkHighlighter(textNext); + if(highlight) + searchHighlighter(textNext, highlightText, searchHighlightCssClass); + } + } + else if(posMain == "2") + { + queryIn.exec("SELECT vorder, position, text FROM verse WHERE poem_id = " + poemID + " AND vorder = " + QString::number(current_row + 1)); + if(queryIn.next()) + posNext = queryIn.value(1).toString(); + } + + if(posMain == "0" && posNext != "1") + { + textNext = ""; + current_row--; + } + else if(posMain == "1") + { + textNext = textMain; + textMain = ""; + hrefNext = hrefMain; + } + else if(posMain == "2" && posNext != "3") + { + pos2Break = true; + } + + if(posMain == "0" || posMain == "1") + { + strHtml += openTable(isTableOpen) + "\n"; + strHtml += "" + textNext + "\n"; + strHtml += "\u200c\u200c\u200c\u200c\u200c\n"; + strHtml += "" + textMain + "\n"; + strHtml += "\n"; + preBreak = false; + } + else if(posMain == "-1") + { + strHtml += closeTable(isTableOpen) + "

" + lBreakAdder(preBreak) + textMain + "

\n"; + preBreak = true; + } + else if(posMain == "2") + { + strHtml += closeTable(isTableOpen) + "

" + lBreakAdder(preBreak) + textMain + (pos2Break ? "
" : "") + "

\n"; + preBreak = pos2Break; + pos2Break = false; + } + else if(posMain == "3") + { + strHtml += closeTable(isTableOpen) + "

" + textMain + "

\n"; + preBreak = true; + } + else if(posMain == "4") + { + strHtml += closeTable(isTableOpen) + "

" + textMain + "

\n"; + preBreak = false; + } + } + strHtml += closeTable(isTableOpen) + ""; + + return strHtml; +} + +inline void htmlEntitiesAndNewLine(QString &str) +{ + str.replace("&", "&"); // This line must be first. + str.replace("<", "<"); + str.replace(">", ">"); + str.replace("\"", """); + str.replace("'", "'"); + + str.replace("\r\n", "\n"); + str.replace("\r", "\n"); + str = str.trimmed(); + str.replace("\n", "
"); +} + +inline QString openTable(bool &isTableOpen) +{ + if(!isTableOpen) + { + isTableOpen = true; + return "\n"; + } + return ""; +} + +inline QString closeTable(bool &isTableOpen) +{ + if(isTableOpen) + { + isTableOpen = false; + return "
\n"; + } + return ""; +} + +inline QString lBreakAdder(bool preBreak) +{ + if(preBreak) + return ""; + return "
"; +} + +inline void bookmarkHighlighter(QString &str) +{ + str = "" + str + ""; +} + +void searchHighlighter(QString &text, const QStringList &list, const QString &cssClass) +{ + QString textCopy(text); + QStringList listCopy(list); + QString openTag = QString("").arg(cssClass); + QString closeTag = QString(""); + QString diacritics_zwnj = "[" + Constants::DIACRITICS + Constants::ZWNJ + "]*"; + + textCopy.replace(Constants::A_TYPES_REGEX, Constants::A_PERSIAN); + textCopy.replace(Constants::E_TYPES_REGEX, Constants::E_PERSIAN); + textCopy.replace(Constants::K_TYPES_REGEX, Constants::K_PERSIAN); + textCopy.replace(Constants::V_TYPES_REGEX, Constants::V_PERSIAN); + textCopy.replace(Constants::H_TYPES_REGEX, Constants::H_PERSIAN); + + for(int i = 0; i < list.count(); i++) + { + listCopy[i].replace(Constants::A_TYPES_REGEX, Constants::A_PERSIAN); + listCopy[i].replace(Constants::E_TYPES_REGEX, Constants::E_PERSIAN); + listCopy[i].replace(Constants::K_TYPES_REGEX, Constants::K_PERSIAN); + listCopy[i].replace(Constants::V_TYPES_REGEX, Constants::V_PERSIAN); + listCopy[i].replace(Constants::H_TYPES_REGEX, Constants::H_PERSIAN); + + listCopy[i] = listCopy[i].split("").join(diacritics_zwnj); + + QRegularExpression regex(listCopy[i]); + QRegularExpressionMatch match; + match = regex.match(textCopy); + while(match.hasMatch()) + { + text.insert(match.capturedStart(), openTag); + text.insert(match.capturedEnd() + openTag.size(), closeTag); + textCopy.insert(match.capturedStart(), openTag); + textCopy.insert(match.capturedEnd() + openTag.size(), closeTag); + match = regex.match(textCopy, match.capturedEnd() + openTag.size() + closeTag.size()); + } + } +} + +QString previousPoem(const QSqlDatabase &database, const QString &level, const QString &id) +{ + QString cat_id; + QSqlQuery query(database); + + if(level == "3") + { + query.exec("SELECT cat_id FROM poem WHERE id = " + id); + query.next(); + + cat_id = query.value(0).toString(); + + query.exec(QString("SELECT id FROM poem WHERE cat_id = %1 AND id < %2 ORDER BY id DESC LIMIT 1").arg(cat_id).arg(id)); + if(query.first()) + return "3-" + query.value(0).toString(); + } + + return QString(); +} + +QString previousPoem(const QSqlDatabase &database, const QString &levelID) +{ + QString level(levelID.left(1)), id(levelID.right(levelID.size() - 2)); + return previousPoem(database, level, id); +} + +QString nextPoem(const QSqlDatabase &database, const QString &level, const QString &id) +{ + QString cat_id; + QSqlQuery query(database); + + if(level == "3") + { + query.exec("SELECT cat_id FROM poem WHERE id = " + id); + query.next(); + + cat_id = query.value(0).toString(); + + query.exec(QString("SELECT id FROM poem WHERE cat_id = %1 AND id > %2 LIMIT 1").arg(cat_id).arg(id)); + if(query.first()) + return "3-" + query.value(0).toString(); + } + + return QString(); +} + +QString nextPoem(const QSqlDatabase &database, const QString &levelID) +{ + QString level(levelID.left(1)), id(levelID.right(levelID.size() - 2)); + return nextPoem(database, level, id); +} + +bool isBookmarked(const QSqlDatabase &database, const QString &level, const QString &id, const QString &verse_id) +{ + if(level == "3") + { + QSqlQuery query(database); + query.exec(QString("SELECT * FROM fav WHERE poem_id = %1 AND verse_id = %2").arg(id).arg(verse_id)); + + if(query.first()) + return true; + } + + return false; +} + +bool isBookmarked(const QSqlDatabase &database, const QString &levelID, const QString &verse_id) +{ + QString level(levelID.left(1)), id(levelID.right(levelID.size() - 2)); + return isBookmarked(database, level, id, verse_id); +} + +void setBookmarked(const QSqlDatabase &database, const QString &level, const QString &id, const QString &verse_id, bool value) +{ + if(level == "3") + { + bool preValue; + QSqlQuery query(database); + query.exec(QString("SELECT * FROM fav WHERE poem_id = %1 AND verse_id = %2").arg(id).arg(verse_id)); + preValue = query.first(); + + if(value && !preValue) + { + int pos = 0; + query.exec("SELECT pos FROM fav ORDER BY pos DESC LIMIT 1"); + if(query.first()) + pos = query.value(0).toInt() + 1; + + query.exec(QString("INSERT INTO fav (poem_id, verse_id, pos) VALUES (%1,%2,%3)").arg(id).arg(verse_id).arg(pos)); + } + else if(!value && preValue) + { + query.exec(QString("DELETE FROM fav WHERE poem_id = %1 AND verse_id = %2").arg(id).arg(verse_id)); + } + } +} + +void setBookmarked(const QSqlDatabase &database, const QString &levelID, const QString &verse_id, bool value) +{ + QString level(levelID.left(1)), id(levelID.right(levelID.size() - 2)); + setBookmarked(database, level, id, verse_id, value); +} + +bool importBookmarks(QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase, int speed) +{ + QSqlQuery queryMainDB(mainDatabase), query(secondDatabase); + TableValues *tValues = new TableValues; + + query.exec("SELECT poem_id, verse_id, pos FROM fav"); + while(query.next()) + { + tValues->clear(); + query.previous(); + for(int i = 0; i < speed; i++) + { + if(query.next()) + tValues->addValue(QString("(%1,%2,%3)").arg(query.value(0).toInt()).arg(query.value(1).toInt()).arg(query.value(2).toInt())); + else + break; + } + queryMainDB.exec("INSERT INTO fav (poem_id, verse_id, pos) VALUES " + tValues->getValues()); + } + + delete tValues; + return true; +} + +bool importBookmarks(QSqlDatabase &mainDatabase, const QString &secondDatabase, int speed) +{ + SqliteDB secondDB(secondDatabase, "secondDatabase"); + bool result = importBookmarks(mainDatabase, secondDB.DB(), speed); + secondDB.remove(); + + return result; +} + +bool exportBookmarks(const QSqlDatabase &mainDatabase, QSqlDatabase &newDatabase, int speed) +{ + QSqlQuery queryMainDB(mainDatabase), queryNewDB(newDatabase); + TableValues *tValues = new TableValues; + + queryNewDB.exec("CREATE TABLE fav (poem_id INTEGER, verse_id INTEGER, pos INTEGER)"); + + queryMainDB.exec("SELECT poem_id, verse_id, pos FROM fav"); + while(queryMainDB.next()) + { + tValues->clear(); + queryMainDB.previous(); + for(int i = 0; i < speed; i++) + { + if(queryMainDB.next()) + tValues->addValue(QString("(%1,%2,%3)").arg(queryMainDB.value(0).toInt()).arg(queryMainDB.value(1).toInt()).arg(queryMainDB.value(2).toInt())); + else + break; + } + queryNewDB.exec("INSERT INTO fav (poem_id, verse_id, pos) VALUES " + tValues->getValues()); + } + + delete tValues; + return true; +} + +QString randString(int len) +{ + return QUuid::createUuid().toString().remove(QRegularExpression("\\{|\\}|\\-")).left(len).toUpper(); +} + +QString createDBDialog(QWidget *parent, const QString &defaultFilePath) +{ + QString filter = "SQLite 3 Database files (*.s3db *.db *.sqlite3 *.sqlite);;Ganjoor Database files (*.gdb);;Database files (*.db)"; + QString file_path = QFileDialog::getSaveFileName(parent, "Save As", defaultFilePath, filter); + if(!file_path.isEmpty()) + { + QFileInfo file(file_path); + QFileInfo dir(file.path()); + if(dir.isWritable()) + { + if(QFile::exists(file_path) && !isStdGanjoorDB(file_path)) + QFile::remove(file_path); + + if(!QFile::exists(file_path) || !isStdGanjoorDB(file_path)) + createGanjoorTable(file_path); + + return file_path; + } + else + { + messageBox("خطا", "این مسیر قابل نوشتن نیست! لطفا مسیر دیگری انتخاب کنید.", Warning, parent); + } + } + else + { + messageBox("پیام", "لطفا مسیر را به درستی انتخاب کنید!", Warning, parent); + } + + return QString(); +} + +QString writableDirDialog(QWidget *parent, const QString &defaultDirPath) +{ + QString dir_path = QFileDialog::getExistingDirectory(parent, "Select Directory", defaultDirPath, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + if(!dir_path.isEmpty()) + { + if(QFileInfo(dir_path).isWritable()) + return dir_path; + else + messageBox("خطا", "این مسیر قابل نوشتن نیست! لطفا مسیر دیگری انتخاب کنید.", Warning, parent); + } + else + { + messageBox("پیام", "لطفا مسیر را به درستی انتخاب کنید!", Warning, parent); + } + + return QString(); +} + +QMessageBox::StandardButton messageBox(const QString &title, const QString &text, MessageBoxType messageBoxType, QWidget *parent, QMessageBox::StandardButton defaultButton) +{ + QMessageBox msgBox(parent); + + msgBox.setLayoutDirection(Qt::LeftToRight); + msgBox.setWindowTitle(title); + msgBox.setText(text); // msgBox.setText("

" + text + "

"); + + if(messageBoxType == Information || messageBoxType == Warning || messageBoxType == Critical) + { + QPushButton *ok = new QPushButton("تایید"); + msgBox.addButton(ok, QMessageBox::AcceptRole); + msgBox.setDefaultButton(ok); + if(messageBoxType == Information) + msgBox.setIcon(QMessageBox::Information); + else if(messageBoxType == Warning) + msgBox.setIcon(QMessageBox::Warning); + else if(messageBoxType == Critical) + msgBox.setIcon(QMessageBox::Critical); + msgBox.exec(); + delete ok; + return QMessageBox::Ok; + } + else if(messageBoxType == Question || messageBoxType == WarningQuestion) + { + QPushButton *yes = new QPushButton("بله"); + QPushButton *no = new QPushButton("خیر"); + msgBox.addButton(yes, QMessageBox::YesRole); + msgBox.addButton(no, QMessageBox::NoRole); + if(defaultButton == QMessageBox::Yes) + msgBox.setDefaultButton(yes); + else if(defaultButton == QMessageBox::No) + msgBox.setDefaultButton(no); + if(messageBoxType == Question) + msgBox.setIcon(QMessageBox::Question); + else if(messageBoxType == WarningQuestion) + msgBox.setIcon(QMessageBox::Warning); + int b = msgBox.exec(); + delete yes; + delete no; + if(b == 0) + return QMessageBox::Yes; + else + return QMessageBox::No; + } + else if(messageBoxType == WarningQuestionToAll) + { + QPushButton *yesToAll = new QPushButton("بله همه"); + QPushButton *noToAll = new QPushButton("خیر"); + QPushButton *abort = new QPushButton("لغو"); + msgBox.addButton(yesToAll, QMessageBox::YesRole); + msgBox.addButton(noToAll, QMessageBox::NoRole); + msgBox.addButton(abort, QMessageBox::RejectRole); + if(defaultButton == QMessageBox::YesToAll) + msgBox.setDefaultButton(yesToAll); + else if(defaultButton == QMessageBox::NoToAll) + msgBox.setDefaultButton(noToAll); + else if(defaultButton == QMessageBox::Abort) + msgBox.setDefaultButton(abort); + msgBox.setIcon(QMessageBox::Warning); + int b = msgBox.exec(); + delete yesToAll; + delete noToAll; + delete abort; + if(b == 0) + return QMessageBox::YesToAll; + else if(b == 1) + return QMessageBox::NoToAll; + else + return QMessageBox::Abort; + } + + return QMessageBox::NoButton; +} + +QString byteToHuman(qint64 size) +{ + int base = 1024; + + if(size < base) + return QString::number(size) + " بایت"; + else if(size < pow(base, 2)) + return QString::number(size / base) + " کیلوبایت"; + else if(size < pow(base, 3)) + return QString::number((float)size / pow(base, 2), 'f', 2) + " مگابایت"; + else if(size < pow(base, 4)) + return QString::number((float)size / pow(base, 3), 'f', 2) + " گیگابایت"; + else if(size < pow(base, 5)) + return QString::number((float)size / pow(base, 4), 'f', 2) + " ترابایت"; + else if(size < pow(base, 6)) + return QString::number((float)size / pow(base, 5), 'f', 2) + " پتابایت"; + + return QString::number((float)size / pow(base, 6), 'f', 2) + " اگزابایت"; +} + +QString ratioFontSize(double size, double ratio) +{ + return QString::number(size * ratio, 'f', 2); +} + +QString appStyleSheet(const QString &appFN, const QString &appFS, const QString &listFN, const QString &listFS, const QString &viewFN, const QString &viewFS) +{ + QString str, appFNFD(appFN); + if(appFN == "Sahel") + appFNFD += " FD"; + + str = "*[accessibleName=classView],*[accessibleName=classViewListHeader]{font-family:" + viewFN + ";font-size:" + viewFS + "pt;}"; + str += "*[accessibleName=class2],QMessageBox,QPushButton,QToolButton,QMenuBar,QMenu{font-family:" + appFN + ";font-size:" + appFS + "pt;}"; + str += "*[accessibleName=class1]{font-family:" + listFN + ";font-size:" + listFS + "pt;}"; + str += "*[accessibleName=classFD],QTabBar,QHeaderView{font-family:'" + appFNFD + "';font-size:" + appFS + "pt;}"; + str += "*[accessibleName=classFDs]{font-family:'" + appFNFD + "';font-size:" + ratioFontSize(appFS.toDouble(), 0.95) + "pt;}"; + str += "*[accessibleName=classFinish]{font-family:" + appFN + ";font-size:" + ratioFontSize(appFS.toDouble(), 1.45) + "pt;font-weight:bold;}"; + + return str; +} + +bool dbExtCheck(const QString &filePath) +{ + QString file_path = filePath.toLower(); + if(file_path.endsWith(".gdb") || + file_path.endsWith(".s3db") || + file_path.endsWith(".db") || + file_path.endsWith(".sqlite") || + file_path.endsWith(".sqlite3")) + return true; + + return false; +} + +bool removeTempDir(const QString &dirName) +{ + QDir qDir(QDir::tempPath() + "/" + dirName); + return qDir.removeRecursively(); +} + +QString rosybitDir() +{ + QString str; +#ifdef Q_OS_WIN + str = QDir::fromNativeSeparators(qgetenv("APPDATA")) + "/" + Constants::Rosybit; +#else + str = QDir::fromNativeSeparators(qgetenv("HOME")) + "/.config/" + Constants::Rosybit.toLower(); +#endif + return str; +} + +QString appNameOS() +{ + QString appName; +#ifdef Q_OS_WIN + appName = Constants::AppName; +#else + appName = Constants::AppName.toLower(); +#endif + return appName; +} + +QString defaultDBPath() +{ + QStringList dbPath; + + // qDebug().noquote() << QProcessEnvironment::systemEnvironment().value(QStringLiteral("APPIMAGE")); // AppImage Path + // qDebug().noquote() << qgetenv("APPIMAGE"); // AppImage Path + + // dbPath << QCoreApplication::applicationDirPath() + "/" + Constants::DefaultDBName; // This is not work if you are inside an AppImage package. + dbPath << QDir::currentPath() + "/" + Constants::DefaultDBName; +#ifdef Q_OS_WIN + dbPath << rosybitDir() + "/" + Constants::AppName + "/" + Constants::DefaultDBName; +#endif + dbPath << QDir::homePath() + "/" + Constants::AppName + "/" + Constants::DefaultDBName; + dbPath << QDir::homePath() + "/" + Constants::DefaultDBName; +#ifdef Q_OS_WIN + dbPath << QDir::fromNativeSeparators(qgetenv("LOCALAPPDATA")) + "/ganjoor/" + Constants::DefaultDBName; +#endif + + for(int i = 0; i < dbPath.count(); i++) + if(QFile::exists(dbPath[i]) && isStdGanjoorDB(dbPath[i])) + return dbPath[i]; + return QString(); +} + +void showFileInDir(const QString &filePath) +{ +#if defined Q_OS_WIN + QProcess::startDetached("explorer.exe", {"/select,", QDir::toNativeSeparators(filePath)}); +#elif defined Q_OS_MACOS + QProcess::execute("/usr/bin/osascript", {"-e", "tell application \"Finder\" to reveal POSIX file \"" + filePath + "\""}); + QProcess::execute("/usr/bin/osascript", {"-e", "tell application \"Finder\" to activate"}); +#else + QDesktopServices::openUrl(QUrl(QFileInfo(filePath).path())); +#endif +} + +QString gregorianToPersian(int day, int month, int year, const QString &delimiter, bool dd, bool mm) +{ + int _d = day, _m = month, _y = year; + gregorian_persian(&_d, &_m, &_y); + + QString d = QString::number(_d); + QString m = QString::number(_m); + + if(dd && _d < 10) + d = "0" + d; + if(mm && _m < 10) + m = "0" + m; + + return QString("%1%2%3%4%5").arg(_y).arg(delimiter).arg(m).arg(delimiter).arg(d); +} + +QString nowDate(const QString &delimiter, bool dd, bool mm) +{ + QDate date(QDate::currentDate()); + return gregorianToPersian(date.day(), date.month(), date.year(), delimiter, dd, mm); +} + +QString nowTime(const QString &delimiter) +{ + return QTime::currentTime().toString(QString("HH%1mm%1ss").arg(delimiter)); +} + +QString correctHtmlTableText(const QString &text) +{ + QString str(text); + +// QRegExp regex("([^\\n]*)\\n\u200c\u200c\u200c\u200c\u200c\\n([^\\n]*)"); +// int pos = 0; +// while((pos = regex.indexIn(str, pos)) != -1) +// str.replace(pos, regex.cap(0).size(), regex.cap(2) + "\n" + regex.cap(1) + "\n"); +// str.replace(QRegExp("\\n{3,}"), "\n\n"); +// str = str.trimmed(); + + QRegularExpression regex("([^\\n]*)\\n\u200c\u200c\u200c\u200c\u200c\\n([^\\n]*)"); + QRegularExpressionMatch match = regex.match(str); + while(match.hasMatch()) + { + str.replace(match.capturedStart(0), match.capturedLength(0), match.captured(2) + "\n" + match.captured(1) + "\n"); + match = regex.match(str); + } + str.replace(QRegularExpression("\\n{3,}"), "\n\n"); + str = str.trimmed(); + + return str; +} + +QString persianNumber(int n) +{ + QString number(QString::number(n)); + number.replace("0", "۰"); + number.replace("1", "۱"); + number.replace("2", "۲"); + number.replace("3", "۳"); + number.replace("4", "۴"); + number.replace("5", "۵"); + number.replace("6", "۶"); + number.replace("7", "۷"); + number.replace("8", "۸"); + number.replace("9", "۹"); + return number; +} + +bool idComp(const QString &id1, const QString &id2) +{ + return id1.toInt() < id2.toInt(); +} + +bool faLessThan(const QString &str1, const QString &str2) +{ + return str1 < str2; +} + +QString faReplaceChars(const QString &text) +{ + QString str(text); + + str.replace("ک", "ك"); + str.replace("ی", "ي"); + + str.replace("پ", "بييييي"); + str.replace("چ", "جييييي"); + str.replace("ژ", "زييييي"); + str.replace("گ", "كييييي"); + + str.replace("و", "_*v*_"); + str.replace("ه", "و"); + str.replace("_*v*_", "ه"); + + return str; +} diff --git a/src/common_functions.h b/src/common_functions.h new file mode 100644 index 0000000..3a85737 --- /dev/null +++ b/src/common_functions.h @@ -0,0 +1,406 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef COMMON_FUNCTIONS_H +#define COMMON_FUNCTIONS_H + +#include "date_converter.h" +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#if QT_VERSION < 0x060000 +#include +#endif +#include +#include +#include +#include + +#include +#include + +#include +#include + +// A preprocessor variable to support both Qt5 and Qt6 +#if QT_VERSION >= 0x060000 +#define SKIP_EMPTY_PARTS Qt::SkipEmptyParts +#else +#define SKIP_EMPTY_PARTS QString::SkipEmptyParts +#endif + +/* +QT_VERSION: +This macro expands a numeric value of the +form 0xMMNNPP (MM = major, NN = minor, PP = patch) that +specifies Qt's version number. For example, +if you compile your application against Qt 4.1.2, +the QT_VERSION macro will expand to 0x040102. +Qt 4.1.2 = 0x040102 +Qt 5.10.0 = 0x050A00 +Qt 5.15.2 = 0x050F02 +*/ + +struct Constants +{ + static const QString Rosybit; + static const QString RosybitFa; + static const QString RosybitUrl; + static const QString Programmer; + static const QString ProgrammerFa; + static const QString Email; + static const QString AppName; + static const QString AppNameFa; + static const QString AppVersion; + static const QString GitHub; + static const QString AppUrl; + static const QString DefaultDBName; + static const QString SettingsFileName; + static const QString HistoryFileName; + + static const QChar ZWNJ; + static const QString DIACRITICS; + static const QString A_PERSIAN; + static const QString E_PERSIAN; + static const QString K_PERSIAN; + static const QString V_PERSIAN; + static const QString H_PERSIAN; + static const QString A_TYPES; + static const QString E_TYPES; + static const QString K_TYPES; + static const QString V_TYPES; + static const QString H_TYPES; + + static const QRegularExpression ZWNJ_REGEX; + static const QRegularExpression DIACRITICS_REGEX; + static const QRegularExpression A_TYPES_REGEX; + static const QRegularExpression E_TYPES_REGEX; + static const QRegularExpression K_TYPES_REGEX; + static const QRegularExpression V_TYPES_REGEX; + static const QRegularExpression H_TYPES_REGEX; + static const QRegularExpression A_REGEX; + static const QRegularExpression E_REGEX; + static const QRegularExpression K_REGEX; + static const QRegularExpression V_REGEX; + static const QRegularExpression H_REGEX; +}; + +enum DatabaseType +{ + MainDatabase, + BookmarkDatabase +}; + +enum MessageBoxType +{ + Information, + Warning, + Critical, + Question, + WarningQuestion, + WarningQuestionToAll +}; + +enum PoemDisplayType +{ + Joft, + Tak +}; + +enum TableDisplayType +{ + AllItems, + PreInstalledItems, + NotInstalledItems +}; + +enum SearchTable +{ + VerseTable, + PoemTable, + CatTable +}; + +struct SearchHistory +{ + QString date; + QString time; + QString table; + bool allItemsSelected; + bool skipDiacritics; + bool skipCharTypes; + QStringList poetID; + QString searchPhrase; + int count; +}; + +struct SearchWord +{ + QStringList orderExact; + QStringList order; + QStringList negExact; + QStringList neg; + QStringList plusExact; + QStringList plus; +}; + +struct SearchWordLike +{ + QString orderAllLike; + QString plusAllLike; +}; + +struct SearchSetting +{ + QStringList poetID; + bool allItemsSelected; + bool skipDiacritics; + bool skipCharTypes; + QString searchPhrase; + SearchTable table; + bool searchState; + bool isSearching; +}; + +struct StartupSettings +{ + QList poetSplitterSize; + bool isMaximized; + QSize mainWindowSize; + QPoint mainWindowPos; +}; + +struct AppSettings +{ + QString mainDBPath; + QSqlDatabase mainDB; + QStringList otherDBsPath; + QListWidget *listWidget; + QTabWidget *tabWidget; + QWidget *activeTab; + QMap tabLastLevelID; + QMap tabCurrentPoem; + QString appFN; + QString appFS; + QString listFN; + QString listFS; + QString viewFN; + QString viewFS; + QString viewFSCurrent; + PoemDisplayType pDisplayType; + SearchSetting ss; + int hemistichDistance; + int hemistichDistanceMin; + int hemistichDistanceMax; + bool isDarkMode; + bool showBookmarks; + bool isOpenWordSearchForm; + bool isOpenAbjadForm; + bool isOpenAbjadFormMini; +}; + +struct GanjoorPath +{ + QStringList level; + QStringList text; + QStringList id; +}; + +struct XmlPoet +{ + QString CatName; + QString PoetID; + QString CatID; + QString DownloadUrl; + QString FileExt; + QString ImageUrl; + QString FileSizeInByte; + QString LowestPoemID; + QString PubDate; +}; + +class SqliteDB +{ +public: + SqliteDB() {;} + SqliteDB(const QString &databasePath, const QString &connectionName, bool isMainDB = false) + { + database_path = databasePath; + if(isMainDB) + database = QSqlDatabase::addDatabase("QSQLITE"); + else + database = QSqlDatabase::addDatabase("QSQLITE", connectionName); + database.setDatabaseName(databasePath); + database.open(); + } + + void setDatabase(const QString &databasePath, const QString &connectionName, bool isMainDB = false) + { + remove(); + database_path = databasePath; + if(isMainDB) + database = QSqlDatabase::addDatabase("QSQLITE"); + else + database = QSqlDatabase::addDatabase("QSQLITE", connectionName); + database.setDatabaseName(databasePath); + database.open(); + } + + void remove() + { + if(database.isOpen()) + { + database_path.clear(); + QString connection; + connection = database.connectionName(); + database.close(); + database = QSqlDatabase(); + database.removeDatabase(connection); + } + } + + QString DBPath() {return database_path;} + QSqlDatabase &DB() {return database;} + +private: + QString database_path; + QSqlDatabase database; +}; + +class TableValues +{ +private: + QString values; + +public: + TableValues() {;} + TableValues(QString value) {values = value + ",";} + + inline void addValue(QString value) {values += value + ",";} + inline QString getValues() {return values.left(values.size() - 1);} + inline void clear() {values.clear();} +}; + +bool isStdGanjoorDB(const QSqlDatabase &database, DatabaseType databaseType = MainDatabase); +bool isStdGanjoorDB(const QString &database, DatabaseType databaseType = MainDatabase); +void lineEditDirectionCorrector(QLineEdit *lineEdit = nullptr, Qt::LayoutDirection direction = Qt::RightToLeft); +void listWidgetPoetList(QListWidget *listWidget, const QSqlDatabase &database, bool checkable = false, const QString &strQuery = "SELECT name, id, cat_id FROM poet"); +bool listWidgetItemList(QListWidget *listWidget, const QSqlDatabase &database, const QString &id); +bool importDatabase(QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase, bool removePreVersion = false, int speed = 1000); +bool importDatabase(QSqlDatabase &mainDatabase, const QString &secondDatabase, bool removePreVersion = false, int speed = 1000); +bool importDatabaseByIDs(QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase, const QStringList &poetIDs, int speed = 1000); +bool exportDatabase(const QSqlDatabase &mainDatabase, QSqlDatabase &newDatabase, const QStringList &poetIDs, int speed = 1000, bool createNewTable = true); +bool removePoet(QSqlDatabase &database, const QStringList &poetIDs); +bool createGanjoorTable(QSqlDatabase &database); +bool createGanjoorTable(const QString &database); +QString getPoetNameByPoetID(const QSqlDatabase &database, const QString &id); +QString getPoetIDByCatID(const QSqlDatabase &database, const QString &id); +QString getPositionByPoemIDVorder(const QSqlDatabase &database, const QString &id, const QString &vorder); +QStringList getPoetsIDs(const QSqlDatabase &database); +bool existsCommonPoet(const QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase); +bool existsCommonPoet(const QSqlDatabase &mainDatabase, const QStringList &poetIDs); +QStringList commonPoetsID(const QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase); +QStringList uncommonPoetsID(const QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase); +QString listWidgetAddTitle(const QSqlDatabase &database, const QString &text, const QString &poemID, int spacePermittedNumber); +GanjoorPath recursiveIDs(const QSqlDatabase &database, const QString &level, const QString &id); +GanjoorPath recursiveIDs(const QSqlDatabase &database, const QString &levelID); +QString idTitle(const QSqlDatabase &database, const QString &level, const QString &id); +QString idTitle(const QSqlDatabase &database, const QString &levelID); +QString spaceReplace(const QString &text, const QString &replaceWith, int permittedNumber); +QList xmlPoetListElements(const QDomElement &root, const QString &tagName); +void tableWidgetDownloadList(QTableWidget *tableWidget, const QSqlDatabase &mainDatabase, const QList &list, QList &preInstalled, QList ¬Installed, bool isDarkMode = false, TableDisplayType tableDisplayType = AllItems); +void dbCloseRemove(QSqlDatabase *database); +void dbCloseRemove(QSqlDatabase &database); +QString oldStyleHtml(const QSqlDatabase &database, const QString &poemID, const QString &fontSize, bool isDarkMode = false, const QStringList &highlightText = QStringList(), bool showAllBookmarks = true, const QString &bookmarkVerseID = QString()); +QString newStyleHtml(const QSqlDatabase &database, const QString &poemID, const QString &fontSize, bool isDarkMode = false, const QStringList &highlightText = QStringList(), bool showAllBookmarks = true, const QString &bookmarkVerseID = QString(), int hemistichDistance = 60); +inline void htmlEntitiesAndNewLine(QString &str); +inline QString openTable(bool &isTableOpen); +inline QString closeTable(bool &isTableOpen); +inline QString lBreakAdder(bool preBreak); +inline void bookmarkHighlighter(QString &str); +void searchHighlighter(QString &text, const QStringList &list, const QString &cssClass); +QString previousPoem(const QSqlDatabase &database, const QString &level, const QString &id); +QString previousPoem(const QSqlDatabase &database, const QString &levelID); +QString nextPoem(const QSqlDatabase &database, const QString &level, const QString &id); +QString nextPoem(const QSqlDatabase &database, const QString &levelID); +bool isBookmarked(const QSqlDatabase &database, const QString &level, const QString &id, const QString &verse_id); +bool isBookmarked(const QSqlDatabase &database, const QString &levelID, const QString &verse_id); +void setBookmarked(const QSqlDatabase &database, const QString &level, const QString &id, const QString &verse_id, bool value); +void setBookmarked(const QSqlDatabase &database, const QString &levelID, const QString &verse_id, bool value); +bool importBookmarks(QSqlDatabase &mainDatabase, const QSqlDatabase &secondDatabase, int speed = 50000); +bool importBookmarks(QSqlDatabase &mainDatabase, const QString &secondDatabase, int speed = 50000); +bool exportBookmarks(const QSqlDatabase &mainDatabase, QSqlDatabase &newDatabase, int speed = 50000); +QString randString(int len = 16); +QString createDBDialog(QWidget *parent = nullptr, const QString &defaultFilePath = QDir::homePath() + "/" + Constants::DefaultDBName); +QString writableDirDialog(QWidget *parent = nullptr, const QString &defaultDirPath = QDir::homePath()); +QMessageBox::StandardButton messageBox(const QString &title, const QString &text, MessageBoxType messageBoxType, QWidget *parent = nullptr, QMessageBox::StandardButton defaultButton = QMessageBox::No); +QString byteToHuman(qint64 size); +QString ratioFontSize(double size, double ratio = 1); +QString appStyleSheet(const QString &appFN = "Sahel", const QString &appFS = "10.5", const QString &listFN = "Sahel", const QString &listFS = "11", const QString &viewFN = "Sahel", const QString &viewFS = "11"); +bool dbExtCheck(const QString &filePath); +bool removeTempDir(const QString &dirName); +QString rosybitDir(); +QString appNameOS(); +QString defaultDBPath(); +void showFileInDir(const QString &filePath); +QString gregorianToPersian(int day, int month, int year, const QString &delimiter = "/", bool dd = true, bool mm = true); +QString nowDate(const QString &delimiter = "/", bool dd = true, bool mm = true); +QString nowTime(const QString &delimiter = ":"); +QString correctHtmlTableText(const QString &text); +QString persianNumber(int n); +bool idComp(const QString &id1, const QString &id2); +bool faLessThan(const QString &str1, const QString &str2); +QString faReplaceChars(const QString &text); + +// COMMON_SEARCH +QString searchTableWidget(AppSettings *appSettings, QTableWidget *tableWidget, const QString &strQuery); +bool patternMatched(const QList &swList, const QString &text); +int wordCount(const QString &word, const QString &text); +SearchWordLike searchWordLike(const SearchWord &sw, const QString &fieldStr); +QString hashSignFinder(const QString &text); +SearchWord searchWordAnalyser(const QString &orPart); +QString searchStrQuery(const QSqlDatabase &database, const QString &userStr, bool allItemsSelected = true, const QStringList &poetID = QStringList(), SearchTable searchTable = VerseTable, bool sDiacritics = false, bool sCharTypes = false); +QString searchRange(const QSqlDatabase &database, const QStringList &poetID = QStringList(), SearchTable searchTable = VerseTable); +bool findActiveWord(const SearchWord &sw); +QString wordLikeRevision(const QString &text); +QString skipZWNJ(const QString &text); +QString skipDiacritics(const QString &text); +QString skipCharTypes(const QString &text); +QString removeZWNJ(const QString &text); +QString removeDiacritics(const QString &text); +QString removeCharTypes(const QString &text); +QString replace_AEKVH_withUnderscore(const QString &text); +QStringList textListHighlight(const QString &searchPhrase); +QString quotationRemover(const QString &text); +// COMMON_SEARCH + +#endif // COMMON_FUNCTIONS_H diff --git a/src/common_search.cpp b/src/common_search.cpp new file mode 100644 index 0000000..f8d9946 --- /dev/null +++ b/src/common_search.cpp @@ -0,0 +1,771 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "common_functions.h" + +// ATTENTION: MAX NESTED REPLACE OF SQL QUERY = 29 + +const QChar Constants::ZWNJ = QChar(0x200C); +const QRegularExpression Constants::ZWNJ_REGEX = QRegularExpression(QString("[%1]").arg(Constants::ZWNJ)); + +// A << E << O << SOKUN << AN << EN << ON << TASHDID << HAMZE << ALEF_KHANJARI << KESHIDE +const QString Constants::DIACRITICS = "\u064E\u0650\u064F\u0652\u064B\u064D\u064C\u0651\u0654\u0670\u0640"; +const QRegularExpression Constants::DIACRITICS_REGEX = QRegularExpression(QString("[%1]").arg(Constants::DIACRITICS)); + +const QString Constants::A_PERSIAN = "\u0627"; +const QString Constants::E_PERSIAN = "\u06CC"; +const QString Constants::K_PERSIAN = "\u06A9"; +const QString Constants::V_PERSIAN = "\u0648"; +const QString Constants::H_PERSIAN = "\u0647"; + +const QString Constants::A_TYPES = "\u0622\u0623\u0625"; +const QString Constants::E_TYPES = "\u064A\u0626\u0649"; +const QString Constants::K_TYPES = "\u0643"; +const QString Constants::V_TYPES = "\u0624"; +const QString Constants::H_TYPES = "\u0629\u06C0"; + +const QRegularExpression Constants::A_TYPES_REGEX = QRegularExpression(QString("[%1]").arg(Constants::A_TYPES)); +const QRegularExpression Constants::E_TYPES_REGEX = QRegularExpression(QString("[%1]").arg(Constants::E_TYPES)); +const QRegularExpression Constants::K_TYPES_REGEX = QRegularExpression(QString("[%1]").arg(Constants::K_TYPES)); +const QRegularExpression Constants::V_TYPES_REGEX = QRegularExpression(QString("[%1]").arg(Constants::V_TYPES)); +const QRegularExpression Constants::H_TYPES_REGEX = QRegularExpression(QString("[%1]").arg(Constants::H_TYPES)); + +const QRegularExpression Constants::A_REGEX = QRegularExpression(QString("[%1]").arg(Constants::A_TYPES + Constants::A_PERSIAN)); +const QRegularExpression Constants::E_REGEX = QRegularExpression(QString("[%1]").arg(Constants::E_TYPES + Constants::E_PERSIAN)); +const QRegularExpression Constants::K_REGEX = QRegularExpression(QString("[%1]").arg(Constants::K_TYPES + Constants::K_PERSIAN)); +const QRegularExpression Constants::V_REGEX = QRegularExpression(QString("[%1]").arg(Constants::V_TYPES + Constants::V_PERSIAN)); +const QRegularExpression Constants::H_REGEX = QRegularExpression(QString("[%1]").arg(Constants::H_TYPES + Constants::H_PERSIAN)); + +QString searchTableWidget(AppSettings *appSettings, QTableWidget *tableWidget, const QString &strQuery) +{ + appSettings->ss.searchState = true; + + const QSqlDatabase database = appSettings->mainDB; + const QString userStr = appSettings->ss.searchPhrase; + const SearchTable searchTable = appSettings->ss.table; + bool sDiacritics = appSettings->ss.skipDiacritics; + bool sCharTypes = appSettings->ss.skipCharTypes; + + tableWidget->model()->removeRows(0, tableWidget->model()->rowCount()); + tableWidget->model()->removeColumns(0, tableWidget->model()->columnCount()); + + QString searchPhrase(userStr); + QString level; + QStringList colList; + QSqlQuery query(database); + query.exec(strQuery); + + searchPhrase = removeZWNJ(searchPhrase); + if(sDiacritics) + searchPhrase = removeDiacritics(searchPhrase); + if(sCharTypes) + searchPhrase = removeCharTypes(searchPhrase); + + QList swList; + QString hashWord(hashSignFinder(searchPhrase)); + if(hashWord.isEmpty()) + { + QStringList listOr = searchPhrase.split("|"); + for(int i = 0; i < listOr.count(); i++) + { + SearchWord sw = searchWordAnalyser(listOr[i]); + swList.append(sw); + } + } + + tableWidget->setColumnCount(2); + tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + + if(searchTable == VerseTable) + { + colList << "عنوان" << "متن"; + level = "3"; + } + else if(searchTable == PoemTable) + { + colList << "نام شاعر یا نویسنده" << "عنوان"; + level = "3"; + } + else if(searchTable == CatTable) + { + colList << "نام شاعر یا نویسنده" << "فهرست"; + level = "2"; + } + + tableWidget->setHorizontalHeaderLabels(colList); + + int count = 0; + int row_count = 0; + while(appSettings->ss.searchState && query.next()) + { + { // Filtering Block + QString text = query.value(1).toString(); + if(sDiacritics) + text = removeDiacritics(text); + if(sCharTypes) + text = removeCharTypes(text); + + if(hashWord.isEmpty()) + { + if(!patternMatched(swList, text)) + continue; + } + else + { + int n = wordCount(hashWord, text); + count += n; + if(n < 2) + continue; + } + } // Filtering Block + + tableWidget->insertRow(row_count); + + QTableWidgetItem *item1 = new QTableWidgetItem; + QTableWidgetItem *item2 = new QTableWidgetItem; + QString id = query.value(0).toString(); + GanjoorPath gp = recursiveIDs(database, level, id); + int iLast = gp.text.count() - 1; + QString str = gp.text[iLast] + ": " + gp.text[0]; + + if(searchTable == VerseTable) + { + item1->setText(spaceReplace(str, "…", 6)); + item2->setText(query.value(1).toString()); + } + else if(searchTable == PoemTable) + { + item1->setText(gp.text[iLast]); + item2->setText(query.value(1).toString()); + } + else if(searchTable == CatTable) + { + item1->setText(gp.text[iLast]); + if(iLast > 1) + { + QString preCat; + for(int i = iLast - 1; i > 0; i--) + { + if(preCat.isEmpty()) + preCat = gp.text[i]; + else + preCat += " | " + gp.text[i]; + } + item2->setText(QString("%1 (%2)").arg(query.value(1).toString(), preCat)); + } + else + item2->setText(query.value(1).toString()); + } + + item1->setData(Qt::UserRole, gp.text[iLast]); + item2->setData(Qt::UserRole, level + "-" + id); + + tableWidget->setItem(row_count, 0, item1); + tableWidget->setItem(row_count, 1, item2); + + row_count++; + } + + appSettings->ss.searchState = false; + if(!hashWord.isEmpty()) + return QString("تعداد کل کلمه (عبارت): %1
برابر است با: %2
کلمه‌هایی (عبارت‌هایی) که بیش از یک بار (دو یا بیشتر) در یک رکورد وجود دارد، در جدول قرار گرفت.").arg(hashWord, persianNumber(count)); + return QString(); +} + +bool patternMatched(const QList &swList, const QString &text) +{ + QString str(removeZWNJ(text)); + QString strRegex; + bool continueFlag; + + for(int i = 0; i < swList.count(); i++) + { + continueFlag = false; + + if(swList[i].orderExact.count()) + { + for(int j = 0; j < swList[i].orderExact.count(); j++) + { + if(j) + strRegex += QString(".*\\b%1\\b").arg(swList[i].orderExact[j]); + else + strRegex = QString("\\b%1\\b").arg(swList[i].orderExact[j]); + } + QRegularExpression regex(strRegex, QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + if(!str.contains(regex)) + continue; + } + + if(swList[i].order.count()) + { + for(int j = 0; j < swList[i].order.count(); j++) + { + if(j) + strRegex += QString(".*%1").arg(swList[i].order[j]); + else + strRegex = QString("%1").arg(swList[i].order[j]); + } + QRegularExpression regex(strRegex, QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + if(!str.contains(regex)) + continue; + } + + if(swList[i].plusExact.count()) + { + for(int j = 0; j < swList[i].plusExact.count(); j++) + { + QRegularExpression regex(QString("\\b%1\\b").arg(swList[i].plusExact[j]), QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + if(!str.contains(regex) && !text.contains(regex)) + { + continueFlag = true; + break; + } + } + if(continueFlag) + continue; + } + + if(swList[i].plus.count()) + { + for(int j = 0; j < swList[i].plus.count(); j++) + { + QRegularExpression regex(QString("%1").arg(swList[i].plus[j]), QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + if(!str.contains(regex)) + { + continueFlag = true; + break; + } + } + if(continueFlag) + continue; + } + + if(swList[i].negExact.count()) + { + for(int j = 0; j < swList[i].negExact.count(); j++) + { + QRegularExpression regex(QString("\\b%1\\b").arg(swList[i].negExact[j]), QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + if(str.contains(regex)) + { + continueFlag = true; + break; + } + } + if(continueFlag) + continue; + } + + if(swList[i].neg.count()) + { + for(int j = 0; j < swList[i].neg.count(); j++) + { + QRegularExpression regex(QString("%1").arg(swList[i].neg[j]), QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + if(str.contains(regex)) + { + continueFlag = true; + break; + } + } + if(continueFlag) + continue; + } + + return true; + } + + return false; +} + +int wordCount(const QString &word, const QString &text) +{ + QString wordPure(word); + QString str(removeZWNJ(text)); + bool exact = false; + int count = 0; + + QRegularExpressionMatch match; + QRegularExpressionMatchIterator i, j; + + if(wordPure.startsWith("\"") && wordPure.endsWith("\"")) + { + exact = true; + wordPure.remove(0, 1); + wordPure.remove(wordPure.size() - 1, 1); + if(wordPure.isEmpty()) + return 0; + } + + if(exact) + { + QRegularExpression regex(QString("\\b%1\\b").arg(wordPure), QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + i = regex.globalMatch(str); + j = regex.globalMatch(text); + while(i.hasNext() || j.hasNext()) + { + count++; + if(i.hasNext()) + i.next(); + if(j.hasNext()) + j.next(); + } + } + else + { + QRegularExpression regex(QString("%1").arg(wordPure), QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + i = regex.globalMatch(str); + j = regex.globalMatch(text); + while(i.hasNext() || j.hasNext()) + { + count++; + if(i.hasNext()) + i.next(); + if(j.hasNext()) + j.next(); + } + } + + return count; +} + +SearchWordLike searchWordLike(const SearchWord &sw, const QString &fieldStr) +{ + // QString strQuery = QString("SELECT poem_id, text FROM verse WHERE text LIKE '%%1%' ORDER BY poem_id").arg(word); + // QString strQuery = QString("SELECT poem_id, text FROM verse WHERE text REGEXP '.*%1.*' ORDER BY poem_id").arg(word); // Qt v5.10+: db.setConnectOptions("QSQLITE_ENABLE_REGEXP"); // Before open db + + QString word; + QStringList orderAll, plusAll; + orderAll << sw.orderExact << sw.order; + plusAll << sw.plusExact << sw.plus; + + QString orderAllLike; + if(orderAll.count()) + { + for(int i = 0; i < orderAll.count(); i++) + { + if((word = wordLikeRevision(orderAll[i])).isEmpty()) + continue; + if(orderAllLike.isEmpty()) + orderAllLike = QString("%1 LIKE '%%2%").arg(fieldStr, word); + else + orderAllLike += QString("%1%").arg(word); + } + if(!orderAllLike.isEmpty()) + orderAllLike += "'"; + } + + QString plusAllLike; + if(plusAll.count()) + { + for(int i = 0; i < plusAll.count(); i++) + { + if((word = wordLikeRevision(plusAll[i])).isEmpty()) + continue; + if(plusAllLike.isEmpty()) + plusAllLike = QString("%1 LIKE '%%2%'").arg(fieldStr, word); + else + plusAllLike += QString(" AND %1 LIKE '%%2%'").arg(fieldStr, word); + } + } + + SearchWordLike swl; + swl.orderAllLike = orderAllLike; + swl.plusAllLike = plusAllLike; + return swl; +} + +QString hashSignFinder(const QString &text) +{ + QRegularExpression regex("#\\s*([^\\s]+.*)"); // #\s*([^\s]+.*) + QRegularExpressionMatch match = regex.match(text); + if(match.hasMatch()) + return match.captured(1).trimmed(); + return QString(); +} + +SearchWord searchWordAnalyser(const QString &orPart) +{ + SearchWord sw; + + // ******************************************************************************* // Srart + QString sPhrase(orPart); + QRegularExpression regex; + QRegularExpressionMatch match; + QRegularExpressionMatchIterator i; + int j; + // ******************************************************************************* + QStringList orderExact; + regex.setPattern("\\s*\\\"([^\\\"]*)\\\"\\s*\\+{2}\\s*\\\"([^\\\"]*)\\\""); // \s*\"([^\"]*)\"\s*\+{2}\s*\"([^\"]*)\" + match = regex.match(sPhrase); + j = 0; + while(match.hasMatch()) + { + if(j++) + orderExact << match.captured(2); + else + orderExact << match.captured(1) << match.captured(2); + match = regex.match(sPhrase, match.capturedEnd(1)); + } + + if(orderExact.count() & 1) + { + sPhrase.remove(regex); + sPhrase.remove(QRegularExpression("\\+{2}\\s*\\\"([^\\\"]*)\\\"")); + sPhrase.replace("++", ""); + } + else + { + sPhrase.remove(regex); + if(orderExact.count()) + sPhrase.replace("++", ""); + } + sPhrase = sPhrase.trimmed(); + // ******************************************************************************* + QStringList order; + regex.setPattern("\\s*([^\\s\\+\\-]*)\\s*\\+{2}\\s*([^\\s\\+\\-]*)"); // \s*([^\s\+\-]*)\s*\+{2}\s*([^\s\+\-]*) + match = regex.match(sPhrase); + j = 0; + while(match.hasMatch()) + { + if(j++) + order << match.captured(2); + else + order << match.captured(1) << match.captured(2); + match = regex.match(sPhrase, match.capturedEnd(2)); + } + sPhrase.remove(regex); + sPhrase = sPhrase.trimmed(); + // ******************************************************************************* + QStringList negExact; + regex.setPattern("[\\-]\\s*\\\"([^\\\"]+)\\\""); // [\-]\s*\"([^\"]+)\" + i = regex.globalMatch(sPhrase); + while(i.hasNext()) + negExact << i.next().captured(1); + sPhrase.remove(regex); + sPhrase = sPhrase.trimmed(); + // ******************************************************************************* + QStringList neg; + regex.setPattern("[\\-]\\s*([^\\s\\-]+)"); // [\-]\s*([^\s\-]+) + i = regex.globalMatch(sPhrase); + while(i.hasNext()) + neg << i.next().captured(1); + sPhrase.remove(regex); + sPhrase = sPhrase.trimmed(); + // ******************************************************************************* + QStringList plusExact; + regex.setPattern("[\\+]?\\s*\\\"([^\\\"]+)\\\""); // [\+]?\s*\"([^\"]+)\" + i = regex.globalMatch(sPhrase); + while(i.hasNext()) + plusExact << i.next().captured(1); + sPhrase.remove(regex); + sPhrase = sPhrase.trimmed(); + // ******************************************************************************* + QStringList plus; + regex.setPattern("[\\+]?\\s*([^\\s\\+]+)"); // [\+]?\s*([^\s\+]+) + i = regex.globalMatch(sPhrase); + while(i.hasNext()) + plus << i.next().captured(1); + sPhrase.remove(regex); + sPhrase = sPhrase.trimmed(); + // ******************************************************************************* // End + + sw.orderExact = orderExact; + sw.order = order; + sw.negExact = negExact; + sw.neg = neg; + sw.plusExact = plusExact; + sw.plus = plus; + + return sw; +} + +QString searchStrQuery(const QSqlDatabase &database, const QString &userStr, bool allItemsSelected, const QStringList &poetID, SearchTable searchTable, bool sDiacritics, bool sCharTypes) +{ + QString result; + QString preStrQuery; + QString range; + QString finalLike; + QString orderBy; + QString searchPhrase(userStr); + QStringList strOr; + QString table, fieldId, fieldName; + QString fieldStr; + bool activeWordExist = false; + + if(searchTable == VerseTable) + { + table = "verse"; + fieldId = "poem_id"; + fieldName = "text"; + orderBy = " ORDER BY poem_id"; + } + else if(searchTable == PoemTable) + { + table = "poem"; + fieldId = "id"; + fieldName = "title"; + orderBy = " ORDER BY cat_id"; + } + else if(searchTable == CatTable) + { + table = "cat"; + fieldId = "id"; + fieldName = "text"; + orderBy = " ORDER BY poet_id"; + } + fieldStr = fieldName; + + if(sDiacritics) + { + searchPhrase = removeDiacritics(searchPhrase); + searchPhrase = removeZWNJ(searchPhrase); + fieldStr = skipDiacritics(fieldStr); + fieldStr = skipZWNJ(fieldStr); + } + if(sCharTypes) + { + searchPhrase = replace_AEKVH_withUnderscore(searchPhrase); + } + + preStrQuery = QString("SELECT %1, %2 FROM %3 WHERE ").arg(fieldId, fieldName, table); + + if(!allItemsSelected && !poetID.isEmpty()) + range = searchRange(database, poetID, searchTable); + + QString hashWord(hashSignFinder(searchPhrase)); + if(!hashWord.isEmpty()) + { + hashWord = wordLikeRevision(quotationRemover(hashWord)); + if(!hashWord.isEmpty()) + result = preStrQuery + (range.isEmpty() ? "" : range + " AND ") + QString("%1 LIKE '%%2%'").arg(fieldStr, hashWord) + orderBy; + else + result = QString("SELECT %1, %2 FROM %3").arg(fieldId, fieldName, table) + (range.isEmpty() ? "" : " WHERE " + range) + orderBy; + return result; + } + + QStringList listOr = searchPhrase.split("|"); + for(int i = 0; i < listOr.count(); i++) + { + QStringList likes; + SearchWord sw = searchWordAnalyser(listOr[i]); + SearchWordLike swl = searchWordLike(sw, fieldStr); + likes << swl.orderAllLike << swl.plusAllLike; + likes.removeAll(""); + strOr << likes.join(" AND "); + if(!activeWordExist) + activeWordExist = findActiveWord(sw); + } + + strOr.removeAll(""); + if(strOr.count() == 1) + { + finalLike = strOr[0]; + } + else if(strOr.count() > 1) + { + for(int i = 0; i < strOr.count(); i++) + strOr[i] = "(" + strOr[i] + ")"; + finalLike = strOr.join(" OR "); + } + + if(!finalLike.isEmpty()) + result = preStrQuery + (range.isEmpty() ? "" : range + " AND ") + finalLike + orderBy; + + if(finalLike.isEmpty() && activeWordExist) + { + if(range.isEmpty()) + result = QString("SELECT %1, %2 FROM %3%4").arg(fieldId, fieldName, table, orderBy); + else + result = QString("SELECT %1, %2 FROM %3 WHERE %4%5").arg(fieldId, fieldName, table, range, orderBy); + } + + return result; +} + +QString searchRange(const QSqlDatabase &database, const QStringList &poetID, SearchTable searchTable) +{ + QSqlQuery query(database), query2(database); + QString cIN, pIN, vIN; + + if(poetID.isEmpty()) + return QString(); + + if(searchTable == CatTable) + { + for(int i = 0; i < poetID.count(); i++) + cIN += poetID[i] + ","; + cIN = cIN.left(cIN.size() - 1); + return "poet_id IN (" + cIN + ")"; + } + + for(int i = 0; i < poetID.count(); i++) + { + QString catID; + query.exec("SELECT id FROM cat WHERE poet_id = " + poetID[i]); + while(query.next()) + { + pIN += (catID = query.value(0).toString()) + ","; + if(searchTable == PoemTable) + continue; + + query2.exec("SELECT id FROM poem WHERE cat_id = " + catID); + while(query2.next()) + vIN += query2.value(0).toString() + ","; + } + } + + if(searchTable == PoemTable) + { + pIN = pIN.left(pIN.size() - 1); + return "cat_id IN (" + pIN + ")"; + } + + if(searchTable == VerseTable) + { + vIN = vIN.left(vIN.size() - 1); + return "poem_id IN (" + vIN + ")"; + } + + return QString(); +} + +bool findActiveWord(const SearchWord &sw) +{ + if(sw.orderExact.isEmpty() && sw.order.isEmpty() && + sw.plusExact.isEmpty() && sw.plus.isEmpty()) + return false; + return true; +} + +QString wordLikeRevision(const QString &text) +{ + QString str(text); + if(!str.isEmpty()) + { + QRegularExpression regex; + QRegularExpressionMatch match; + + regex.setPattern("^([_%]+)([^_%].*)?$"); + match = regex.match(str); + if(match.hasMatch()) + str.remove(match.capturedStart(1), match.capturedLength(1)); + + regex.setPattern("^(.*[^_%])?([_%]+)$"); + match = regex.match(str); + if(match.hasMatch()) + str.remove(match.capturedStart(2), match.capturedLength(2)); + } + return str; +} + +QString skipZWNJ(const QString &text) +{ + QString str(text); + str = QString("REPLACE(%1, '%2', '')").arg(str).arg(Constants::ZWNJ); + return str; +} + +QString skipDiacritics(const QString &text) +{ + QString str(text); + for(int i = 0; i < Constants::DIACRITICS.size(); i++) + str = QString("REPLACE(%1, '%2', '')").arg(str).arg(Constants::DIACRITICS[i]); + return str; +} + +QString skipCharTypes(const QString &text) +{ + QString str(text); + for(int i = 0; i < Constants::A_TYPES.size(); i++) + str = QString("REPLACE(%1, '%2', '%3')").arg(str).arg(Constants::A_TYPES[i]).arg(Constants::A_PERSIAN); + for(int i = 0; i < Constants::E_TYPES.size(); i++) + str = QString("REPLACE(%1, '%2', '%3')").arg(str).arg(Constants::E_TYPES[i]).arg(Constants::E_PERSIAN); + for(int i = 0; i < Constants::K_TYPES.size(); i++) + str = QString("REPLACE(%1, '%2', '%3')").arg(str).arg(Constants::K_TYPES[i]).arg(Constants::K_PERSIAN); + for(int i = 0; i < Constants::V_TYPES.size(); i++) + str = QString("REPLACE(%1, '%2', '%3')").arg(str).arg(Constants::V_TYPES[i]).arg(Constants::V_PERSIAN); + for(int i = 0; i < Constants::H_TYPES.size(); i++) + str = QString("REPLACE(%1, '%2', '%3')").arg(str).arg(Constants::H_TYPES[i]).arg(Constants::H_PERSIAN); + return str; +} + +QString removeZWNJ(const QString &text) +{ + QString str(text); + str.replace(Constants::ZWNJ_REGEX, ""); + return str; +} + +QString removeDiacritics(const QString &text) +{ + QString str(text); + str.replace(Constants::DIACRITICS_REGEX, ""); + return str; +} + +QString removeCharTypes(const QString &text) +{ + QString str(text); + str.replace(Constants::A_TYPES_REGEX, Constants::A_PERSIAN); + str.replace(Constants::E_TYPES_REGEX, Constants::E_PERSIAN); + str.replace(Constants::K_TYPES_REGEX, Constants::K_PERSIAN); + str.replace(Constants::V_TYPES_REGEX, Constants::V_PERSIAN); + str.replace(Constants::H_TYPES_REGEX, Constants::H_PERSIAN); + return str; +} + +QString replace_AEKVH_withUnderscore(const QString &text) +{ + QString str(text); + str.replace(Constants::A_REGEX, "_"); + str.replace(Constants::E_REGEX, "_"); + str.replace(Constants::K_REGEX, "_"); + str.replace(Constants::V_REGEX, "_"); + str.replace(Constants::H_REGEX, "_"); + return str; +} + +QStringList textListHighlight(const QString &searchPhrase) +{ + QStringList result; + QString sPhrase(searchPhrase); + + QRegularExpression regex("(#)\\s*[^\\s]+.*"); // (#)\s*[^\s]+.* + QRegularExpressionMatch match = regex.match(searchPhrase); + if(match.hasMatch()) + sPhrase.remove(match.capturedStart(1), match.capturedLength(1)); + + QStringList listOr = sPhrase.split("|"); + for(int i = 0; i < listOr.count(); i++) + { + SearchWord sw = searchWordAnalyser(listOr[i]); + + for(int j = 0; j < sw.orderExact.count(); j++) + result << sw.orderExact[j]; + for(int j = 0; j < sw.order.count(); j++) + result << sw.order[j]; + for(int j = 0; j < sw.plusExact.count(); j++) + result << sw.plusExact[j]; + for(int j = 0; j < sw.plus.count(); j++) + result << sw.plus[j]; + } + + return result; +} + +QString quotationRemover(const QString &text) +{ + QString wordPure(text); + if(wordPure.startsWith("\"") && wordPure.endsWith("\"")) + { + wordPure.remove(0, 1); + wordPure.remove(wordPure.size() - 1, 1); + } + return wordPure; +} diff --git a/src/databaseform.cpp b/src/databaseform.cpp new file mode 100644 index 0000000..2f2a108 --- /dev/null +++ b/src/databaseform.cpp @@ -0,0 +1,283 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "databaseform.h" +#include "ui_databaseform.h" +#include "downloadform.h" + +#include +#include + +DatabaseForm::DatabaseForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::DatabaseForm) +{ + ui->setupUi(this); +} + +DatabaseForm::DatabaseForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::DatabaseForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("مدیریت پایگاه داده"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + + ui->lineEdit->setText(QDir::toNativeSeparators(appSettings->mainDBPath)); + ui->labelProgress->hide(); + ui->progressBar->hide(); + ui->progressBar->setMaximum(0); + + listWidgetPoetList(ui->listWidget, appSettings->mainDB, true); + ui->labelTotal->setText(QString("تعداد کل: %1 مورد ").arg(ui->listWidget->count())); +} + +DatabaseForm::~DatabaseForm() +{ + delete ui; +} + +void DatabaseForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + on_btnClose_clicked(); +} + +void DatabaseForm::closeEvent(QCloseEvent *event) +{ + if(isProcessing) + { + messageBox("توجه", "نرم‌افزار در حال پردازش است. لطفا شکیبا باشید!", Warning, this); + event->ignore(); + return; + } + + QWidget::closeEvent(event); +} + +void DatabaseForm::on_btnClose_clicked() +{ + close(); +} + +void DatabaseForm::on_listWidget_doubleClicked(const QModelIndex &index) +{ + int row = index.row(); + + if(ui->listWidget->item(row)->checkState() == Qt::Unchecked) + ui->listWidget->item(row)->setCheckState(Qt::Checked); + else + ui->listWidget->item(row)->setCheckState(Qt::Unchecked); +} + +void DatabaseForm::on_listWidget_itemChanged(QListWidgetItem *item) +{ + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + + if(item->checkState() == Qt::Checked) + poetSelectedIDs << item->data(Qt::UserRole).toString(); + else + poetSelectedIDs.removeOne(item->data(Qt::UserRole).toString()); + + labelUpdate(); +} + +void DatabaseForm::on_selectAllCheckBox_clicked(bool checked) +{ + ui->selectNoneCheckBox->setChecked(false); + + if(checked) + { + for(int i = 0; i < ui->listWidget->count(); i++) + ui->listWidget->item(i)->setCheckState(Qt::Checked); + ui->selectAllCheckBox->setChecked(true); + } + else + for(int i = 0; i < ui->listWidget->count(); i++) + ui->listWidget->item(i)->setCheckState(Qt::Unchecked); +} + +void DatabaseForm::on_selectNoneCheckBox_clicked(bool checked) +{ + Q_UNUSED(checked); // (void)checked; + + ui->selectAllCheckBox->setChecked(false); + + for(int i = 0; i < ui->listWidget->count(); i++) + ui->listWidget->item(i)->setCheckState(Qt::Unchecked); + ui->selectNoneCheckBox->setChecked(true); +} + +void DatabaseForm::labelUpdate() +{ + ui->labelSelectedCount->setText(QString("انتخاب‌شده: %1 مورد ").arg(poetSelectedIDs.count())); + ui->labelTotal->setText(QString("تعداد کل: %1 مورد ").arg(ui->listWidget->count())); + if(!poetSelectedIDs.count()) + { + ui->btnExport->setEnabled(false); + ui->btnRemovePoet->setEnabled(false); + ui->labelSelectedCount->setText("انتخاب‌شده: "); + } + else + { + ui->btnExport->setEnabled(true); + ui->btnRemovePoet->setEnabled(true); + } +} + +void DatabaseForm::on_btnDownloadForm_clicked() +{ + DownloadForm *downloadForm = new DownloadForm(appSettings, this); + connect(downloadForm, &DownloadForm::sigMainDBChanged, this, &DatabaseForm::slotMainDBChanged); + connect(downloadForm, &DownloadForm::sigUpdatePoetList, this, &DatabaseForm::slotUpdatePoetList); + downloadForm->show(); +} + +void DatabaseForm::slotMainDBChanged() +{ + emit sigMainDBChanged(); // This line must be the first. Because the application database must be opened. + listWidgetPoetList(ui->listWidget, appSettings->mainDB, true); + labelUpdate(); + ui->lineEdit->setText(QDir::toNativeSeparators(appSettings->mainDBPath)); +} + +void DatabaseForm::slotUpdatePoetList() +{ + emit sigUpdatePoetList(); + listWidgetPoetList(ui->listWidget, appSettings->mainDB, true); + labelUpdate(); +} + +void DatabaseForm::on_btnAddPoet_clicked() +{ + if(appSettings->mainDBPath.isEmpty()) + { + messageBox("هشدار", "شما پایگاه دادهٔ فعالی ندارید. لطفا ابتدا یک پایگاه داده ایجاد کنید.", Warning, this); + appSettings->mainDBPath = createDBDialog(this); + if(!appSettings->mainDBPath.isEmpty()) + slotMainDBChanged(); + else + return; + } + + QString filter = "Supported files (*.gdb *.s3db *.db *.sqlite *.sqlite3 *.zip);;Database files (*.gdb *.s3db *.db *.sqlite *.sqlite3);;Compressed files (*.zip);;All files (*.*)"; + QString file_name = QFileDialog::getOpenFileName(this, "Open", QDir::homePath(), filter); + + if(!file_name.isEmpty()) + { + if(isStdGanjoorDB(file_name) || file_name.endsWith(".zip", Qt::CaseInsensitive)) + { + Worker::WorkerType workerType; + if(file_name.endsWith(".zip", Qt::CaseInsensitive)) + workerType = Worker::ImporterZip; + else + workerType = Worker::Importer; + + Worker *worker = new Worker(workerType, appSettings, file_name, true, 1000); + threadStart(worker); + } + else + messageBox("خطا", "خطا:
فایل انتخاب‌شده قالب استانداردی ندارد!", Critical, this); + } +} + +void DatabaseForm::on_btnExport_clicked() +{ + if(poetSelectedIDs.count()) + { + QString filter = "Ganjoor Database files (*.s3db);;Ganjoor Database files (*.gdb);;SQLite Database files (*.sqlite);;SQLite 3 Database files (*.sqlite3);;Database files (*.db)"; + QString db_file_name = QFileDialog::getSaveFileName(this, "Save As", QDir::homePath() + "/exportedDB_" + nowDate("-") + "_" + nowTime("") + ".s3db", filter); + if(!db_file_name.isEmpty()) + { + Worker *worker = new Worker(Worker::Exporter, appSettings, db_file_name, poetSelectedIDs, 1000); + threadStart(worker); + } + } +} + +void DatabaseForm::on_btnRemovePoet_clicked() +{ + if(poetSelectedIDs.count()) + { + int reply = messageBox("حذف؟", "آیا از حذف موارد انتخاب‌شده مطمئن هستید؟ ", WarningQuestion, this); + if(reply == QMessageBox::Yes) + { + Worker *worker = new Worker(Worker::Remover, appSettings, poetSelectedIDs); + threadStart(worker); + } + } +} + +void DatabaseForm::on_btnCompactDB_clicked() +{ + Worker *worker = new Worker(Worker::Vacuumer, appSettings); + threadStart(worker); +} + +void DatabaseForm::threadStart(Worker *worker) +{ + QThread *thread = new QThread; + worker->moveToThread(thread); + + connect(thread, &QThread::started, worker, &Worker::process); + connect(worker, &Worker::finished, this, &DatabaseForm::threadFinished); + connect(worker, &Worker::finished, thread, &QThread::quit); + connect(worker, &Worker::finished, worker, &Worker::deleteLater); + connect(thread, &QThread::finished, thread, &QThread::deleteLater); + + isProcessing = true; + setEnabled(false); + ui->labelProgress->show(); + ui->progressBar->show(); + thread->start(); +} + +void DatabaseForm::threadFinished(Worker::WorkerType type, QVariant result) +{ + isProcessing = false; + setEnabled(true); + ui->labelProgress->hide(); + ui->progressBar->hide(); + + if(type == Worker::Importer) + { + qDebug().noquote() << "Worker: Importer"; + slotUpdatePoetList(); + } + else if(type == Worker::ImporterZip) + { + qDebug().noquote() << "Worker: ImporterZip"; + slotUpdatePoetList(); + } + else if(type == Worker::Exporter) + { + qDebug().noquote() << "Worker: Exporter"; + } + else if(type == Worker::Remover) + { + qDebug().noquote() << "Worker: Remover"; + poetSelectedIDs.clear(); + slotUpdatePoetList(); + } + else if(type == Worker::Vacuumer) + { + qDebug().noquote() << "Worker: Vacuumer"; + if(result.toBool()) + messageBox("گزارش", "پایگاه داده با موفقیت فشرده شد.", Information, this); + else + messageBox("خطا", "فشرده‌سازی پایگاه داده با خطا مواجه شد!", Critical, this); + } +} diff --git a/src/databaseform.h b/src/databaseform.h new file mode 100644 index 0000000..816bdb1 --- /dev/null +++ b/src/databaseform.h @@ -0,0 +1,65 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef DATABASEFORM_H +#define DATABASEFORM_H + +#include +#include "common_functions.h" +#include "worker.h" + +namespace Ui { +class DatabaseForm; +} + +class DatabaseForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit DatabaseForm(QWidget *parent = nullptr); + DatabaseForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~DatabaseForm(); + +signals: + void sigMainDBChanged(); + void sigUpdatePoetList(); + +public slots: + void slotMainDBChanged(); + void slotUpdatePoetList(); + void labelUpdate(); + void threadStart(Worker *worker); + void threadFinished(Worker::WorkerType type, QVariant result); + +private slots: + void on_listWidget_itemChanged(QListWidgetItem *item); + void on_listWidget_doubleClicked(const QModelIndex &index); + void on_selectAllCheckBox_clicked(bool checked); + void on_selectNoneCheckBox_clicked(bool checked); + void on_btnClose_clicked(); + void on_btnAddPoet_clicked(); + void on_btnRemovePoet_clicked(); + void on_btnCompactDB_clicked(); + void on_btnDownloadForm_clicked(); + void on_btnExport_clicked(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void closeEvent(QCloseEvent *event) override; + +private: + Ui::DatabaseForm *ui; + AppSettings *appSettings; + QStringList poetSelectedIDs; + bool isProcessing = false; +}; + +#endif // DATABASEFORM_H diff --git a/src/databaseform.ui b/src/databaseform.ui new file mode 100644 index 0000000..72b2901 --- /dev/null +++ b/src/databaseform.ui @@ -0,0 +1,308 @@ + + + DatabaseForm + + + + 0 + 0 + 672 + 399 + + + + + Sahel + 11 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + + + class2 + + + مدیریت پایگاه داده + + + + + + + + + + class2 + + + انتخاب همه + + + + + + + class2 + + + هیچکدام + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Sahel + 11 + + + + class2 + + + + + + + + + + 10 + + + + classFDs + + + تعداد کل: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 10 + + + + classFDs + + + انتخاب‌شده: + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + class2 + + + اضافه + + + + + + + false + + + class2 + + + حذف + + + + + + + false + + + class2 + + + خروجی + + + + + + + class2 + + + دانلود از مخزن + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + class2 + + + فشرده‌سازی پایگاه داده + + + + + + + + + + + + + + class2 + + + لطفا منتظر بمانید… + + + Qt::AlignCenter + + + + + + + class2 + + + 0 + + + false + + + + + + + + + class2 + + + مسیر پایگاه داده: + + + + + + + class2 + + + color: rgb(255, 255, 255); +background-color: rgb(21, 21, 21); + + + databasePath + + + false + + + true + + + + + + + class2 + + + بستن + + + + + + + + + + + + + diff --git a/src/date_converter.c b/src/date_converter.c new file mode 100644 index 0000000..9b59ac2 --- /dev/null +++ b/src/date_converter.c @@ -0,0 +1,92 @@ +/* + JavaScript functions for the Fourmilab Calendar Converter: + by John Walker -- September, MMIX + http://www.fourmilab.ch/documents/calendar/ + + Converted to C: + by Aboutaleb Roshan -- October, MMXI + 27 Mehr, 1390 (21 Dhu al-Qidah, 1432) (19 October, 2011) + ab.roshan39@gmail.com +*/ + +#include + +float persian_to_jd(int, int, int); +void jd_to_persian(float, int *, int *, int *); +int leap_gregorian(int); +float gregorian_to_jd(int, int, int); +float modFJS(float, float); +//********************************************************************************************// +//////////////////////////////////// PERSIAN CALENDAR //////////////////////////////////// +const float PERSIAN_EPOCH = 1948320.5; + +float persian_to_jd(int day, int month, int year) +{ + float epbase, epyear; + + epbase = year - ((year >= 0) ? 474 : 473); + epyear = 474 + modFJS(epbase, 2820); + + return day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) + + floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 + floor(epbase / 2820) * 1029983 + + (PERSIAN_EPOCH - 1); +} + +void jd_to_persian(float jd, int *day, int *month, int *year) +{ + float wjd, depoch, cycle, cyear, ycycle, aux1, aux2, yday; + + wjd = floor(jd) + 0.5; + depoch = wjd - persian_to_jd(1, 1, 475); + cycle = floor(depoch / 1029983); + cyear = modFJS(depoch, 1029983); + if(cyear == 1029982) + { + ycycle = 2820; + } + else + { + aux1 = floor(cyear / 366); + aux2 = modFJS(cyear, 366); + ycycle = floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1; + } + + *year = ycycle + (2820 * cycle) + 474; + if((*year) <= 0) (*year)--; + + yday = (wjd - persian_to_jd(1, 1, *year)) + 1; + *month = (yday <= 186) ? ceil(yday / 31) : ceil((yday - 6) / 30); + *day = (wjd - persian_to_jd(1, *month, *year)) + 1; +} +//////////////////////////////////// PERSIAN CALENDAR //////////////////////////////////// +//********************************************************************************************// +//////////////////////////////////// GREGORIAN CALENDAR //////////////////////////////////// +const float GREGORIAN_EPOCH = 1721425.5; + +int leap_gregorian(int year) +{ + return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); +} + +float gregorian_to_jd(int day, int month, int year) +{ + return (GREGORIAN_EPOCH - 1) + (365 * (year - 1)) + floor((year - 1) / (float)4) + + (-floor((year - 1) / (float)100)) + floor((year - 1) / (float)400) + + floor((((367 * month) - 362) / (float)12) + + ((month <= 2) ? 0 : (leap_gregorian(year) ? -1 : -2)) + day); +} +//////////////////////////////////// GREGORIAN CALENDAR //////////////////////////////////// +//********************************************************************************************// +float modFJS(float n1, float n2) +{ + float a = fabs(fmod(n1, n2)); + if((n1 < 0) && (n2 > 0) && (a != 0)) return n2 - a; + if((n1 > 0) && (n2 < 0) && (a != 0)) return -(fabs(n2) - a); + if((n1 < 0) && (n2 < 0) && (a != 0)) return -a; + return a; +} + +void gregorian_persian(int *day, int *month, int *year) +{ + jd_to_persian(gregorian_to_jd(*day, *month, *year), day, month, year); +} diff --git a/src/date_converter.h b/src/date_converter.h new file mode 100644 index 0000000..7e3d1c9 --- /dev/null +++ b/src/date_converter.h @@ -0,0 +1,25 @@ +/* + JavaScript functions for the Fourmilab Calendar Converter: + by John Walker -- September, MMIX + http://www.fourmilab.ch/documents/calendar/ + + Converted to C: + by Aboutaleb Roshan -- October, MMXI + 27 Mehr, 1390 (21 Dhu al-Qidah, 1432) (19 October, 2011) + ab.roshan39@gmail.com +*/ + +#ifndef DATE_CONVERTER_H +#define DATE_CONVERTER_H + +#ifdef __cplusplus +extern "C" +{ +#endif // __cplusplus + +void gregorian_persian(int *day, int *month, int *year); + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif // DATE_CONVERTER_H diff --git a/src/downloadform.cpp b/src/downloadform.cpp new file mode 100644 index 0000000..18da45c --- /dev/null +++ b/src/downloadform.cpp @@ -0,0 +1,665 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "downloadform.h" +#include "ui_downloadform.h" + +#include +#include +#include + +#include + +DownloadForm::DownloadForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::DownloadForm) +{ + ui->setupUi(this); +} + +DownloadForm::DownloadForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::DownloadForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + downloadType = ImportToMainDB; + ui->lineEditSaveLocation->setText(QDir::toNativeSeparators(appSettings->mainDBPath)); + + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("دانلود از مخزن"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + + startWidgets(); + + ui->comboBoxSave->addItem("ذخیره در پایگاه داده اصلی", ImportToMainDB); + ui->comboBoxSave->addItem("خروجی در یک پایگاه داده جدید", ExportToNewDB); + ui->comboBoxSave->addItem("فقط دانلود فایل خام", OnlyDownloadFiles); + + fileDownloader = new FileDownloader(); + connect(fileDownloader, &FileDownloader::sigStartDownload, this, &DownloadForm::slotStartDownload); + connect(fileDownloader, &FileDownloader::sigCancel, this, &DownloadForm::slotCancel); + connect(fileDownloader, &FileDownloader::sigProgress, this, &DownloadForm::slotProgress); + connect(fileDownloader, &FileDownloader::sigFinished, this, &DownloadForm::slotFinished); + connect(fileDownloader, &FileDownloader::sigErorr, this, &DownloadForm::slotErorr); +} + +DownloadForm::~DownloadForm() +{ + if(fileDownloader) + { + fileDownloader->deleteLater(); + fileDownloader = nullptr; + } + + delete ui; +} + +void DownloadForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + on_btnClose_clicked(); +} + +void DownloadForm::closeEvent(QCloseEvent *event) +{ + if(downloadFlag == IsDownloading) + { + int reply = messageBox("خروج؟", "نرم‌افزار در حال دانلود است. آیا می‌خواهید دانلود را متوقف کنید و از صفحهٔ دانلود خارج شوید؟", WarningQuestion, this); + if(reply == QMessageBox::No) + { + event->ignore(); + return; + } + cancelClose = true; + downloadFlag = None; + fileDownloader->cancel(); + } + + QWidget::closeEvent(event); +} + +void DownloadForm::on_btnClose_clicked() +{ + close(); +} + +void DownloadForm::startWidgets() +{ + qDir.setPath(QDir::tempPath()); + ui->lineEdit->setText("http://i.ganjoor.net/android/androidgdbs.xml"); + ui->labelSaveLocation->setText("

:محل ذخیره‌سازی

"); + ui->btnCancel->hide(); + ui->labelPoetName->hide(); + ui->labelFinish->hide(); + ui->progressBarOne->hide(); + ui->progressBarAll->hide(); + + ui->tableWidget->setColumnCount(3); + ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + QStringList colList; + colList << "نام شاعر یا نویسنده" << "حجم فایل" << "تاریخ انتشار"; + ui->tableWidget->setHorizontalHeaderLabels(colList); + ui->tableWidget->horizontalHeader()->setDefaultSectionSize(180); +} + +void DownloadForm::on_btnSearchOnGanjoor_clicked() +{ + isXml = true; + downloadFlag = IsDownloading; + + refreshForm(); + ui->comboBox->setCurrentIndex(0); + + QString url = ui->lineEdit->text(); + QFileInfo xmlFN(url); + + xmlDirName = Constants::Rosybit.toLower() + "-xml-" + randString(); + xmlFileName = xmlFN.fileName(); + + ui->tableWidget->model()->removeRows(0, ui->tableWidget->model()->rowCount()); + + if(qDir.mkdir(xmlDirName)) + { + fileDownloader->download(url, qDir.path() + "/" + xmlDirName); + ui->btnSearchOnGanjoor->setEnabled(false); + } +} + +void DownloadForm::on_btnDownload_clicked() +{ + isXml = false; + + if(selectedPoets.count() && check_DB_DirPath()) + { + startDownload(); + downloadLoop(); + } +} + +void DownloadForm::downloadLoop() +{ + if(downloadType == ImportToMainDB || downloadType == ExportToNewDB) + { + if(!commonPoetsChecked) + { + QSqlQuery query(downloadType == ImportToMainDB ? appSettings->mainDB : exportDB.DB()); + QMapIterator i(selectedPoets); + + while(i.hasNext()) + { + i.next(); + query.exec("SELECT * FROM poet WHERE id = " + i.key()); + if(query.first()) + commonPoets << i.key(); + } + + if(!commonPoets.isEmpty()) + { + int reply = messageBox("جایگزینی؟", "در بین انتخاب‌شده‌ها، مواردی وجود دارد که از قبل در پایگاه داده موجود است. آیا می‌خواهید موارد قدیمی را حذف و با موارد جدید جایگزین کنید؟
در غیر این صورت فقط مواردی نصب می‌شوند که در پایگاه داده موجود نیستند.", WarningQuestionToAll, this, QMessageBox::NoToAll); + if(reply == QMessageBox::YesToAll) + removePreVer = true; + else if(reply == QMessageBox::NoToAll) + removePreVer = false; + else + { + startDownloadAbort(); + downloadFlag = None; + return; + } + } + + commonPoetsChecked = true; + } + + while(!removePreVer && commonPoets.contains(selectedPoets.firstKey())) + { + selectedPoets.remove(selectedPoets.firstKey()); + ui->progressBarAll->setMaximum(--allSelectedCount); + } + + if(!downloadedDB && !allSelectedCount) + { + downloadFlag = None; + downloadLoopEnd(); + messageBox("گزارش", "توجه:
موردی برای دانلود یافت نشد!", Information, this); + return; + } + else if(downloadedDB == allSelectedCount) + { + downloadFlag = Finished; + downloadLoopEnd(); + return; + } + } + + QString url = selectedPoets.first()[2]; + QString poetName = selectedPoets.first()[1]; + QFileInfo dlFN(url); + + ui->labelPoetName->setText(QString("در حال دانلود دیتابیس مربوط به %1:").arg(poetName)); + + dlDirName = Constants::Rosybit.toLower() + "-" + randString(); + dlFileName = dlFN.fileName(); + + if(downloadType == ImportToMainDB || downloadType == ExportToNewDB) + { + if(qDir.mkdir(dlDirName)) + fileDownloader->download(url, qDir.path() + "/" + dlDirName); + } + else if(downloadType == OnlyDownloadFiles) + { + fileDownloader->download(url, onlyDownloadFilesDirPath); + } +} + +void DownloadForm::slotFinished() +{ + if(isXml) + { + ui->progressBarOne->hide(); + + QDomDocument document; + QFile file(qDir.path() + "/" + xmlDirName + "/" + xmlFileName); + file.open(QIODevice::ReadOnly | QIODevice::Text); + document.setContent(&file); + file.close(); + removeTempDir(xmlDirName); + + QDomElement root = document.documentElement(); + xmlPoetList.clear(); + xmlPoetList = xmlPoetListElements(root, "gdb"); + + totalSize = 0; + selectedPoets.clear(); + disconnect(ui->tableWidget, &QTableWidget::itemChanged, this, &DownloadForm::slotTableWidgetItemChanged); + tableWidgetDownloadList(ui->tableWidget, appSettings->mainDB, xmlPoetList, preInstalled, notInstalled, appSettings->isDarkMode); + connect(ui->tableWidget, &QTableWidget::itemChanged, this, &DownloadForm::slotTableWidgetItemChanged); + ui->btnSearchOnGanjoor->setEnabled(true); + ui->btnCancel->hide(); + downloadFlag = Finished; + } + else + { + if(downloadType == ImportToMainDB || downloadType == ExportToNewDB) + { + QString dlDirPath = qDir.path() + "/" + dlDirName; + QString dlFilePath = dlDirPath + "/" + dlFileName; + + if(dlFilePath.endsWith(".zip", Qt::CaseInsensitive)) + { + QStringList list = JlCompress::getFileList(dlFilePath); + QStringList dbList; + + for(int i = 0; i < list.count(); i++) + if(dbExtCheck(list[i])) + dbList << list[i]; + + dbList = JlCompress::extractFiles(dlFilePath, dbList, dlDirPath); + + for(int i = 0; i < dbList.count(); i++) + if(isStdGanjoorDB(dbList[i])) + writeToDB(dbList[i]); + } + else + { + if(isStdGanjoorDB(dlFilePath)) + writeToDB(dlFilePath); + else + qDebug().noquote() << "Cannot open downloaded file as a database file!"; + } + removeTempDir(dlDirName); + } + + ui->progressBarAll->setValue(++downloadedDB); + downloadedSize += selectedPoets.first()[3].toInt(); + ui->labelDlInstalledCount->setText(QString("دانلود و نصب‌شده: %1 مورد (%2) ").arg(downloadedDB).arg(byteToHuman(downloadedSize))); + + if(downloadedDB == allSelectedCount) + downloadFlag = Finished; + + selectedPoets.remove(selectedPoets.firstKey()); + + if(downloadFlag == IsDownloading || downloadFlag == Finished) + { + if(selectedPoets.count()) + downloadLoop(); + else + downloadLoopEnd(); + } + } +} + +void DownloadForm::slotStartDownload() +{ + ui->progressBarOne->setValue(0); + ui->progressBarOne->show(); + ui->btnCancel->show(); +} + +void DownloadForm::slotCancel() +{ + downloadFlag = Canceled; + downloadLoopEnd(); +} + +void DownloadForm::slotProgress(const QString &fileName, qint64 total, qint64 received, const QString &sSpeed, int leftHour, int leftMin, int leftSec) +{ + Q_UNUSED(fileName); // (void)fileName; + Q_UNUSED(sSpeed); // (void)sSpeed; + Q_UNUSED(leftHour); // (void)leftHour; + Q_UNUSED(leftMin); // (void)leftMin; + Q_UNUSED(leftSec); // (void)leftSec; + + ui->progressBarOne->setValue(received); + ui->progressBarOne->setMaximum(total); +} + +void DownloadForm::slotErorr(const QString &error) +{ + Q_UNUSED(error); // (void)error; + downloadFlag = Error; + downloadLoopEnd(); +} + +void DownloadForm::on_btnCancel_clicked() +{ + int reply = messageBox("توقف دانلود؟", "آیا از توقف دانلود مطمئن هستید؟ ", WarningQuestion, this); + if(reply == QMessageBox::Yes) + fileDownloader->cancel(); +} + +void DownloadForm::on_tableWidget_doubleClicked(const QModelIndex &index) +{ + int row = index.row(); + + if(ui->tableWidget->item(row, 0)->checkState() == Qt::Unchecked) + ui->tableWidget->item(row, 0)->setCheckState(Qt::Checked); + else + ui->tableWidget->item(row, 0)->setCheckState(Qt::Unchecked); +} + +void DownloadForm::slotTableWidgetItemChanged(QTableWidgetItem *item) +{ + QString itemPoetID(item->data(Qt::UserRole).toString()); + QStringList list; + + if(item->checkState() == Qt::Checked) + { + QString poetName = ui->tableWidget->item(item->row(), 0)->data(Qt::DisplayRole).toString(); + QString poetURL = ui->tableWidget->item(item->row(), 3)->data(Qt::DisplayRole).toString(); + QString poetSize = ui->tableWidget->item(item->row(), 4)->data(Qt::DisplayRole).toString(); + totalSize += poetSize.toInt(); + list << QString::number(item->row()) << poetName << poetURL << poetSize; + selectedPoets.insert(itemPoetID, list); + } + else + { + QString poetSize = ui->tableWidget->item(item->row(), 4)->data(Qt::DisplayRole).toString(); + totalSize -= poetSize.toInt(); + selectedPoets.remove(itemPoetID); + } + + ui->labelSelectedCount->setText(QString("انتخاب‌شده: %1 مورد ").arg(selectedPoets.count())); + ui->labelSelectedSize->setText(QString("حجم کل: %1 ").arg(byteToHuman(totalSize))); + if(!selectedPoets.count()) + clearLabels(); + + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + ui->preInstalledCheckBox->setChecked(false); + ui->notInstalledCheckBox->setChecked(false); +} + +void DownloadForm::on_selectAllCheckBox_clicked(bool checked) +{ + ui->selectNoneCheckBox->setChecked(false); + ui->preInstalledCheckBox->setChecked(false); + ui->notInstalledCheckBox->setChecked(false); + + if(checked) + { + for(int i = 0; i < ui->tableWidget->rowCount(); i++) + ui->tableWidget->item(i, 0)->setCheckState(Qt::Checked); + ui->selectAllCheckBox->setChecked(true); + } + else + for(int i = 0; i < ui->tableWidget->rowCount(); i++) + ui->tableWidget->item(i, 0)->setCheckState(Qt::Unchecked); +} + +void DownloadForm::on_selectNoneCheckBox_clicked(bool checked) +{ + Q_UNUSED(checked); // (void)checked; + + ui->selectAllCheckBox->setChecked(false); + ui->preInstalledCheckBox->setChecked(false); + ui->notInstalledCheckBox->setChecked(false); + + for(int i = 0; i < ui->tableWidget->rowCount(); i++) + ui->tableWidget->item(i, 0)->setCheckState(Qt::Unchecked); + ui->selectNoneCheckBox->setChecked(true); +} + +void DownloadForm::on_preInstalledCheckBox_clicked(bool checked) +{ + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + ui->notInstalledCheckBox->setChecked(false); + + if(checked) + { + for(int i = 0; i < ui->tableWidget->rowCount(); i++) + if(preInstalled.contains(i)) + ui->tableWidget->item(i, 0)->setCheckState(Qt::Checked); + else + ui->tableWidget->item(i, 0)->setCheckState(Qt::Unchecked); + ui->preInstalledCheckBox->setChecked(true); + } + else + for(int i = 0; i < preInstalled.count(); i++) + ui->tableWidget->item(preInstalled[i], 0)->setCheckState(Qt::Unchecked); +} + +void DownloadForm::on_notInstalledCheckBox_clicked(bool checked) +{ + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + ui->preInstalledCheckBox->setChecked(false); + + if(checked) + { + for(int i = 0; i < ui->tableWidget->rowCount(); i++) + if(notInstalled.contains(i)) + ui->tableWidget->item(i, 0)->setCheckState(Qt::Checked); + else + ui->tableWidget->item(i, 0)->setCheckState(Qt::Unchecked); + ui->notInstalledCheckBox->setChecked(true); + } + else + for(int i = 0; i < notInstalled.count(); i++) + ui->tableWidget->item(notInstalled[i], 0)->setCheckState(Qt::Unchecked); +} + +void DownloadForm::on_comboBox_currentIndexChanged(int index) +{ + if(!xmlPoetList.isEmpty()) + { + totalSize = 0; + selectedPoets.clear(); + disconnect(ui->tableWidget, &QTableWidget::itemChanged, this, &DownloadForm::slotTableWidgetItemChanged); + if(index == 1) + tableWidgetDownloadList(ui->tableWidget, appSettings->mainDB, xmlPoetList, preInstalled, notInstalled, appSettings->isDarkMode, NotInstalledItems); + else if(index == 2) + tableWidgetDownloadList(ui->tableWidget, appSettings->mainDB, xmlPoetList, preInstalled, notInstalled, appSettings->isDarkMode, PreInstalledItems); + else + tableWidgetDownloadList(ui->tableWidget, appSettings->mainDB, xmlPoetList, preInstalled, notInstalled, appSettings->isDarkMode); + connect(ui->tableWidget, &QTableWidget::itemChanged, this, &DownloadForm::slotTableWidgetItemChanged); + + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + ui->preInstalledCheckBox->setChecked(false); + ui->notInstalledCheckBox->setChecked(false); + + clearLabels(); + } +} + +void DownloadForm::startDownload() +{ + downloadFlag = IsDownloading; + + ui->btnSearchOnGanjoor->setEnabled(false); + ui->lineEdit->setEnabled(false); + ui->comboBox->setEnabled(false); + ui->comboBoxSave->setEnabled(false); + ui->notInstalledCheckBox->setEnabled(false); + ui->preInstalledCheckBox->setEnabled(false); + ui->selectAllCheckBox->setEnabled(false); + ui->selectNoneCheckBox->setEnabled(false); + ui->tableWidget->setEnabled(false); + ui->btnDownload->setEnabled(false); + + ui->btnClose->setText("توقف و بستن"); + ui->btnCancel->show(); + ui->labelPoetName->show(); + ui->progressBarOne->show(); + ui->progressBarAll->show(); + + allSelectedCount = selectedPoets.count(); + ui->progressBarAll->setRange(0, allSelectedCount); + ui->progressBarAll->setValue(0); +} + +void DownloadForm::startDownloadAbort() +{ + ui->btnSearchOnGanjoor->setEnabled(true); + ui->lineEdit->setEnabled(true); + ui->comboBox->setEnabled(true); + ui->comboBoxSave->setEnabled(true); + ui->notInstalledCheckBox->setEnabled(true); + ui->preInstalledCheckBox->setEnabled(true); + ui->selectAllCheckBox->setEnabled(true); + ui->selectNoneCheckBox->setEnabled(true); + ui->tableWidget->setEnabled(true); + ui->btnDownload->setEnabled(true); + + ui->btnClose->setText("بستن"); + ui->btnCancel->hide(); + ui->labelPoetName->hide(); + ui->progressBarOne->hide(); + ui->progressBarAll->hide(); + + exportDB.remove(); + commonPoets.clear(); +} + +void DownloadForm::downloadLoopEnd() +{ + ui->labelPoetName->hide(); + ui->labelFinish->show(); + ui->progressBarOne->hide(); + + if(downloadFlag == Canceled || downloadFlag == Error) + { + if(isXml) + removeTempDir(xmlDirName); + else if(!isXml && (downloadType == ImportToMainDB || downloadType == ExportToNewDB)) + removeTempDir(dlDirName); + else if(!isXml && downloadType == OnlyDownloadFiles) + QFile::remove(onlyDownloadFilesDirPath + "/" + dlFileName); + } + + if(downloadFlag == Finished) + messageBox("گزارش", "تبریک!
دانلود با موفقیت به پایان رسید.", Information, this); + else if(downloadFlag == Canceled && !cancelClose) + messageBox("گزارش", "دانلود توسط شما متوقف شد!", Information, this); + else if(downloadFlag == Error) + messageBox("خطا", "متأسفانه هنگام دانلود خطایی رخ داد و فرآیند دانلود متوقف شد!", Critical, this); + + if(appSettings->mainDBPath.isEmpty() && downloadType == ExportToNewDB) + { + appSettings->mainDBPath = exportDB.DBPath(); + emit sigMainDBChanged(); + } + + emit sigUpdatePoetList(); + downloadFlag = None; + + refreshForm(); + on_comboBox_currentIndexChanged(ui->comboBox->currentIndex()); +} + +void DownloadForm::refreshForm() +{ + exportDB.remove(); + selectedPoets.clear(); + preInstalled.clear(); + notInstalled.clear(); + commonPoetsChecked = false; + commonPoets.clear(); + removePreVer = false; + totalSize = 0; + downloadedDB = 0; + downloadedSize = 0; + + startDownloadAbort(); + clearLabels(); + + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + ui->preInstalledCheckBox->setChecked(false); + ui->notInstalledCheckBox->setChecked(false); + + ui->labelPoetName->setText(""); + ui->labelFinish->hide(); +} + +void DownloadForm::writeToDB(const QString &databasePath, int speed) +{ + if(downloadType == ImportToMainDB) + importDatabase(appSettings->mainDB, databasePath, removePreVer, speed); + else if(downloadType == ExportToNewDB) + importDatabase(exportDB.DB(), databasePath, removePreVer, speed); +} + +void DownloadForm::on_comboBoxSave_currentIndexChanged(int index) +{ + downloadType = static_cast(ui->comboBoxSave->itemData(index, Qt::UserRole).toInt()); + exportToNewDBPath.clear(); + onlyDownloadFilesDirPath.clear(); + + if(downloadType == ImportToMainDB && !appSettings->mainDBPath.isEmpty()) + ui->lineEditSaveLocation->setText(QDir::toNativeSeparators(appSettings->mainDBPath)); + else + ui->lineEditSaveLocation->clear(); +} + +bool DownloadForm::check_DB_DirPath() +{ + if(downloadType == ImportToMainDB) + { + if(!appSettings->mainDBPath.isEmpty()) + { + return true; + } + else + { + messageBox("هشدار", "شما پایگاه دادهٔ فعالی ندارید. لطفا ابتدا یک پایگاه داده ایجاد کنید.", Warning, this); + appSettings->mainDBPath = createDBDialog(this); + if(!appSettings->mainDBPath.isEmpty()) + { + emit sigMainDBChanged(); + ui->lineEditSaveLocation->setText(QDir::toNativeSeparators(appSettings->mainDBPath)); + return true; + } + } + } + else if(downloadType == ExportToNewDB) + { + if(exportToNewDBPath.isEmpty()) + exportToNewDBPath = createDBDialog(this, QDir::homePath() + "/exportedDB_" + nowDate("-") + "_" + nowTime("") + ".s3db"); + + if(!exportToNewDBPath.isEmpty()) + { + ui->lineEditSaveLocation->setText(QDir::toNativeSeparators(exportToNewDBPath)); + exportDB.setDatabase(exportToNewDBPath, "exportDatabase"); + return true; + } + } + else if(downloadType == OnlyDownloadFiles) + { + if(!onlyDownloadFilesDirPath.isEmpty()) + { + return true; + } + else + { + onlyDownloadFilesDirPath = writableDirDialog(this); + if(!onlyDownloadFilesDirPath.isEmpty()) + { + ui->lineEditSaveLocation->setText(QDir::toNativeSeparators(onlyDownloadFilesDirPath)); + return true; + } + } + } + + return false; +} + +void DownloadForm::clearLabels() +{ + ui->labelSelectedCount->setText("انتخاب‌شده: "); + ui->labelSelectedSize->setText("حجم کل: "); + ui->labelDlInstalledCount->setText("دانلود و نصب‌شده: "); +} diff --git a/src/downloadform.h b/src/downloadform.h new file mode 100644 index 0000000..5ce9fc5 --- /dev/null +++ b/src/downloadform.h @@ -0,0 +1,118 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef DOWNLOADFORM_H +#define DOWNLOADFORM_H + +#include +#include +#include +#include +#include +#include "common_functions.h" +#include "filedownloader.h" + +namespace Ui { +class DownloadForm; +} + +class DownloadForm : public QMainWindow +{ + Q_OBJECT + + enum DownloadType // If you want to change this enum, do it carefully. Because the comboBoxSave items is connected to this enum. + { + ImportToMainDB, + ExportToNewDB, + OnlyDownloadFiles + }; + + enum DownloadFlag + { + None, + IsDownloading, + Canceled, + Finished, + Error + }; + +public: + explicit DownloadForm(QWidget *parent = nullptr); + DownloadForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~DownloadForm(); + +signals: + void sigMainDBChanged(); + void sigUpdatePoetList(); + +public slots: + void startWidgets(); + void slotStartDownload(); + void slotCancel(); + void slotProgress(const QString &fileName, qint64 total, qint64 received, const QString &sSpeed, int leftHour, int leftMin, int leftSec); + void slotFinished(); + void slotErorr(const QString &error); + void slotTableWidgetItemChanged(QTableWidgetItem *item); + void startDownload(); + void startDownloadAbort(); + void downloadLoop(); + void downloadLoopEnd(); + void refreshForm(); + void writeToDB(const QString &databasePath, int speed = 1000); + bool check_DB_DirPath(); + void clearLabels(); + +private slots: + void on_btnClose_clicked(); + void on_btnSearchOnGanjoor_clicked(); + void on_btnDownload_clicked(); + void on_btnCancel_clicked(); + void on_selectAllCheckBox_clicked(bool checked); + void on_notInstalledCheckBox_clicked(bool checked); + void on_preInstalledCheckBox_clicked(bool checked); + void on_comboBox_currentIndexChanged(int index); + void on_selectNoneCheckBox_clicked(bool checked); + void on_comboBoxSave_currentIndexChanged(int index); + void on_tableWidget_doubleClicked(const QModelIndex &index); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void closeEvent(QCloseEvent *event) override; + +private: + Ui::DownloadForm *ui; + AppSettings *appSettings; + SqliteDB exportDB; + bool cancelClose = false; + DownloadType downloadType; // If you want to change this enum, do it carefully. Because the comboBoxSave items is connected to this enum. + QString exportToNewDBPath; + QString onlyDownloadFilesDirPath; + FileDownloader *fileDownloader = nullptr; + bool isXml; + QList xmlPoetList; + QDir qDir; + QString xmlDirName; + QString xmlFileName; + QString dlDirName; + QString dlFileName; + + DownloadFlag downloadFlag = None; + QMap selectedPoets; + int allSelectedCount = 0; + QList preInstalled, notInstalled; + bool commonPoetsChecked = false; + QStringList commonPoets; + bool removePreVer = false; + long long int totalSize = 0; + int downloadedDB = 0; + long long int downloadedSize = 0; +}; + +#endif // DOWNLOADFORM_H diff --git a/src/downloadform.ui b/src/downloadform.ui new file mode 100644 index 0000000..31f39e0 --- /dev/null +++ b/src/downloadform.ui @@ -0,0 +1,481 @@ + + + DownloadForm + + + + 0 + 0 + 704 + 416 + + + + + Sahel + 11 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + + + + + class2 + + + جست‌وجو + + + + + + + class2 + + + مخزن: + + + + + + + class2 + + + + + + + + + + + class2 + + + نحوهٔ نمایش: + + + + + + + class2 + + + + همه + + + + + فقط نصب‌نشده‌ها + + + + + فقط نصب‌شده‌ها + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + class2 + + + نحوهٔ ذخیره‌سازی: + + + + + + + class2 + + + -1 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + class2 + + + انتخاب نصب‌نشده‌ها + + + + + + + class2 + + + انتخاب نصب‌شده‌ها + + + + + + + class2 + + + انتخاب همه + + + + + + + class2 + + + هیچکدام + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Sahel FD + 10 + + + + classFD + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows + + + true + + + + + + + + + + 0 + 0 + + + + + Sahel FD + 10 + + + + classFDs + + + انتخاب‌شده: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + Sahel FD + 10 + + + + classFDs + + + حجم کل: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + Sahel FD + 10 + + + + classFDs + + + دانلود و نصب‌شده: + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + class2 + + + در حال دانلود دیتابیس مربوط به: + + + + + + + classFinish + + + پایان! + + + Qt::AlignCenter + + + + + + + + + + + + Courier New + 9 + + + + class2 + + + Qt::LeftToRight + + + 0 + + + + + + + + Courier New + 9 + + + + class2 + + + Qt::LeftToRight + + + 0 + + + + + + + + + + + class2 + + + دانلود + + + + + + + class2 + + + توقف + + + + + + + class2 + + + بستن + + + + + + + + Sahel + 10 + 50 + false + + + + class2 + + + color: rgb(255, 255, 255); +background-color: rgb(21, 21, 21); + + + databasePath + + + false + + + true + + + + + + + class2 + + + :محل ذخیره‌سازی + + + + + + + + + + + + + diff --git a/src/event_functions.cpp b/src/event_functions.cpp new file mode 100644 index 0000000..c3bd896 --- /dev/null +++ b/src/event_functions.cpp @@ -0,0 +1,75 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "event_functions.h" + +KeyPress::KeyPress(QObject *parent) : + QObject(parent) +{ + if(parent) + parent->installEventFilter(this); +} + +bool KeyPress::eventFilter(QObject *object, QEvent *event) +{ + if(event->type() == QEvent::KeyPress) + { + QKeyEvent *keyEvent = static_cast(event); // QKeyEvent *keyEvent = (QKeyEvent *)event; + emit keyPressed(object, keyEvent); + } + + return false; // return QObject::eventFilter(object, event); +} + +FocusWatcher::FocusWatcher(QObject *parent) : + QObject(parent) +{ + if(parent) + parent->installEventFilter(this); +} + +bool FocusWatcher::eventFilter(QObject *object, QEvent *event) +{ + if(event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) + emit focusChanged(object, event); + + return false; // return QObject::eventFilter(object, event); +} + +ZWNJPress::ZWNJPress(QObject *parent) : + QObject(parent) +{ + if(parent) + parent->installEventFilter(this); +} + +bool ZWNJPress::eventFilter(QObject *object, QEvent *event) +{ + if(event->type() == QEvent::KeyPress) + { + pressedKeys += ((QKeyEvent *)event)->key(); + if(pressedKeys.contains(Qt::Key_Shift) && pressedKeys.contains(Qt::Key_Space)) + { + emit zwnjPressed(object, Qt::ShiftModifier); + return true; + } + else if(pressedKeys.contains(Qt::Key_Control) && pressedKeys.contains(Qt::Key_Space)) + { + emit zwnjPressed(object, Qt::ControlModifier); + return true; + } + } + else if(event->type() == QEvent::KeyRelease) + { + pressedKeys -= ((QKeyEvent *)event)->key(); + } + + return false; // return QObject::eventFilter(object, event); +} diff --git a/src/event_functions.h b/src/event_functions.h new file mode 100644 index 0000000..edaa941 --- /dev/null +++ b/src/event_functions.h @@ -0,0 +1,64 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef EVENTFUNCTIONS_H +#define EVENTFUNCTIONS_H + +#include +#include +#include +#include + +class KeyPress : public QObject +{ + Q_OBJECT + +public: + explicit KeyPress(QObject *parent = nullptr); + +signals: + void keyPressed(QObject *, QKeyEvent *); + +protected: + bool eventFilter(QObject *object, QEvent *event) override; +}; + +class FocusWatcher : public QObject +{ + Q_OBJECT + +public: + explicit FocusWatcher(QObject *parent = nullptr); + +signals: + void focusChanged(QObject *, QEvent *); + +protected: + bool eventFilter(QObject *object, QEvent *event) override; +}; + +class ZWNJPress : public QObject +{ + Q_OBJECT + +public: + explicit ZWNJPress(QObject *parent = nullptr); + +signals: + void zwnjPressed(QObject *, Qt::KeyboardModifier); + +protected: + bool eventFilter(QObject *object, QEvent *event) override; + +private: + QSet pressedKeys; +}; + +#endif // EVENTFUNCTIONS_H diff --git a/src/filedownloader.cpp b/src/filedownloader.cpp new file mode 100644 index 0000000..ff1e5b8 --- /dev/null +++ b/src/filedownloader.cpp @@ -0,0 +1,245 @@ +/* + File Downloader (Qt C++ class): + by Aboutaleb Roshan + 7 Tir, 1396 (3 Shawwal, 1438) (28 June, 2017) + EDITED: + 18 Mehr, 1400 (3 Rabi' al-Awwal, 1443) (10 October, 2021) + ab.roshan39@gmail.com +*/ + +#include "filedownloader.h" + +FileDownloader::FileDownloader(QObject *parent) : + QObject(parent) +{ + manager = new QNetworkAccessManager(this); +} + +FileDownloader::~FileDownloader() +{ + cancel(); +} + +bool FileDownloader::download(const QString &strUrl, const QString &path) +{ + url = QUrl(strUrl); + fileInfo.setFile(url.path()); + QString fileName(fileInfo.fileName()); + + if(fileName.isEmpty()) + { + QString error("Download Status: Failed! Please check the address!"); + qDebug().noquote() << error; + emit sigErorr(error); + return false; + } + else + { + file = new QFile(path + "/" + fileName); + if(!file->open((QIODevice::WriteOnly))) + { + delete file; + file = nullptr; + return false; + } + + qDebug().noquote() << QString("Download Status: Started [%1]").arg(strUrl); + emit sigStartDownload(); + + startDownload(url); + } + return true; +} + +void FileDownloader::cancel() +{ + canceled = true; + if(reply) + reply->abort(); +} + +QString FileDownloader::byteToHuman(qint64 size) +{ + int base = 1024; + + if(size < base) + return QString::number(size) + " Bytes"; + else if(size < pow(base, 2)) + return QString::number((float)size / base, 'f', 2) + " KB"; // Kilobyte + else if(size < pow(base, 3)) + return QString::number((float)size / pow(base, 2), 'f', 2) + " MB"; // Megabyte + else if(size < pow(base, 4)) + return QString::number((float)size / pow(base, 3), 'f', 2) + " GB"; // Gigabyte + else if(size < pow(base, 5)) + return QString::number((float)size / pow(base, 4), 'f', 2) + " TB"; // Terabyte + else if(size < pow(base, 6)) + return QString::number((float)size / pow(base, 5), 'f', 2) + " PB"; // Petabyte + else if(size < pow(base, 7)) + return QString::number((float)size / pow(base, 6), 'f', 2) + " EB"; // Exabyte + else if(size < pow(base, 8)) + return QString::number((float)size / pow(base, 7), 'f', 2) + " ZB"; // Zettabyte + + return QString::number((float)size / pow(base, 8), 'f', 2) + " YB"; // Yottabyte +} + +QString FileDownloader::speedToHuman(double bytesPerMillisecond) +{ + double bps = bytesPerMillisecond * 1000; + int base = 1024; + + if(bps < base) + return QString::number((int)bps) + " Bytes/sec"; + else if(bps < pow(base, 2)) + return QString::number((float)bps / base, 'f', 3) + " KB/sec"; + else if(bps < pow(base, 3)) + return QString::number((float)bps / pow(base, 2), 'f', 3) + " MB/sec"; + else if(bps < pow(base, 4)) + return QString::number((float)bps / pow(base, 3), 'f', 3) + " GB/sec"; + else if(bps < pow(base, 5)) + return QString::number((float)bps / pow(base, 4), 'f', 3) + " TB/sec"; + else if(bps < pow(base, 6)) + return QString::number((float)bps / pow(base, 5), 'f', 3) + " PB/sec"; + else if(bps < pow(base, 7)) + return QString::number((float)bps / pow(base, 6), 'f', 3) + " EB/sec"; + else if(bps < pow(base, 8)) + return QString::number((float)bps / pow(base, 7), 'f', 3) + " ZB/sec"; + + return QString::number((float)bps / pow(base, 8), 'f', 3) + " YB/sec"; +} + +void FileDownloader::startDownload(QUrl url) +{ + canceled = false; + errorOccurred = false; + strError = ""; + reply = manager->get(QNetworkRequest(url)); + + connect(reply, &QIODevice::readyRead, this, &FileDownloader::streamReceived); + connect(reply, &QNetworkReply::downloadProgress, this, &FileDownloader::updateProgress); + connect(reply, &QNetworkReply::finished, this, &FileDownloader::downloadFinished); + connect(reply, &QNetworkReply::sslErrors, this, &FileDownloader::networkSslErrors); +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // #if QT_VERSION >= 0x050F00 + connect(reply, &QNetworkReply::errorOccurred, this, &FileDownloader::networkError); +#else + connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); +#endif + + // Ignored by networkSslErrors slot + // reply->ignoreSslErrors(); + + eTimer.start(); +} + +void FileDownloader::streamReceived() +{ + if(file) + file->write(reply->readAll()); +} + +void FileDownloader::updateProgress(qint64 bytesReceived, qint64 bytesTotal) +{ + if(!canceled && !errorOccurred) + { + QString fileName(fileInfo.fileName()); + qint64 useTime = eTimer.elapsed(); + + double speed = bytesReceived / useTime; + double leftTime = bytesTotal / speed / 1000 - useTime / 1000; + + int intLeftTime = (int)leftTime; + int leftHour = intLeftTime / 3600; + int leftMin = (intLeftTime % 3600) / 60; + int leftSec = intLeftTime % 60; + QString sSpeed = speedToHuman(speed); + + qDebug().noquote() << QString("%1 | File Size: %2 | Downloaded: %3 | Speed: %4 | Time Left: %5h %6m %7s") + .arg(fileName) + .arg(byteToHuman(bytesTotal)) + .arg(byteToHuman(bytesReceived)) + .arg(sSpeed) + .arg(leftHour) + .arg(leftMin) + .arg(leftSec); + emit sigProgress(fileName, bytesTotal, bytesReceived, sSpeed, leftHour, leftMin, leftSec); + } +} + +void FileDownloader::downloadFinished() +{ + if(file) + { + file->close(); + delete file; + file = nullptr; + } + + if(reply) + { + reply->deleteLater(); + reply = nullptr; + } + + if(errorOccurred) + { + qDebug().noquote() << QString("Download Status: Error Occurred and Download Stopped [%1]").arg(strError); + emit sigErorr(strError); + return; + } + + if(canceled) + { + qDebug().noquote() << "Download Status: Canceled"; + emit sigCancel(); + return; + } + + // if(!errorOccurred) + // { + // qDebug().noquote() << "Download Status: Finished"; + // emit sigFinished(); + // } + + qDebug().noquote() << "Download Status: Finished"; + emit sigFinished(); +} + +void FileDownloader::networkSslErrors(const QList &errors) +{ + for(int i = 0; i < errors.count(); i++) + qDebug().noquote() << errors[i].errorString(); + + reply->ignoreSslErrors(errors); + + /* + Note: Because most SSL errors are associated with a certificate, for + most of them you must set the expected certificate this SSL error is + related to (Like self-signed certificate). + + QList expectedSslErrors; + expectedSslErrors.append(QSslError::SelfSignedCertificate); + expectedSslErrors.append(QSslError::CertificateUntrusted); + reply->ignoreSslErrors(expectedSslErrors); + + void QNetworkReply::ignoreSslErrors() + void QNetworkReply::ignoreSslErrors(const QList &errors) + Warning: Be sure to always let the user inspect the errors reported by + the sslErrors() signal, and only call this method upon confirmation + from the user that proceeding is ok. If there are unexpected errors, the + reply should be aborted. Calling this method without inspecting the + actual errors will most likely pose a security risk for your application. + Use it with great care! + */ +} + +void FileDownloader::networkError(QNetworkReply::NetworkError error) +{ + Q_UNUSED(error); // (void)error; + + if(!canceled) + { + errorOccurred = true; + strError = reply->errorString(); + // qDebug().noquote() << QString("Download Status: Error Occurred and Download Stopped [%1]").arg(strError); + // emit sigErorr(strError); + } +} diff --git a/src/filedownloader.h b/src/filedownloader.h new file mode 100644 index 0000000..cb26462 --- /dev/null +++ b/src/filedownloader.h @@ -0,0 +1,66 @@ +/* + File Downloader (Qt C++ class): + by Aboutaleb Roshan + 7 Tir, 1396 (3 Shawwal, 1438) (28 June, 2017) + EDITED: + 18 Mehr, 1400 (3 Rabi' al-Awwal, 1443) (10 October, 2021) + ab.roshan39@gmail.com +*/ + +#ifndef FILEDOWNLOADER_H +#define FILEDOWNLOADER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class FileDownloader : public QObject +{ + Q_OBJECT + +public: + explicit FileDownloader(QObject *parent = nullptr); + virtual ~FileDownloader(); + + bool download(const QString &strUrl, const QString &path); + void cancel(); + + static QString byteToHuman(qint64 size); + static QString speedToHuman(double bytesPerMillisecond); + +signals: + void sigStartDownload(); + void sigCancel(); + void sigProgress(const QString &fileName, qint64 total, qint64 received, const QString &sSpeed, int leftHour, int leftMin, int leftSec); + void sigFinished(); + void sigErorr(const QString &error); + +private slots: + void streamReceived(); + void updateProgress(qint64 bytesReceived, qint64 bytesTotal); + void downloadFinished(); + void networkSslErrors(const QList &errors); + void networkError(QNetworkReply::NetworkError error); + +private: + void startDownload(QUrl url); + +private: + QNetworkAccessManager *manager = nullptr; + QNetworkReply *reply = nullptr; + QUrl url; + QFileInfo fileInfo; + QFile *file = nullptr; + QElapsedTimer eTimer; + bool canceled = false; + bool errorOccurred = false; + QString strError; +}; + +#endif // FILEDOWNLOADER_H diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..fd3e533 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,11 @@ +#include "mainwindow.h" + +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + MainWindow w; + w.show(); + return a.exec(); +} diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp new file mode 100644 index 0000000..c76923a --- /dev/null +++ b/src/mainwindow.cpp @@ -0,0 +1,423 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "appthemes.h" +#include "event_functions.h" + +#include +#include + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) +{ + ui->setupUi(this); + + setWindowTitle(Constants::AppNameFa + ": کتابخانه شعر فارسی"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + QApplication::setLayoutDirection(Qt::RightToLeft); + + loadDefaultFonts(); + readSettings(); + appMenuCreator(); + searchRangeMenuCreator(); + slotMainDBChanged(); + readHistory(); + widgetsStartup(); + applyStyleSheet(); + checkDBExist(); + tabHeaderLabel(); + lineEditDirectionCorrector(ui->lineEditPoet); + lineEditDirectionCorrector(ui->lineEditSearch); + + clipboard = QApplication::clipboard(); + connect(clipboard, &QClipboard::dataChanged, this, &MainWindow::changeTextCopiedToCB); + isClipboardConnect = true; + + connect(qApp, &QGuiApplication::applicationStateChanged, this, &MainWindow::appStateChanged); + connect(new KeyPress(ui->listWidget), &KeyPress::keyPressed, this, &MainWindow::listWidgetKeyPressed); + connect(new KeyPress(ui->tableWidget), &KeyPress::keyPressed, this, &MainWindow::tableWidgetKeyPressed); + connect(new KeyPress(ui->lineEditSearch), &KeyPress::keyPressed, this, &MainWindow::lineEditSearchKeyPressed); + connect(new ZWNJPress(ui->lineEditSearch), &ZWNJPress::zwnjPressed, this, &MainWindow::lineEditsZWNJPressed); + connect(new ZWNJPress(ui->lineEditPoet), &ZWNJPress::zwnjPressed, this, &MainWindow::lineEditsZWNJPressed); +} + +MainWindow::~MainWindow() +{ + delete ui; +} + +void MainWindow::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + { + if(searchAction->isChecked()) + searchAction->setChecked(false); + if(bookmarkListAction->isChecked()) + bookmarkListAction->setChecked(false); + } +} + +void MainWindow::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); // (void)event; + + writeSettings(); + writeHistory(); + dbCloseRemove(appSettings.mainDB); +} + +void MainWindow::appStateChanged(Qt::ApplicationState state) +{ + if(state == Qt::ApplicationActive) + { + if(!isClipboardConnect) + { + qDebug().noquote() << QString("%1 connected").arg(Constants::AppName); + connect(clipboard, &QClipboard::dataChanged, this, &MainWindow::changeTextCopiedToCB); + isClipboardConnect = true; + } + } + else if(state == Qt::ApplicationInactive) + { + if(isClipboardConnect) + { + qDebug().noquote() << QString("%1 disconnected").arg(Constants::AppName); + disconnect(clipboard, &QClipboard::dataChanged, this, &MainWindow::changeTextCopiedToCB); + isClipboardConnect = false; + } + } +} + +void MainWindow::changeTextCopiedToCB() +{ + QString text = correctHtmlTableText(clipboard->text()); + if(clipboard->text() != text) + clipboard->setText(text); +} + +void MainWindow::setContents(QWidget *ptrTab, const QString &levelID, bool setFocusListWidget, bool rememberScrollBarValue, const QStringList &highlightText, const QString &bookmarkVerseID) +{ + connect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), ptrTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); + emit sigSetTabContent(levelID, setFocusListWidget, rememberScrollBarValue, highlightText, bookmarkVerseID); + disconnect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), ptrTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); +} + +void MainWindow::on_listWidget_doubleClicked(const QModelIndex &index) +{ + poetSelected(index); +} + +void MainWindow::on_tableWidget_doubleClicked(const QModelIndex &index) +{ + if(searchAction->isChecked()) + { + QString poetName = index.sibling(index.row(), 0).data(Qt::UserRole).toString(); + QString id = index.sibling(index.row(), 1).data(Qt::UserRole).toString(); + QStringList searchList = textListHighlight(appSettings.ss.searchPhrase); + + ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), " " + poetName + " "); + setContents(appSettings.activeTab, id, false, false, searchList); + } + else if(bookmarkListAction->isChecked()) + { + QString poetName = index.sibling(index.row(), 0).data(Qt::UserRole).toString(); + QString verse_id = index.sibling(index.row(), 1).data(Qt::UserRole).toString(); + QString id = index.sibling(index.row(), 2).data(Qt::UserRole).toString(); + + fromClickOnTableWidget = true; + ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), " " + poetName + " "); + if(verse_id == "-1") + setContents(appSettings.activeTab, id); + else + setContents(appSettings.activeTab, id, false, false, QStringList(), verse_id); + fromClickOnTableWidget = false; + } + + ui->tableWidget->setFocus(); +} + +void MainWindow::poetSelected(const QModelIndex &index, bool setFocusListWidget) +{ + QString poetName = index.data().toString(); + QString poetID = index.data(Qt::UserRole).toString(); + + QSqlQuery query("SELECT cat_id FROM poet WHERE id = " + poetID); + query.next(); + + ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), " " + poetName + " "); + setContents(ui->tabWidget->currentWidget(), "1-" + query.value(0).toString(), setFocusListWidget); +} + +void MainWindow::on_tabWidget_tabCloseRequested(int index) +{ + QWidget *tabWidget = ui->tabWidget->widget(index); + + appSettings.tabLastLevelID.remove(tabWidget); + appSettings.tabCurrentPoem.remove(tabWidget); + tabFontSize.remove(tabWidget); + tabIsDarkMode.remove(tabWidget); + + if(ui->tabWidget->count() != 1) + { + ui->tabWidget->removeTab(index); + } + else + { + actionNewTab(); + tabWidget = ui->tabWidget->widget(0); + ui->tabWidget->removeTab(0); + ui->tabWidget->setTabText(0, "برگ 1"); + } + + if(tabWidget != nullptr) + tabWidget->deleteLater(); +} + +void MainWindow::on_splitter_2_splitterMoved(int pos, int index) +{ + Q_UNUSED(pos); // (void)pos; + Q_UNUSED(index); // (void)index; + + QList sSizes = ui->splitter_2->sizes(); + + if(sSizes[1] && !searchAction->isChecked()) + { + if(!bookmarkListAction->isChecked()) + searchAction->setChecked(true); + } + else if(!sSizes[1] && (searchAction->isChecked() || bookmarkListAction->isChecked())) + { + bookmarkListAction->setChecked(false); + searchAction->setChecked(false); + + ui->btnSearchForm->show(); + ui->btnBookmarkForm->hide(); + } +} + +void MainWindow::on_lineEditPoet_textChanged(const QString &arg1) +{ + listWidgetPoetList(ui->listWidget, appSettings.mainDB, false, "SELECT name, id, cat_id FROM poet WHERE name LIKE '%" + arg1 + "%'"); +} + +void MainWindow::slotUpdatePoetList() +{ + listWidgetPoetList(ui->listWidget, appSettings.mainDB, false, "SELECT name, id, cat_id FROM poet WHERE name LIKE '%" + ui->lineEditPoet->text() + "%'"); +} + +void MainWindow::on_tabWidget_currentChanged(int index) +{ + appSettings.activeTab = ui->tabWidget->widget(index); + + checkBookmark(); + + if(historyOnLoad.contains(appSettings.activeTab)) + { + setContents(appSettings.activeTab, historyOnLoad.value(appSettings.activeTab)); + historyOnLoad.remove(appSettings.activeTab); + } + + if(tabFontSize.value(appSettings.activeTab) != appSettings.viewFSCurrent) + { + fontSizeChanged(appSettings.activeTab); + tabFontSize.insert(appSettings.activeTab, appSettings.viewFSCurrent); + } + + if(tabIsDarkMode.value(appSettings.activeTab) != appSettings.isDarkMode) + { + themeChanged(); + tabIsDarkMode.insert(appSettings.activeTab, appSettings.isDarkMode); + } +} + +void MainWindow::slotMainDBChanged() +{ + dbCloseRemove(appSettings.mainDB); + SqliteDB sqliteDB(appSettings.mainDBPath, "", true); + appSettings.mainDB = sqliteDB.DB(); + + listWidgetPoetList(ui->listWidget, appSettings.mainDB); + ui->lineEditPoet->clear(); +} + +void MainWindow::slotTabLastLevelIDChanged() +{ + checkBookmark(); +} + +void MainWindow::slotSelectedText(const QString &text) +{ + if(appSettings.isOpenAbjadForm || appSettings.isOpenAbjadFormMini) + emit sigSelectedText(text); +} + +void MainWindow::themeChanged() +{ + connect(this, SIGNAL(sigTabTheme()), appSettings.activeTab, SLOT(slotTabTheme())); + emit sigTabTheme(); + disconnect(this, SIGNAL(sigTabTheme()), appSettings.activeTab, SLOT(slotTabTheme())); +} + +void MainWindow::fontSizeChanged(QWidget *ptrTab) +{ + connect(this, SIGNAL(sigTabFormSize()), ptrTab, SLOT(slotTabFormSize())); + emit sigTabFormSize(); + disconnect(this, SIGNAL(sigTabFormSize()), ptrTab, SLOT(slotTabFormSize())); +} + +void MainWindow::tabHeaderLabel() +{ + connect(this, SIGNAL(sigTabHeaderLabel()), appSettings.activeTab, SLOT(slotTabHeaderLabel())); + emit sigTabHeaderLabel(); + disconnect(this, SIGNAL(sigTabHeaderLabel()), appSettings.activeTab, SLOT(slotTabHeaderLabel())); +} + +void MainWindow::checkBookmark() +{ + if(appSettings.tabCurrentPoem.value(appSettings.activeTab).left(1) != "3") + { + bookmarkAction->setChecked(false); + bookmarkAction->setEnabled(false); + ui->checkBoxBookmark->setEnabled(false); + return; + } + else + { + bookmarkAction->setEnabled(true); + ui->checkBoxBookmark->setEnabled(true); + } + + bool value = isBookmarked(appSettings.mainDB, appSettings.tabCurrentPoem.value(appSettings.activeTab), "-1"); + bookmarkAction->setChecked(value); +} + +void MainWindow::slotBookmarkChanged() +{ + checkBookmark(); + if(bookmarkListAction->isChecked()) + tableWidgetBookmark(); +} + +void MainWindow::on_checkBoxDarkMode_clicked(bool checked) +{ + if(checked) + appSettings.isDarkMode = true; + else + appSettings.isDarkMode = false; + applyStyleSheet(); + + themeChanged(); +} + +void MainWindow::listWidgetKeyPressed(QObject *object, QKeyEvent *event) +{ + Q_UNUSED(object); // (void)object; + + int key = event->key(); + if(key == Qt::Key_Return || key == Qt::Key_Enter) + poetSelected(ui->listWidget->currentIndex()); + else if(key == Qt::Key_Space && ui->listWidget->count() && ui->listWidget->currentRow() < 0) + ui->listWidget->setCurrentRow(0); + else if(key == Qt::Key_Left) + poetSelected(ui->listWidget->currentIndex(), true); +} + +void MainWindow::tableWidgetKeyPressed(QObject *object, QKeyEvent *event) +{ + Q_UNUSED(object); // (void)object; + if(event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) + on_tableWidget_doubleClicked(ui->tableWidget->currentIndex()); +} + +void MainWindow::lineEditSearchKeyPressed(QObject *object, QKeyEvent *event) +{ + Q_UNUSED(object); // (void)object; + if(event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) + { + if(ui->lineEditSearch->isEnabled() && !ui->lineEditSearch->isReadOnly()) + on_btnSearch_clicked(); + } +} + +void MainWindow::lineEditsZWNJPressed(QObject *object, Qt::KeyboardModifier key) +{ + Q_UNUSED(key); // (void)key; + static_cast(object)->insert(Constants::ZWNJ); +} + +void MainWindow::on_btnExportXML_clicked() +{ + if(!ui->tableWidget->rowCount()) + return; + + QString file_path = QFileDialog::getSaveFileName(this, "Save As", QDir::homePath() + "/" + Constants::AppName + "_SearchResult_" + QString(searchHistory.date).replace("/", "-") + "_" + QString(searchHistory.time).replace(":", "") + ".xml", "XML files (*.xml)"); + if(file_path.isEmpty()) + { + messageBox("خطا", "لطفا مسیر فایل خروجی را درست انتخاب کنید!.", Warning, this); + return; + } + + QFile file(file_path); + file.open(QIODevice::WriteOnly); + + QXmlStreamWriter stream(&file); +#if QT_VERSION < 0x060000 + stream.setCodec("UTF-8"); +#endif + stream.setAutoFormatting(true); + stream.setAutoFormattingIndent(4); + stream.writeStartDocument("1.0"); + + stream.writeStartElement(Constants::AppName + "App"); + stream.writeTextElement("Version", Constants::AppVersion); + stream.writeStartElement("SearchResult"); + stream.writeTextElement("Date", searchHistory.date); + stream.writeTextElement("Time", searchHistory.time); + stream.writeTextElement("Table", searchHistory.table); + stream.writeTextElement("SkipDiacritics", QVariant(searchHistory.skipDiacritics).toString()); + stream.writeTextElement("SkipCharTypes", QVariant(searchHistory.skipCharTypes).toString()); + + stream.writeStartElement("SearchRange"); + if(searchHistory.allItemsSelected) + stream.writeAttribute("Summary", "AllItems"); + else + stream.writeAttribute("Summary", "SelectedItems"); + stream.writeAttribute("Count", QString::number(searchHistory.poetID.count())); + for(int i = 0; i < searchHistory.poetID.count(); i++) + { + stream.writeStartElement("Item"); + stream.writeAttribute("ID", searchHistory.poetID.at(i)); + stream.writeCharacters(getPoetNameByPoetID(appSettings.mainDB, searchHistory.poetID.at(i))); + stream.writeEndElement(); // Item + } + stream.writeEndElement(); // SearchRange + + stream.writeTextElement("SearchPhrase", searchHistory.searchPhrase); + stream.writeTextElement("Count", QString::number(searchHistory.count)); + stream.writeStartElement("Results"); + + for(int i = 0; i < ui->tableWidget->rowCount(); i++) + { + stream.writeStartElement("Item"); + stream.writeAttribute("ID", ui->tableWidget->item(i, 1)->data(Qt::UserRole).toString()); + stream.writeAttribute("Name", ui->tableWidget->item(i, 0)->data(Qt::UserRole).toString()); + stream.writeCharacters(ui->tableWidget->item(i, 1)->data(Qt::DisplayRole).toString()); + stream.writeEndElement(); // Item + } + + stream.writeEndElement(); // Results + stream.writeEndElement(); // SearchResult + stream.writeEndElement(); // GhazalApp + stream.writeEndDocument(); + file.close(); +} diff --git a/src/mainwindow.h b/src/mainwindow.h new file mode 100644 index 0000000..286fc76 --- /dev/null +++ b/src/mainwindow.h @@ -0,0 +1,152 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include +#include +#include +#include "common_functions.h" +#include "worker.h" + +QT_BEGIN_NAMESPACE +namespace Ui { class MainWindow; } +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr); + ~MainWindow(); + +signals: + void sigSetTabContent(const QString &levelID, bool setFocusListWidget = false, bool rememberScrollBarValue = false, const QStringList &highlightText = QStringList(), const QString &bookmarkVerseID = QString()); + void sigTabFormSize(); + void sigTabTheme(); + void sigTabHeaderLabel(); + void sigSelectedText(const QString &text); + void stopSearch(); + +public slots: + void appStateChanged(Qt::ApplicationState state); + void changeTextCopiedToCB(); + void slotUpdatePoetList(); + void slotMainDBChanged(); + void slotTabLastLevelIDChanged(); + void slotAdjustMenuFont(); + void slotSelectedText(const QString &text); + void slotSearchTableChanged(); + void slotSearch(); + void poetSelected(const QModelIndex &index, bool setFocusListWidget = false); + void themeChanged(); + void fontSizeChanged(QWidget *ptrTab); + void tabHeaderLabel(); + void checkBookmark(); + void slotBookmarkChanged(); + void setContents(QWidget *ptrTab, const QString &levelID, bool setFocusListWidget = false, bool rememberScrollBarValue = false, const QStringList &highlightText = QStringList(), const QString &bookmarkVerseID = QString()); + void threadFinished(Worker::WorkerType type, QVariant result); + void createHistorySearch(); + void loadDefaultFonts(); + void writeSettings(); + void readSettings(); + void writeHistory(); + void readHistory(); + void widgetsStartup(); + void applyStyleSheet(); + void checkDBExist(); + void applyStyleSheetListHeader(); + void lineEditsZWNJPressed(QObject *object, Qt::KeyboardModifier key); + void listWidgetKeyPressed(QObject *object, QKeyEvent *event); + void tableWidgetKeyPressed(QObject *object, QKeyEvent *event); + void lineEditSearchKeyPressed(QObject *object, QKeyEvent *event); + void appMenuCreator(); + void searchRangeMenuCreator(); + void tableWidgetBookmark(); + void actionNewTab(); + void actionCloseTab(); + void actionOpen(); + void actionExit(); + void actionPrevious(); + void actionNext(); + void actionSearchToggled(bool checked); + void actionSearchInCurrentTab(); + void actionJoft(); + void actionTak(); + void actionZoomIn(); + void actionZoomOut(); + void actionDefaultZoomLevel(); + void actionRefresh(); + void actionBookmarkToggled(bool checked); + void actionBookmarkToggledList(bool checked); + void actionShowBookmarks(bool checked); + void actionImportBookmark(); + void actionExportBookmark(); + void actionDatabase(); + void actionDownloadDB(); + void actionAbjad(); + void actionSettings(); + void actionAboutAuthor(); + void actionAbout(); + void actionCat(); + void actionPoem(); + void actionVerse(); + +private slots: + void on_listWidget_doubleClicked(const QModelIndex &index); + void on_lineEditPoet_textChanged(const QString &arg1); + void on_tableWidget_doubleClicked(const QModelIndex &index); + void on_tabWidget_currentChanged(int index); + void on_tabWidget_tabCloseRequested(int index); + void on_splitter_2_splitterMoved(int pos, int index); + void on_checkBoxDarkMode_clicked(bool checked); + void on_btnSearch_clicked(); + void on_btnAdvancedSearch_clicked(); + void on_btnExportXML_clicked(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void closeEvent(QCloseEvent *event) override; + +private: + Ui::MainWindow *ui; + AppSettings appSettings; + SearchHistory searchHistory; + QClipboard *clipboard; + bool isClipboardConnect; + bool fromClickOnTableWidget = false; + + QMap historyOnLoad; + QMap tabFontSize; + QMap tabIsDarkMode; + + QMenu *fileMenu; + QMenu *navigationMenu; + QMenu *searchMenu; + QMenu *viewMenu; + QMenu *viewDisplaySubMenu; + QMenu *bookmarkMenu; + QMenu *toolsMenu; + QMenu *helpMenu; + QMenu *toolButtonMenu; + QAction *searchAction; + QAction *joftAction; + QAction *takAction; + QAction *bookmarkAction; + QAction *bookmarkListAction; + QAction *showBookmarksAction; + QAction *catAction; + QAction *poemAction; + QAction *verseAction; +}; +#endif // MAINWINDOW_H diff --git a/src/mainwindow.ui b/src/mainwindow.ui new file mode 100644 index 0000000..a86d1b1 --- /dev/null +++ b/src/mainwindow.ui @@ -0,0 +1,304 @@ + + + MainWindow + + + + 0 + 0 + 968 + 520 + + + + + Sahel + 11 + 50 + false + + + + MainWindow + + + Qt::RightToLeft + + + + + + + Qt::Vertical + + + + Qt::Horizontal + + + + + + + + Sahel + 11 + + + + class1 + + + + + + + class1 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + شاعر یا نویسنده + + + Qt::VisualMoveStyle + + + + + + + + + + + classFD + + + -1 + + + true + + + true + + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + class2 + + + حالت تاریک + + + + + + + class2 + + + نشانه‌گذاری + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + قبل + + + + + + + بعد + + + + + + + + 0 + 0 + + + + class2 + + + برگ جدید + + + + + + + صفحه نشانه‌ها + + + true + + + + + + + class2 + + + صفحه جست‌وجو + + + true + + + + + + + + + + + + + + + Sahel FD + 10 + + + + classFD + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows + + + 300 + + + true + + + + + + + + + class2 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + عبارت جست‌وجو + + + + + + + class2 + + + 0 + + + false + + + + + + + class2 + + + جست‌وجو + + + + + + + class2 + + + ... + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextOnly + + + + + + + پیشرفته + + + + + + + خروجی + + + + + + + + + + + + + + + diff --git a/src/mainwindow_action_menu.cpp b/src/mainwindow_action_menu.cpp new file mode 100644 index 0000000..b5d4e50 --- /dev/null +++ b/src/mainwindow_action_menu.cpp @@ -0,0 +1,572 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "tabform.h" +#include "settingsform.h" +#include "databaseform.h" +#include "downloadform.h" +#include "wordsearchform.h" +#include "aboutauthorform.h" +#include "abjadform.h" +#include "aboutform.h" + +#include +#include +#include + +#include +#include +#include +#include + +void MainWindow::appMenuCreator() +{ + menuBar()->setNativeMenuBar(false); + + QAction *newTabAction; + QAction *closeTabAction; + QAction *openAction; + QAction *exitAction; + QAction *previousAction; + QAction *nextAction; + QAction *searchAdvancedAction; + QAction *searchInCurrentTabAction; + QAction *zoomInAction; + QAction *zoomOutAction; + QAction *defaultZoomLevelAction; + QAction *refreshAction; + QAction *importBookmarkAction; + QAction *exportBookmarkAction; + QAction *databaseAction; + QAction *downloadDBAction; + QAction *abjadAction; + QAction *settingsAction; + QAction *aboutAction; + QAction *aboutAuthorAction; + + fileMenu = new QMenu(" پرونده "); + navigationMenu = new QMenu(" ناوبری "); + searchMenu = new QMenu(" جست‌وجو "); + viewMenu = new QMenu(" نمایش "); + viewDisplaySubMenu = new QMenu(" نحوهٔ نمایش "); + bookmarkMenu = new QMenu(" نشانه‌ها "); + toolsMenu = new QMenu(" ابزارها "); + helpMenu = new QMenu(" راهنما "); + + newTabAction = new QAction("برگ جدید"); + closeTabAction = new QAction("بستن برگه"); + openAction = new QAction("باز کردن"); + exitAction = new QAction("خروج"); + previousAction = new QAction("قبل"); + nextAction = new QAction("بعد"); + searchAction = new QAction("صفحه جست‌وجو"); + searchAdvancedAction = new QAction("جست‌وجوی پیشرفته"); + searchInCurrentTabAction = new QAction("جست‌وجو در متن جاری"); + joftAction = new QAction("کنار هم"); + takAction = new QAction("زیر هم"); + zoomInAction = new QAction("بزرگ‌تر کردن قلم"); + zoomOutAction = new QAction("کوچک‌تر کردن قلم"); + defaultZoomLevelAction = new QAction("بزرگنمایی پیش‌فرض"); + refreshAction = new QAction("تازه‌سازی"); + bookmarkAction = new QAction("نشانه‌گذاری"); + bookmarkListAction = new QAction("صفحه نشانه‌ها"); + showBookmarksAction = new QAction("نمایش نشانه‌ها"); + importBookmarkAction = new QAction("ورودی به نشانه‌ها"); + exportBookmarkAction = new QAction("خروجی از نشانه‌ها"); + databaseAction = new QAction("صفحه حذف و اضافه"); + downloadDBAction = new QAction("دانلود از مخزن"); + abjadAction = new QAction("محاسبه‌گر ابجد"); + settingsAction = new QAction("تنظیمات"); + aboutAuthorAction = new QAction("دربارهٔ نویسنده"); + aboutAction = new QAction("دربارهٔ برنامه"); + + newTabAction->setShortcut(QKeySequence("Ctrl+T")); + closeTabAction->setShortcut(QKeySequence("Ctrl+W")); + openAction->setShortcut(QKeySequence("Ctrl+O")); + exitAction->setShortcut(QKeySequence("Ctrl+Q")); + previousAction->setShortcut(QKeySequence("Ctrl+Right")); + nextAction->setShortcut(QKeySequence("Ctrl+Left")); + searchAction->setShortcut(QKeySequence("Ctrl+F")); + searchAdvancedAction->setShortcut(QKeySequence("Ctrl+Shift+F")); + searchInCurrentTabAction->setShortcut(QKeySequence("F3")); + joftAction->setShortcut(QKeySequence("Ctrl+1")); + takAction->setShortcut(QKeySequence("Ctrl+2")); + zoomInAction->setShortcuts(QList() << QKeySequence("Ctrl++") << QKeySequence("Ctrl+=")); + zoomOutAction->setShortcut(QKeySequence("Ctrl+-")); + defaultZoomLevelAction->setShortcut(QKeySequence("Ctrl+0")); + refreshAction->setShortcut(QKeySequence("F5")); + bookmarkAction->setShortcut(QKeySequence("Ctrl+D")); + bookmarkListAction->setShortcut(QKeySequence("Ctrl+B")); + showBookmarksAction->setShortcut(QKeySequence("Ctrl+Shift+B")); + databaseAction->setShortcut(QKeySequence("Alt+D")); + downloadDBAction->setShortcut(QKeySequence("Alt+R")); + abjadAction->setShortcut(QKeySequence("Alt+A")); + settingsAction->setShortcut(QKeySequence("Alt+T")); + + searchAction->setCheckable(true); + bookmarkAction->setCheckable(true); + bookmarkListAction->setCheckable(true); + showBookmarksAction->setCheckable(true); + joftAction->setCheckable(true); + takAction->setCheckable(true); + + fileMenu->addAction(newTabAction); + fileMenu->addAction(closeTabAction); + fileMenu->addAction(openAction); + fileMenu->addAction(exitAction); + navigationMenu->addAction(previousAction); + navigationMenu->addAction(nextAction); + searchMenu->addAction(searchAction); + searchMenu->addAction(searchAdvancedAction); + searchMenu->addAction(searchInCurrentTabAction); + viewMenu->addMenu(viewDisplaySubMenu); + viewDisplaySubMenu->addAction(joftAction); + viewDisplaySubMenu->addAction(takAction); + viewMenu->addSeparator(); + viewMenu->addAction(zoomInAction); + viewMenu->addAction(zoomOutAction); + viewMenu->addSeparator(); + viewMenu->addAction(defaultZoomLevelAction); + viewMenu->addSeparator(); + viewMenu->addAction(refreshAction); + bookmarkMenu->addAction(bookmarkAction); + bookmarkMenu->addAction(bookmarkListAction); + bookmarkMenu->addSeparator(); + bookmarkMenu->addAction(showBookmarksAction); + bookmarkMenu->addSeparator(); + bookmarkMenu->addAction(importBookmarkAction); + bookmarkMenu->addAction(exportBookmarkAction); + toolsMenu->addAction(databaseAction); + toolsMenu->addAction(downloadDBAction); + toolsMenu->addSeparator(); + toolsMenu->addAction(abjadAction); + toolsMenu->addSeparator(); + toolsMenu->addAction(settingsAction); + helpMenu->addAction(aboutAuthorAction); + helpMenu->addAction(aboutAction); + + menuBar()->addMenu(fileMenu); + menuBar()->addMenu(navigationMenu); + menuBar()->addMenu(searchMenu); + menuBar()->addMenu(viewMenu); + menuBar()->addMenu(bookmarkMenu); + menuBar()->addMenu(toolsMenu); + menuBar()->addMenu(helpMenu); + + connect(newTabAction, &QAction::triggered, this, &MainWindow::actionNewTab); // connect(newTabAction, SIGNAL(triggered()), this, SLOT(actionNewTab())); + connect(ui->btnNewTab, &QPushButton::clicked, this, &MainWindow::actionNewTab); // connect(ui->btnNewTab, SIGNAL(clicked()), this, SLOT(actionNewTab())); + + connect(closeTabAction, &QAction::triggered, this, &MainWindow::actionCloseTab); + connect(openAction, &QAction::triggered, this, &MainWindow::actionOpen); + connect(exitAction, &QAction::triggered, this, &MainWindow::actionExit); + + connect(previousAction, &QAction::triggered, this, &MainWindow::actionPrevious); + connect(ui->btnPrevious, &QPushButton::clicked, this, &MainWindow::actionPrevious); + + connect(nextAction, &QAction::triggered, this, &MainWindow::actionNext); + connect(ui->btnNext, &QPushButton::clicked, this, &MainWindow::actionNext); + + connect(searchAction, &QAction::toggled, this, &MainWindow::actionSearchToggled); // connect(searchAction, SIGNAL(toggled(bool)), this, SLOT(actionSearchToggled(bool))); + connect(searchAction, &QAction::toggled, ui->btnSearchForm, &QPushButton::setChecked); // connect(searchAction, SIGNAL(toggled(bool)), ui->btnSearchForm, SLOT(setChecked(bool))); + connect(ui->btnSearchForm, &QPushButton::toggled, searchAction, &QAction::setChecked); // connect(ui->btnSearchForm, SIGNAL(toggled(bool)), searchAction, SLOT(setChecked(bool))); + + connect(searchAdvancedAction, &QAction::triggered, ui->btnAdvancedSearch, &QPushButton::clicked); + connect(searchInCurrentTabAction, &QAction::triggered, this, &MainWindow::actionSearchInCurrentTab); + + connect(joftAction, &QAction::triggered, this, &MainWindow::actionJoft); + connect(takAction, &QAction::triggered, this, &MainWindow::actionTak); + + connect(zoomInAction, &QAction::triggered, this, &MainWindow::actionZoomIn); + connect(zoomOutAction, &QAction::triggered, this, &MainWindow::actionZoomOut); + connect(defaultZoomLevelAction, &QAction::triggered, this, &MainWindow::actionDefaultZoomLevel); + connect(refreshAction, &QAction::triggered, this, &MainWindow::actionRefresh); + + connect(bookmarkAction, &QAction::toggled, this, &MainWindow::actionBookmarkToggled); + connect(bookmarkAction, &QAction::toggled, ui->checkBoxBookmark, &QCheckBox::setChecked); + connect(ui->checkBoxBookmark, &QCheckBox::toggled, bookmarkAction, &QAction::setChecked); + + connect(bookmarkListAction, &QAction::toggled, this, &MainWindow::actionBookmarkToggledList); + connect(bookmarkListAction, &QAction::toggled, ui->btnBookmarkForm, &QPushButton::setChecked); + connect(ui->btnBookmarkForm, &QPushButton::toggled, bookmarkListAction, &QAction::setChecked); + + connect(showBookmarksAction, &QAction::triggered, this, &MainWindow::actionShowBookmarks); + connect(importBookmarkAction, &QAction::triggered, this, &MainWindow::actionImportBookmark); + connect(exportBookmarkAction, &QAction::triggered, this, &MainWindow::actionExportBookmark); + connect(databaseAction, &QAction::triggered, this, &MainWindow::actionDatabase); + connect(downloadDBAction, &QAction::triggered, this, &MainWindow::actionDownloadDB); + connect(abjadAction, &QAction::triggered, this, &MainWindow::actionAbjad); + connect(settingsAction, &QAction::triggered, this, &MainWindow::actionSettings); + connect(aboutAuthorAction, &QAction::triggered, this, &MainWindow::actionAboutAuthor); + connect(aboutAction, &QAction::triggered, this, &MainWindow::actionAbout); + + if(appSettings.pDisplayType == Joft) + { + joftAction->setChecked(true); + takAction->setChecked(false); + } + else if(appSettings.pDisplayType == Tak) + { + joftAction->setChecked(false); + takAction->setChecked(true); + } + + if(appSettings.showBookmarks) + showBookmarksAction->setChecked(true); +} + +void MainWindow::slotAdjustMenuFont() +{ + int size = (int)(appSettings.appFS.toDouble() + 0.5); + + menuBar()->setFont(QFont(appSettings.appFN, size)); + fileMenu->setFont(QFont(appSettings.appFN, size)); + navigationMenu->setFont(QFont(appSettings.appFN, size)); + searchMenu->setFont(QFont(appSettings.appFN, size)); + viewMenu->setFont(QFont(appSettings.appFN, size)); + bookmarkMenu->setFont(QFont(appSettings.appFN, size)); + toolsMenu->setFont(QFont(appSettings.appFN, size)); + helpMenu->setFont(QFont(appSettings.appFN, size)); + toolButtonMenu->setFont(QFont(appSettings.appFN, size)); +} + +void MainWindow::actionNewTab() +{ + ui->tabWidget->addTab(new TabForm(&appSettings, this), "برگ " + QString::number(ui->tabWidget->count() + 1)); + ui->tabWidget->setCurrentIndex(ui->tabWidget->count() - 1); + ui->listWidget->setFocus(); +} + +void MainWindow::actionCloseTab() +{ + on_tabWidget_tabCloseRequested(ui->tabWidget->currentIndex()); +} + +void MainWindow::actionOpen() +{ + QString filter = "Database files (*.s3db *.db *.sqlite3 *.sqlite *.gdb);;All files (*.*)"; + QString file_name = QFileDialog::getOpenFileName(this, "Open", QDir::homePath(), filter); + if(!file_name.isEmpty()) + { + if(isStdGanjoorDB(file_name)) + { + appSettings.mainDBPath = file_name; + slotMainDBChanged(); + } + else + messageBox("خطا", "خطا:
فایل انتخاب‌شده قالب استانداردی ندارد!", Critical, this); + } +} + +void MainWindow::actionExit() +{ + close(); + QCoreApplication::quit(); // QCoreApplication::exit(0); // qApp->quit(); // qApp->exit(0); + + /* + void QCoreApplication::quit() + Tells the application to exit with return code 0 (success). + Equivalent to calling QCoreApplication::exit(0). + + QApplication is derived from QCoreApplication and thereby inherits quit() + which is a public slot of QCoreApplication, so there is no difference between + QApplication::quit() and QCoreApplication::quit() + + qApp + A global pointer referring to the unique application object. It is + equivalent to QCoreApplication::instance(), but cast as a QApplication pointer, + so only valid when the unique application object is a QApplication. + */ +} + +void MainWindow::actionPrevious() +{ + QString previous(previousPoem(appSettings.mainDB, appSettings.tabCurrentPoem.value(appSettings.activeTab))); + + if(!previous.isEmpty()) + setContents(appSettings.activeTab, previous); +} + +void MainWindow::actionNext() +{ + QString next(nextPoem(appSettings.mainDB, appSettings.tabCurrentPoem.value(appSettings.activeTab))); + + if(!next.isEmpty()) + setContents(appSettings.activeTab, next); +} + +void MainWindow::actionSearchToggled(bool checked) +{ + if(checked) + { + bookmarkListAction->setChecked(false); + ui->splitter_2->setSizes({4000, 3000}); + ui->tableWidget->setEnabled(true); + ui->lineEditSearch->show(); + ui->lineEditSearch->setEnabled(true); + ui->btnSearch->show(); + ui->btnSearch->setEnabled(true); + ui->toolButton->show(); + ui->toolButton->setEnabled(true); + ui->btnAdvancedSearch->show(); + ui->btnAdvancedSearch->setEnabled(true); + ui->btnExportXML->show(); + ui->btnExportXML->setEnabled(true); + ui->lineEditSearch->selectAll(); + ui->lineEditSearch->setFocus(); + if(ui->tableWidget->columnCount() == 3) + { + ui->tableWidget->model()->removeRows(0, ui->tableWidget->model()->rowCount()); + ui->tableWidget->model()->removeColumns(0, ui->tableWidget->model()->columnCount()); + ui->tableWidget->horizontalHeader()->setDefaultSectionSize(300); + } + } + else + { + ui->splitter_2->setSizes({4000, 0}); + ui->tableWidget->setEnabled(false); + ui->lineEditSearch->setEnabled(false); + ui->btnSearch->setEnabled(false); + ui->toolButton->setEnabled(false); + ui->btnAdvancedSearch->setEnabled(false); + ui->btnExportXML->setEnabled(false); + } +} + +void MainWindow::actionSearchInCurrentTab() +{ + if(!appSettings.isOpenWordSearchForm) + { + WordSearchForm *wordSearchForm = new WordSearchForm(&appSettings, this); + wordSearchForm->show(); + } +} + +void MainWindow::actionJoft() +{ + if(appSettings.pDisplayType != Joft) + { + appSettings.pDisplayType = Joft; + setContents(appSettings.activeTab, appSettings.tabLastLevelID.value(appSettings.activeTab)); + } + + joftAction->setChecked(true); + takAction->setChecked(false); +} + +void MainWindow::actionTak() +{ + if(appSettings.pDisplayType != Tak) + { + appSettings.pDisplayType = Tak; + setContents(appSettings.activeTab, appSettings.tabLastLevelID.value(appSettings.activeTab)); + } + + joftAction->setChecked(false); + takAction->setChecked(true); +} + +void MainWindow::actionZoomIn() +{ + double size = appSettings.viewFSCurrent.toDouble() + 1; + appSettings.viewFSCurrent = QString::number(size); + fontSizeChanged(appSettings.activeTab); + applyStyleSheetListHeader(); +} + +void MainWindow::actionZoomOut() +{ + double size = appSettings.viewFSCurrent.toDouble() - 1; + appSettings.viewFSCurrent = QString::number(size); + fontSizeChanged(appSettings.activeTab); + applyStyleSheetListHeader(); +} + +void MainWindow::actionDefaultZoomLevel() +{ + double size = appSettings.viewFS.toDouble(); + appSettings.viewFSCurrent = QString::number(size); + fontSizeChanged(appSettings.activeTab); + applyStyleSheetListHeader(); +} + +void MainWindow::actionRefresh() +{ + setContents(appSettings.activeTab, appSettings.tabLastLevelID.value(appSettings.activeTab)); +} + +void MainWindow::actionBookmarkToggled(bool checked) +{ + setBookmarked(appSettings.mainDB, appSettings.tabCurrentPoem.value(appSettings.activeTab), "-1", checked); + if(bookmarkListAction->isChecked()) + tableWidgetBookmark(); +} + +void MainWindow::actionBookmarkToggledList(bool checked) +{ + if(checked) + { + searchAction->setChecked(false); + ui->splitter_2->setSizes({4000, 3000}); + ui->btnSearchForm->hide(); + ui->btnBookmarkForm->show(); + ui->tableWidget->setEnabled(true); + ui->lineEditSearch->hide(); + ui->btnSearch->hide(); + ui->toolButton->hide(); + ui->btnAdvancedSearch->hide(); + ui->btnExportXML->hide(); + appSettings.ss.searchPhrase.clear(); + } + else + { + ui->splitter_2->setSizes({4000, 0}); + ui->btnSearchForm->show(); + ui->btnBookmarkForm->hide(); + ui->tableWidget->setEnabled(false); + return; + } + + tableWidgetBookmark(); +} + +void MainWindow::tableWidgetBookmark() +{ + if(fromClickOnTableWidget) + return; + + ui->tableWidget->model()->removeRows(0, ui->tableWidget->model()->rowCount()); + ui->tableWidget->model()->removeColumns(0, ui->tableWidget->model()->columnCount()); + + QSqlQuery query("SELECT poem_id, verse_id FROM fav ORDER BY pos"); + QSqlQuery queryText; + + ui->tableWidget->setColumnCount(3); + ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + + QStringList colList; + colList << "عنوان" << "محدوده" << "متن"; + ui->tableWidget->setHorizontalHeaderLabels(colList); + ui->tableWidget->setColumnWidth(1, 120); + + int row_count = 0; + while(query.next()) + { + ui->tableWidget->insertRow(row_count); + + QTableWidgetItem *item1 = new QTableWidgetItem; + QTableWidgetItem *item2 = new QTableWidgetItem; + QTableWidgetItem *item3 = new QTableWidgetItem; + QString poemID = query.value(0).toString(); + QString verse_id = query.value(1).toString(); + QString vorder = verse_id == "-1" ? "1" : verse_id; + GanjoorPath gp = recursiveIDs(appSettings.mainDB, "3", poemID); + int iLast = gp.text.count() - 1; + QString str = gp.text[iLast] + ": " + gp.text[0]; + + queryText.exec(QString("SELECT text FROM verse WHERE poem_id = %1 AND vorder = %2").arg(poemID, vorder)); + queryText.next(); + + item1->setText(spaceReplace(str, "…", 6)); + item1->setData(Qt::UserRole, gp.text[iLast]); + item2->setText(verse_id == "-1" ? "کل متن" : "یک بخش"); + item2->setData(Qt::UserRole, verse_id); + item3->setText(queryText.value(0).toString()); + item3->setData(Qt::UserRole, "3-" + poemID); + + ui->tableWidget->setItem(row_count, 0, item1); + ui->tableWidget->setItem(row_count, 1, item2); + ui->tableWidget->setItem(row_count, 2, item3); + + row_count++; + } +} + +void MainWindow::actionShowBookmarks(bool checked) +{ + appSettings.showBookmarks = checked; + setContents(appSettings.activeTab, appSettings.tabLastLevelID.value(appSettings.activeTab), false, true); +} + +void MainWindow::actionImportBookmark() +{ + QString filter = "Ganjoor Database files (*.gdb);;Ganjoor Database files (*.s3db);;SQLite Database files (*.sqlite);;SQLite 3 Database files (*.sqlite3);;Database files (*.db)"; + QString file_name = QFileDialog::getOpenFileName(this, "Open", QDir::homePath(), filter); + + if(!file_name.isEmpty()) + { + if(isStdGanjoorDB(file_name, BookmarkDatabase)) + importBookmarks(appSettings.mainDB, file_name, 50000); + else + messageBox("خطا", "خطا:
در فایل انتخاب‌شده جدول نشانه‌ها یافت نشد!", Critical, this); + } +} + +void MainWindow::actionExportBookmark() +{ + QString filter = "Ganjoor Database files (*.gdb);;Ganjoor Database files (*.s3db);;SQLite Database files (*.sqlite);;SQLite 3 Database files (*.sqlite3);;Database files (*.db)"; + QString db_file_name = QFileDialog::getSaveFileName(this, "Save As", QDir::homePath() + "/exportedBookmarks_" + nowDate("-") + "_" + nowTime("") + ".gdb", filter); + + if(!db_file_name.isEmpty()) + { + SqliteDB secondDB(db_file_name, "secondDatabase", false); + exportBookmarks(appSettings.mainDB, secondDB.DB(), 50000); + secondDB.remove(); + } +} + +void MainWindow::actionDatabase() +{ + DatabaseForm *databaseForm = new DatabaseForm(&appSettings, this); + connect(databaseForm, &DatabaseForm::sigMainDBChanged, this, &MainWindow::slotMainDBChanged); + connect(databaseForm, &DatabaseForm::sigUpdatePoetList, this, &MainWindow::slotUpdatePoetList); + databaseForm->show(); +} + +void MainWindow::actionDownloadDB() +{ + DownloadForm *downloadForm = new DownloadForm(&appSettings, this); + connect(downloadForm, &DownloadForm::sigMainDBChanged, this, &MainWindow::slotMainDBChanged); + connect(downloadForm, &DownloadForm::sigUpdatePoetList, this, &MainWindow::slotUpdatePoetList); + downloadForm->show(); +} + +void MainWindow::actionAbjad() +{ + if(!appSettings.isOpenAbjadForm) + { + AbjadForm *abjadForm = new AbjadForm(&appSettings, this); + connect(this, &MainWindow::sigSelectedText, abjadForm, &AbjadForm::slotSelectedText); + abjadForm->show(); + } +} + +void MainWindow::actionSettings() +{ + SettingsForm *settingsForm = new SettingsForm(&appSettings, this); + connect(settingsForm, &SettingsForm::sigAdjustMenuFont, this, &MainWindow::slotAdjustMenuFont); + connect(settingsForm, &SettingsForm::sigMainDBChanged, this, &MainWindow::slotMainDBChanged); + connect(settingsForm, SIGNAL(sigTabFormSize()), ui->tabWidget->currentWidget(), SLOT(slotTabFormSize())); + connect(settingsForm, SIGNAL(sigTabTheme()), ui->tabWidget->currentWidget(), SLOT(slotTabTheme())); + settingsForm->show(); +} + +void MainWindow::actionAboutAuthor() +{ + AboutAuthorForm *aboutAuthorForm = new AboutAuthorForm(&appSettings, this); + aboutAuthorForm->show(); +} + +void MainWindow::actionAbout() +{ + AboutForm *aboutForm = new AboutForm(&appSettings, this); + aboutForm->show(); +} diff --git a/src/mainwindow_app_setting.cpp b/src/mainwindow_app_setting.cpp new file mode 100644 index 0000000..ee9af2f --- /dev/null +++ b/src/mainwindow_app_setting.cpp @@ -0,0 +1,210 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "tabform.h" +#include "appthemes.h" + +#include + +void MainWindow::loadDefaultFonts() +{ + QFontDatabase::addApplicationFont(":/files/fonts/Sahel.ttf"); + QFontDatabase::addApplicationFont(":/files/fonts/Sahel-Bold.ttf"); + QFontDatabase::addApplicationFont(":/files/fonts/Sahel-FD.ttf"); + QFontDatabase::addApplicationFont(":/files/fonts/Sahel-Bold-FD.ttf"); +} + +void MainWindow::writeSettings() +{ + QSettings settings(QString("%1/%2/%3").arg(rosybitDir()).arg(appNameOS()).arg(Constants::SettingsFileName), QSettings::IniFormat); + + settings.setValue("General/MainDatabase", appSettings.mainDBPath); + settings.setValue("General/PoemDisplayType", appSettings.pDisplayType); + settings.setValue("General/ShowBookmarks", (int)appSettings.showBookmarks); + settings.setValue("General/DarkMode", (int)appSettings.isDarkMode); + settings.setValue("General/HemistichDistance", appSettings.hemistichDistance); + settings.setValue("Font/AppFontName", appSettings.appFN); + settings.setValue("Font/AppFontSize", appSettings.appFS); + settings.setValue("Font/ListFontName", appSettings.listFN); + settings.setValue("Font/ListFontSize", appSettings.listFS); + settings.setValue("Font/ViewFontName", appSettings.viewFN); + settings.setValue("Font/ViewFontSize", appSettings.viewFS); + settings.setValue("Search/SkipDiacritics", (int)appSettings.ss.skipDiacritics); + settings.setValue("Search/SkipCharTypes", (int)appSettings.ss.skipCharTypes); + + settings.setValue("Startup/PoetSplitterSizeI0", ui->splitter->sizes().at(0)); + settings.setValue("Startup/PoetSplitterSizeI1", ui->splitter->sizes().at(1)); + settings.setValue("Startup/Maximized", (int)isMaximized()); + if(!isMaximized()) + { + settings.setValue("Startup/Size", size()); + settings.setValue("Startup/Pos", pos()); + } +} + +void MainWindow::readSettings() +{ + QSettings settings(QString("%1/%2/%3").arg(rosybitDir()).arg(appNameOS()).arg(Constants::SettingsFileName), QSettings::IniFormat); + + appSettings.mainDBPath = settings.value("General/MainDatabase").toString(); + appSettings.pDisplayType = static_cast(settings.value("General/PoemDisplayType", "0").toInt()); + appSettings.showBookmarks = settings.value("General/ShowBookmarks", "1").toInt(); + appSettings.isDarkMode = settings.value("General/DarkMode", "0").toInt(); + appSettings.hemistichDistance = settings.value("General/HemistichDistance", "60").toInt(); + appSettings.appFN = settings.value("Font/AppFontName", "Sahel").toString(); + appSettings.appFS = settings.value("Font/AppFontSize", "10.5").toString(); + appSettings.listFN = settings.value("Font/ListFontName", "Sahel").toString(); + appSettings.listFS = settings.value("Font/ListFontSize", "11").toString(); + appSettings.viewFN = settings.value("Font/ViewFontName", "Sahel").toString(); + appSettings.viewFS = settings.value("Font/ViewFontSize", "11").toString(); + appSettings.ss.skipDiacritics = settings.value("Search/SkipDiacritics", "0").toInt(); + appSettings.ss.skipCharTypes = settings.value("Search/SkipCharTypes", "0").toInt(); + + StartupSettings startupSettings; + startupSettings.poetSplitterSize << settings.value("Startup/PoetSplitterSizeI0", "1000").toInt(); + startupSettings.poetSplitterSize << settings.value("Startup/PoetSplitterSizeI1", "4000").toInt(); + ui->splitter->setSizes(startupSettings.poetSplitterSize); + startupSettings.isMaximized = settings.value("Startup/Maximized", "1").toInt(); + startupSettings.mainWindowSize = settings.value("Startup/Size", QSize(968, 520)).toSize(); + resize(startupSettings.mainWindowSize); + startupSettings.mainWindowPos = settings.value("Startup/Pos", QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry()).topLeft()).toPoint(); + move(startupSettings.mainWindowPos); + if(startupSettings.isMaximized) + setWindowState(Qt::WindowMaximized); + + appSettings.listWidget = ui->listWidget; + appSettings.tabWidget = ui->tabWidget; + appSettings.viewFSCurrent = appSettings.viewFS; + appSettings.ss.allItemsSelected = true; + appSettings.ss.searchState = false; + appSettings.ss.isSearching = false; + appSettings.isOpenWordSearchForm = false; + appSettings.isOpenAbjadForm = false; + appSettings.isOpenAbjadFormMini = false; + + if(!QFile::exists(appSettings.mainDBPath) || !isStdGanjoorDB(appSettings.mainDBPath)) + appSettings.mainDBPath = defaultDBPath(); + + if(!(appSettings.pDisplayType == Joft || appSettings.pDisplayType == Tak)) + appSettings.pDisplayType = Joft; + + appSettings.hemistichDistanceMin = 0; + appSettings.hemistichDistanceMax = 200; + + if(appSettings.hemistichDistance < appSettings.hemistichDistanceMin) + appSettings.hemistichDistance = appSettings.hemistichDistanceMin; + else if(appSettings.hemistichDistance > appSettings.hemistichDistanceMax) + appSettings.hemistichDistance = appSettings.hemistichDistanceMax; + + appSettings.ss.table = VerseTable; +} + +void MainWindow::writeHistory() +{ + QString historyFilePath = QString("%1/%2/%3").arg(rosybitDir()).arg(appNameOS()).arg(Constants::HistoryFileName); + QFile::remove(historyFilePath); + QSettings settings(historyFilePath, QSettings::IniFormat); + + settings.setValue("History/ActiveTab", ui->tabWidget->currentIndex() + 1); + + QString value; + for(int i = 0; i < ui->tabWidget->count(); i++) + { + QWidget *tab = ui->tabWidget->widget(i); + if(appSettings.tabLastLevelID.contains(tab)) + value = appSettings.tabLastLevelID.value(tab); + else + value = "NULL"; + + settings.setValue(QString("History/Tab%1").arg(i + 1), value); + } +} + +void MainWindow::readHistory() +{ + QString historyFilePath = QString("%1/%2/%3").arg(rosybitDir()).arg(appNameOS()).arg(Constants::HistoryFileName); + QSettings settings(historyFilePath, QSettings::IniFormat); + QWidget *pActiveTab = nullptr; + QString valueActiveTab; + + int activeTab = settings.value("History/ActiveTab", "1").toInt(); + + int i = 1; + QString value = settings.value(QString("History/Tab%1").arg(i)).toString(); + while(!value.isEmpty()) + { + TabForm *newTab = new TabForm(&appSettings, this); + ui->tabWidget->addTab(newTab, "برگ " + QString::number(ui->tabWidget->count() + 1)); + + fontSizeChanged(newTab); + tabFontSize.insert(newTab, appSettings.viewFSCurrent); + tabIsDarkMode.insert(newTab, appSettings.isDarkMode); + + if(value != "NULL") + { + appSettings.tabLastLevelID.insert(newTab, value); + historyOnLoad.insert(newTab, value); + ui->tabWidget->setTabText(i - 1, " " + idTitle(appSettings.mainDB, value) + " "); + + if(i == activeTab) + { + pActiveTab = newTab; + valueActiveTab = value; + } + } + + value = settings.value(QString("History/Tab%1").arg(++i)).toString(); + } + + ui->tabWidget->setCurrentIndex(activeTab ? --activeTab : activeTab); + + // محتواي تب از طريق تابع تغيير تب کنونی قرار داده مي‌شود. مگر اينکه تغيير تب وجود نداشته باشد. يعني: + // activeTab == 0 + // که در اين صورت با بلاك زير قرار داده مي‌شود. + if(pActiveTab != nullptr && !activeTab) + { + setContents(pActiveTab, valueActiveTab); + historyOnLoad.remove(pActiveTab); + } +} + +void MainWindow::widgetsStartup() +{ + ui->splitter_2->setSizes({4000, 0}); + ui->progressBarSearch->hide(); + ui->progressBarSearch->setMaximum(0); + ui->btnBookmarkForm->hide(); + ui->checkBoxDarkMode->setChecked(appSettings.isDarkMode); + + if(!ui->tabWidget->count()) + actionNewTab(); +} + +void MainWindow::applyStyleSheet() +{ + QString addStyle = appStyleSheet(appSettings.appFN, appSettings.appFS, appSettings.listFN, appSettings.listFS, appSettings.viewFN, appSettings.viewFSCurrent); + if(appSettings.isDarkMode) + QApplication::setStyle(new DarkStyle(addStyle)); + else + QApplication::setStyle(new LightStyle(addStyle)); +} + +void MainWindow::applyStyleSheetListHeader() +{ + setStyleSheet("*[accessibleName=classViewListHeader]{font-family:" + appSettings.viewFN + ";font-size:" + appSettings.viewFSCurrent + "pt;}"); +} + +void MainWindow::checkDBExist() +{ + if(appSettings.mainDBPath.isEmpty()) + messageBox("توجه", "فایل پایگاه داده یافت نشد!
لطفا از طریق گزینهٔ باز کردن در منوی پرونده، فایل پایگاه داده را انتخاب کنید؛ یا از طریق گزینهٔ دانلود از مخزن در منوی ابزارها، پایگاه داده خود را بسازید.", Warning, this); +} diff --git a/src/mainwindow_search_form.cpp b/src/mainwindow_search_form.cpp new file mode 100644 index 0000000..7c5f07b --- /dev/null +++ b/src/mainwindow_search_form.cpp @@ -0,0 +1,179 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "searchform.h" + +#include + +void MainWindow::on_btnAdvancedSearch_clicked() +{ + if(!searchAction->isChecked()) + ui->btnSearchForm->toggled(true); + + SearchForm *searchForm = new SearchForm(&appSettings, this); + connect(searchForm, &SearchForm::sigSearch, this, &MainWindow::slotSearch); + connect(searchForm, &SearchForm::sigSearchTableChanged, this, &MainWindow::slotSearchTableChanged); + searchForm->show(); +} + +void MainWindow::slotSearch() +{ + ui->lineEditSearch->setText(appSettings.ss.searchPhrase); + on_btnSearch_clicked(); +} + +void MainWindow::on_btnSearch_clicked() +{ + if(appSettings.ss.isSearching) + { + appSettings.ss.searchState = false; + return; + } + + appSettings.ss.isSearching = true; + appSettings.ss.searchPhrase = ui->lineEditSearch->text(); + QString strQuery = searchStrQuery(appSettings.mainDB, appSettings.ss.searchPhrase, appSettings.ss.allItemsSelected, appSettings.ss.poetID, appSettings.ss.table, appSettings.ss.skipDiacritics, appSettings.ss.skipCharTypes); + + qDebug().noquote() << strQuery; + + Worker *worker = new Worker(Worker::Searcher, &appSettings, ui->tableWidget, strQuery); + QThread *thread = new QThread; + worker->moveToThread(thread); + + connect(thread, &QThread::started, worker, &Worker::process); + connect(worker, &Worker::finished, this, &MainWindow::threadFinished); + connect(worker, &Worker::finished, thread, &QThread::quit); + connect(worker, &Worker::finished, worker, &Worker::deleteLater); + connect(thread, &QThread::finished, thread, &QThread::deleteLater); + + thread->start(); + + ui->btnSearch->setText(" توقف "); + ui->toolButton->setEnabled(false); + ui->btnAdvancedSearch->setEnabled(false); + ui->btnExportXML->setEnabled(false); + ui->lineEditSearch->setReadOnly(true); + ui->progressBarSearch->show(); +} + +void MainWindow::threadFinished(Worker::WorkerType type, QVariant result) +{ + if(type == Worker::Searcher) + { + qDebug().noquote() << "Worker: Searcher"; + createHistorySearch(); + + ui->btnSearch->setText(" جست‌وجو "); + ui->toolButton->setEnabled(true); + ui->btnAdvancedSearch->setEnabled(true); + ui->btnExportXML->setEnabled(true); + ui->lineEditSearch->setReadOnly(false); + ui->progressBarSearch->hide(); + + appSettings.ss.isSearching = false; + + if(!result.toString().isEmpty()) + messageBox("گزارش", result.toString(), Information, this); + } +} + +void MainWindow::createHistorySearch() +{ + { // History Block + if(appSettings.ss.table == VerseTable) + searchHistory.table = "verse"; + else if(appSettings.ss.table == PoemTable) + searchHistory.table = "poem"; + else if(appSettings.ss.table == CatTable) + searchHistory.table = "cat"; + + searchHistory.poetID.clear(); + if(appSettings.ss.allItemsSelected) + { + QSqlQuery query("SELECT id FROM poet ORDER BY id"); + while(query.next()) + searchHistory.poetID << query.value(0).toString(); + } + else + { + searchHistory.poetID = appSettings.ss.poetID; + std::sort(searchHistory.poetID.begin(), searchHistory.poetID.end(), idComp); + } + + searchHistory.allItemsSelected = appSettings.ss.allItemsSelected; + searchHistory.date = nowDate(); + searchHistory.time = nowTime(); + searchHistory.skipDiacritics = appSettings.ss.skipDiacritics; + searchHistory.skipCharTypes = appSettings.ss.skipCharTypes; + searchHistory.searchPhrase = appSettings.ss.searchPhrase; + searchHistory.count = ui->tableWidget->rowCount(); + } // History Block +} + +void MainWindow::searchRangeMenuCreator() +{ + toolButtonMenu = new QMenu("Menu"); + catAction = new QAction("جستجو در فهرست‌ها"); + poemAction = new QAction("جستجو در عنوان‌ها"); + verseAction = new QAction("جستجو در متن‌ها"); + + catAction->setCheckable(true); + poemAction->setCheckable(true); + verseAction->setCheckable(true); + + toolButtonMenu->addAction(catAction); + toolButtonMenu->addAction(poemAction); + toolButtonMenu->addAction(verseAction); + + ui->toolButton->setMenu(toolButtonMenu); + + connect(catAction, &QAction::triggered, this, &MainWindow::actionCat); + connect(poemAction, &QAction::triggered, this, &MainWindow::actionPoem); + connect(verseAction, &QAction::triggered, this, &MainWindow::actionVerse); + + appSettings.ss.table = VerseTable; + slotSearchTableChanged(); +} + +void MainWindow::slotSearchTableChanged() +{ + if(appSettings.ss.table == CatTable) + actionCat(); + else if(appSettings.ss.table == PoemTable) + actionPoem(); + else if(appSettings.ss.table == VerseTable) + actionVerse(); +} + +void MainWindow::actionCat() +{ + appSettings.ss.table = CatTable; + catAction->setChecked(true); + poemAction->setChecked(false); + verseAction->setChecked(false); +} + +void MainWindow::actionPoem() +{ + appSettings.ss.table = PoemTable; + catAction->setChecked(false); + poemAction->setChecked(true); + verseAction->setChecked(false); +} + +void MainWindow::actionVerse() +{ + appSettings.ss.table = VerseTable; + catAction->setChecked(false); + poemAction->setChecked(false); + verseAction->setChecked(true); +} diff --git a/src/searchexamplesform.cpp b/src/searchexamplesform.cpp new file mode 100644 index 0000000..1b2a2ac --- /dev/null +++ b/src/searchexamplesform.cpp @@ -0,0 +1,66 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "searchexamplesform.h" +#include "ui_searchexamplesform.h" + +#include + +SearchExamplesForm::SearchExamplesForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::SearchExamplesForm) +{ + ui->setupUi(this); +} + +SearchExamplesForm::SearchExamplesForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::SearchExamplesForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("نمونه‌های جست‌وجو"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + + setHtml(); +} + +SearchExamplesForm::~SearchExamplesForm() +{ + delete ui; +} + +void SearchExamplesForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + close(); +} + +void SearchExamplesForm::setHtml() +{ + QString html; + QString textColor = appSettings->isDarkMode ? "white" : "black"; + QFile file(":/files/html/search_examples.html"); + + file.open(QIODevice::ReadOnly | QIODevice::Text); + html = file.readAll(); + file.close(); + + html.replace(QRegularExpression("\\$\\{FontName\\}"), appSettings->viewFN); + html.replace(QRegularExpression("\\$\\{FontSize\\}"), QString::number(appSettings->viewFS.toDouble())); + html.replace(QRegularExpression("\\$\\{TopicFontSize\\}"), ratioFontSize(appSettings->viewFS.toDouble(), 1.25)); + html.replace(QRegularExpression("\\$\\{TextColor\\}"), textColor); + + ui->textBrowser->setHtml(html); +} diff --git a/src/searchexamplesform.h b/src/searchexamplesform.h new file mode 100644 index 0000000..a5992c7 --- /dev/null +++ b/src/searchexamplesform.h @@ -0,0 +1,41 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef SEARCHEXAMPLESFORM_H +#define SEARCHEXAMPLESFORM_H + +#include +#include "common_functions.h" + +namespace Ui { +class SearchExamplesForm; +} + +class SearchExamplesForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit SearchExamplesForm(QWidget *parent = nullptr); + SearchExamplesForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~SearchExamplesForm(); + +public slots: + void setHtml(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + +private: + Ui::SearchExamplesForm *ui; + AppSettings *appSettings; +}; + +#endif // SEARCHEXAMPLESFORM_H diff --git a/src/searchexamplesform.ui b/src/searchexamplesform.ui new file mode 100644 index 0000000..fbcd5d9 --- /dev/null +++ b/src/searchexamplesform.ui @@ -0,0 +1,39 @@ + + + SearchExamplesForm + + + + 0 + 0 + 792 + 457 + + + + + Sahel + 11 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + classView + + + + + + + + + diff --git a/src/searchform.cpp b/src/searchform.cpp new file mode 100644 index 0000000..33a0727 --- /dev/null +++ b/src/searchform.cpp @@ -0,0 +1,288 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "searchform.h" +#include "ui_searchform.h" +#include "event_functions.h" +#include "searchexamplesform.h" + +#include + +SearchForm::SearchForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::SearchForm) +{ + ui->setupUi(this); +} + +SearchForm::SearchForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::SearchForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("جست‌وجوی پیشرفته"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + + searchRangeMenuCreator(); + listWidgetPoetList(ui->listWidget, appSettings->mainDB, true); + ui->labelTotal->setText(QString("تعداد کل: %1 مورد ").arg(ui->listWidget->count())); + + for(int i = 0; i < ui->listWidget->count(); i++) + if(appSettings->ss.poetID.contains(ui->listWidget->item(i)->data(Qt::UserRole).toString())) + ui->listWidget->item(i)->setCheckState(Qt::Checked); + fromFormLoad = false; + labelUpdate(); + + skipDiacritics = appSettings->ss.skipDiacritics; + skipCharTypes = appSettings->ss.skipCharTypes; + ui->skipDiacriticsCheckBox->setChecked(skipDiacritics); + ui->skipCharTypesCheckBox->setChecked(skipCharTypes); + + lineEditDirectionCorrector(ui->lineEditOr); + lineEditDirectionCorrector(ui->lineEditNeg); + lineEditDirectionCorrector(ui->lineEditHash); + lineEditDirectionCorrector(ui->lineEditPlus); + lineEditDirectionCorrector(ui->lineEditExact); + lineEditDirectionCorrector(ui->lineEditOrder); + ui->lineEditHash->setEnabled(false); + + connect(new ZWNJPress(ui->lineEditOr), &ZWNJPress::zwnjPressed, this, &SearchForm::lineEditsZWNJPressed); + connect(new ZWNJPress(ui->lineEditNeg), &ZWNJPress::zwnjPressed, this, &SearchForm::lineEditsZWNJPressed); + connect(new ZWNJPress(ui->lineEditHash), &ZWNJPress::zwnjPressed, this, &SearchForm::lineEditsZWNJPressed); + connect(new ZWNJPress(ui->lineEditPlus), &ZWNJPress::zwnjPressed, this, &SearchForm::lineEditsZWNJPressed); + connect(new ZWNJPress(ui->lineEditExact), &ZWNJPress::zwnjPressed, this, &SearchForm::lineEditsZWNJPressed); + connect(new ZWNJPress(ui->lineEditOrder), &ZWNJPress::zwnjPressed, this, &SearchForm::lineEditsZWNJPressed); +} + +SearchForm::~SearchForm() +{ + delete ui; +} + +void SearchForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + on_btnClose_clicked(); + else if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) + on_btnSearch_clicked(); +} + +void SearchForm::on_btnClose_clicked() +{ + close(); + if(!strSearch.isEmpty()) + { + appSettings->ss.searchPhrase = strSearch; + emit sigSearch(); + } +} + +void SearchForm::on_listWidget_doubleClicked(const QModelIndex &index) +{ + int row = index.row(); + + if(ui->listWidget->item(row)->checkState() == Qt::Unchecked) + ui->listWidget->item(row)->setCheckState(Qt::Checked); + else + ui->listWidget->item(row)->setCheckState(Qt::Unchecked); +} + +void SearchForm::on_listWidget_itemChanged(QListWidgetItem *item) +{ + if(!fromFormLoad) + { + ui->selectAllCheckBox->setChecked(false); + ui->selectNoneCheckBox->setChecked(false); + + if(item->checkState() == Qt::Checked) + appSettings->ss.poetID << item->data(Qt::UserRole).toString(); + else + appSettings->ss.poetID.removeOne(item->data(Qt::UserRole).toString()); + + labelUpdate(); + } +} + +void SearchForm::on_selectAllCheckBox_clicked(bool checked) +{ + ui->selectNoneCheckBox->setChecked(false); + + if(checked) + { + for(int i = 0; i < ui->listWidget->count(); i++) + ui->listWidget->item(i)->setCheckState(Qt::Checked); + ui->selectAllCheckBox->setChecked(true); + } + else + for(int i = 0; i < ui->listWidget->count(); i++) + ui->listWidget->item(i)->setCheckState(Qt::Unchecked); +} + +void SearchForm::on_selectNoneCheckBox_clicked(bool checked) +{ + Q_UNUSED(checked); // (void)checked; + + ui->selectAllCheckBox->setChecked(false); + + for(int i = 0; i < ui->listWidget->count(); i++) + ui->listWidget->item(i)->setCheckState(Qt::Unchecked); + ui->selectNoneCheckBox->setChecked(true); +} + +void SearchForm::labelUpdate() +{ + ui->labelSelectedCount->setText(QString("انتخاب‌شده: %1 مورد ").arg(appSettings->ss.poetID.count())); + if(!appSettings->ss.poetID.count()) + ui->labelSelectedCount->setText("انتخاب‌شده: "); +} + +void SearchForm::lineEditsZWNJPressed(QObject *object, Qt::KeyboardModifier key) +{ + Q_UNUSED(key); // (void)key; + static_cast(object)->insert(Constants::ZWNJ); +} + +void SearchForm::on_skipDiacriticsCheckBox_clicked(bool checked) +{ + skipDiacritics = checked; +} + +void SearchForm::on_skipCharTypesCheckBox_clicked(bool checked) +{ + skipCharTypes = checked; +} + +void SearchForm::on_btnSearch_clicked() +{ + QString str; + + if(ui->checkBoxHash->isChecked()) + { + str = ui->lineEditHash->text().trimmed().isEmpty() ? "" : "#" + ui->lineEditHash->text().trimmed(); + } + else + { + QString strOr; + strOr = ui->lineEditOr->text().split(QRegularExpression("[\\s\\|]"), SKIP_EMPTY_PARTS).join(" | "); + str = ui->lineEditPlus->text().split(QRegularExpression("[\\s\\+]"), SKIP_EMPTY_PARTS).join(" + "); + str += (str.trimmed().isEmpty() || ui->lineEditExact->text().trimmed().isEmpty() ? "" : " + ") + (ui->lineEditExact->text().trimmed().isEmpty() ? "" : QString("\"%1\"").arg(ui->lineEditExact->text())); + str += (str.trimmed().isEmpty() || ui->lineEditOrder->text().trimmed().isEmpty() ? "" : " + ") + ui->lineEditOrder->text().split(QRegularExpression("[\\s]|\\+\\+"), SKIP_EMPTY_PARTS).join(" ++ "); + str += str.trimmed().isEmpty() || ui->lineEditNeg->text().isEmpty() ? "" : " - " + ui->lineEditNeg->text().split(QRegularExpression("[\\s\\-]"), SKIP_EMPTY_PARTS).join(" - "); + str = (strOr.trimmed().isEmpty() ? "" : strOr) + (str.trimmed().isEmpty() || strOr.trimmed().isEmpty() ? "" : " | ") + str; + } + + strSearch = str.trimmed(); + on_btnOK_clicked(); +} + +void SearchForm::on_btnOK_clicked() +{ + int poetCount = appSettings->ss.poetID.count(); + if(poetCount == 0 || poetCount == ui->listWidget->count()) + appSettings->ss.allItemsSelected = true; + else + appSettings->ss.allItemsSelected = false; + + if(appSettings->ss.allItemsSelected) + appSettings->ss.poetID.clear(); + + appSettings->ss.skipDiacritics = skipDiacritics; + appSettings->ss.skipCharTypes = skipCharTypes; + on_btnClose_clicked(); +} + +void SearchForm::on_checkBoxHash_toggled(bool checked) +{ + if(checked) + { + ui->lineEditHash->setEnabled(true); + ui->lineEditOr->setEnabled(false); + ui->lineEditNeg->setEnabled(false); + ui->lineEditPlus->setEnabled(false); + ui->lineEditExact->setEnabled(false); + ui->lineEditOrder->setEnabled(false); + } + else + { + ui->lineEditHash->setEnabled(false); + ui->lineEditOr->setEnabled(true); + ui->lineEditNeg->setEnabled(true); + ui->lineEditPlus->setEnabled(true); + ui->lineEditExact->setEnabled(true); + ui->lineEditOrder->setEnabled(true); + } +} + +void SearchForm::on_btnExamples_clicked() +{ + SearchExamplesForm *searchExamplesForm = new SearchExamplesForm(appSettings, this); + searchExamplesForm->show(); +} + +void SearchForm::searchRangeMenuCreator() +{ + QMenu *toolButtonMenu = new QMenu("Menu"); + catAction = new QAction("جستجو در فهرست‌ها"); + poemAction = new QAction("جستجو در عنوان‌ها"); + verseAction = new QAction("جستجو در متن‌ها"); + + catAction->setCheckable(true); + poemAction->setCheckable(true); + verseAction->setCheckable(true); + + toolButtonMenu->addAction(catAction); + toolButtonMenu->addAction(poemAction); + toolButtonMenu->addAction(verseAction); + + ui->toolButton->setMenu(toolButtonMenu); + + connect(catAction, &QAction::triggered, this, &SearchForm::actionCat); + connect(poemAction, &QAction::triggered, this, &SearchForm::actionPoem); + connect(verseAction, &QAction::triggered, this, &SearchForm::actionVerse); + + if(appSettings->ss.table == CatTable) + actionCat(); + else if(appSettings->ss.table == PoemTable) + actionPoem(); + else if(appSettings->ss.table == VerseTable) + actionVerse(); +} + +void SearchForm::actionCat() +{ + appSettings->ss.table = CatTable; + catAction->setChecked(true); + poemAction->setChecked(false); + verseAction->setChecked(false); + emit sigSearchTableChanged(); +} + +void SearchForm::actionPoem() +{ + appSettings->ss.table = PoemTable; + catAction->setChecked(false); + poemAction->setChecked(true); + verseAction->setChecked(false); + emit sigSearchTableChanged(); +} + +void SearchForm::actionVerse() +{ + appSettings->ss.table = VerseTable; + catAction->setChecked(false); + poemAction->setChecked(false); + verseAction->setChecked(true); + emit sigSearchTableChanged(); +} diff --git a/src/searchform.h b/src/searchform.h new file mode 100644 index 0000000..d364a29 --- /dev/null +++ b/src/searchform.h @@ -0,0 +1,71 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef SEARCHFORM_H +#define SEARCHFORM_H + +#include +#include "common_functions.h" + +namespace Ui { +class SearchForm; +} + +class SearchForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit SearchForm(QWidget *parent = nullptr); + SearchForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~SearchForm(); + +signals: + void sigSearchTableChanged(); + void sigSearch(); + +public slots: + void labelUpdate(); + void lineEditsZWNJPressed(QObject *object, Qt::KeyboardModifier key); + void searchRangeMenuCreator(); + void actionCat(); + void actionPoem(); + void actionVerse(); + +private slots: + void on_listWidget_itemChanged(QListWidgetItem *item); + void on_listWidget_doubleClicked(const QModelIndex &index); + void on_selectAllCheckBox_clicked(bool checked); + void on_selectNoneCheckBox_clicked(bool checked); + void on_skipDiacriticsCheckBox_clicked(bool checked); + void on_skipCharTypesCheckBox_clicked(bool checked); + void on_btnOK_clicked(); + void on_btnClose_clicked(); + void on_btnSearch_clicked(); + void on_checkBoxHash_toggled(bool checked); + void on_btnExamples_clicked(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + +private: + Ui::SearchForm *ui; + AppSettings *appSettings; + bool fromFormLoad = true; + bool skipDiacritics; + bool skipCharTypes; + QString strSearch; + + QAction *catAction; + QAction *poemAction; + QAction *verseAction; +}; + +#endif // SEARCHFORM_H diff --git a/src/searchform.ui b/src/searchform.ui new file mode 100644 index 0000000..e0cd3e0 --- /dev/null +++ b/src/searchform.ui @@ -0,0 +1,465 @@ + + + SearchForm + + + + 0 + 0 + 574 + 524 + + + + + Sahel + 11 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + class2 + + + محدوده جست‌وجو + + + + + + + + + + class2 + + + انتخاب همه + + + + + + + class2 + + + هیچکدام + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Sahel + 11 + + + + class2 + + + + + + + + + + 10 + + + + classFDs + + + تعداد کل: + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + + 10 + + + + classFDs + + + انتخاب‌شده: + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + class2 + + + نادیده گرفتن حرکت کلمات + + + + + + + class2 + + + نادیده گرفتن حالت‌های یک حرف + + + + + + + + + + + + + + + + 0 + 0 + + + + class2 + + + همه این کلمات: + + + + + + + + 0 + 0 + + + + class2 + + + حداقل یکی از این کلمات: + + + + + + + + 0 + 0 + + + + class2 + + + عین این کلمه یا عبارت: + + + + + + + + 0 + 0 + + + + class2 + + + کلمات با رعایت ترتیب: + + + + + + + + 0 + 0 + + + + class2 + + + بدون این کلمات: + + + + + + + + + + + + 0 + 0 + + + + class2 + + + + + + + + 0 + 0 + + + + class2 + + + + + + + + 0 + 0 + + + + class2 + + + + + + + + 0 + 0 + + + + class2 + + + + + + + + 0 + 0 + + + + class2 + + + + + + + + + + + + + + 0 + 0 + + + + class2 + + + تعداد این کلمه یا عبارت: + + + + + + + class2 + + + + + + + + + + + + + class2 + + + جست‌وجو + + + + + + + class2 + + + ... + + + QToolButton::InstantPopup + + + Qt::ToolButtonTextOnly + + + + + + + class2 + + + مثال‌ها + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + class2 + + + تایید + + + + + + + class2 + + + بستن + + + + + + + + + + lineEditPlus + lineEditOr + lineEditExact + lineEditOrder + lineEditNeg + checkBoxHash + lineEditHash + btnSearch + toolButton + btnExamples + btnOK + btnClose + selectAllCheckBox + selectNoneCheckBox + listWidget + skipDiacriticsCheckBox + skipCharTypesCheckBox + + + + diff --git a/src/settingsform.cpp b/src/settingsform.cpp new file mode 100644 index 0000000..022647b --- /dev/null +++ b/src/settingsform.cpp @@ -0,0 +1,210 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "settingsform.h" +#include "ui_settingsform.h" +#include "appthemes.h" + +#include +#include +#include + +SettingsForm::SettingsForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::SettingsForm) +{ + ui->setupUi(this); +} + +SettingsForm::SettingsForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::SettingsForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("تنظیمات"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + setWindowModality(Qt::WindowModal); + ui->spinBoxHemistich->setMinimum(appSettings->hemistichDistanceMin); + ui->spinBoxHemistich->setMaximum(appSettings->hemistichDistanceMax); + + preCreator(); + + ui->lineEdit->setText(QDir::toNativeSeparators(appSettings->mainDBPath)); + ui->darkModeCheckBox->setChecked(appSettings->isDarkMode); + ui->spinBoxHemistich->setValue(appSettings->hemistichDistance); + ui->labelText->setText(appSettings->viewFN); + ui->spinBoxText->setValue(appSettings->viewFS.toDouble()); + ui->labelList->setText(appSettings->listFN); + ui->spinBoxList->setValue(appSettings->listFS.toDouble()); + ui->labelGlo->setText(appSettings->appFN); + ui->spinBoxGlo->setValue(appSettings->appFS.toDouble()); + + if(appSettings->viewFN != "Sahel") + ui->radioTextSys->setChecked(true); + if(appSettings->listFN != "Sahel") + ui->radioListSys->setChecked(true); + if(appSettings->appFN != "Sahel") + ui->radioGloSys->setChecked(true); +} + +SettingsForm::~SettingsForm() +{ + delete ui; +} + +void SettingsForm::preCreator() +{ + preMainDBPath = appSettings->mainDBPath; + preIsDarkMode = appSettings->isDarkMode; + preHemistichDistance = appSettings->hemistichDistance; + preViewFN = appSettings->viewFN; + preViewFS = appSettings->viewFS; + preListFN = appSettings->listFN; + preListFS = appSettings->listFS; + preAppFN = appSettings->appFN; + preAppFS = appSettings->appFS; +} + +void SettingsForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Escape) + on_btnClose_clicked(); +} + +void SettingsForm::on_btnClose_clicked() +{ + close(); +} + +void SettingsForm::on_btnText_clicked() +{ + bool ok; + QFont font = QFontDialog::getFont(&ok, QFont(appSettings->viewFN, (int)ui->spinBoxText->text().toDouble()), this); + if(ok) + { + ui->labelText->setText(font.family()); + ui->spinBoxText->setValue(font.pointSize()); + ui->radioTextSys->setChecked(true); + } +} + +void SettingsForm::on_btnList_clicked() +{ + bool ok; + QFont font = QFontDialog::getFont(&ok, QFont(appSettings->listFN, (int)ui->spinBoxList->text().toDouble()), this); + if(ok) + { + ui->labelList->setText(font.family()); + ui->spinBoxList->setValue(font.pointSize()); + ui->radioListSys->setChecked(true); + } +} + +void SettingsForm::on_btnGlo_clicked() +{ + bool ok; + QFont font = QFontDialog::getFont(&ok, QFont(appSettings->appFN, (int)ui->spinBoxGlo->text().toDouble()), this); + if(ok) + { + ui->labelGlo->setText(font.family()); + ui->spinBoxGlo->setValue(font.pointSize()); + ui->radioGloSys->setChecked(true); + } +} + +void SettingsForm::on_btnApply_clicked() +{ + appSettings->mainDBPath = QDir::fromNativeSeparators(ui->lineEdit->text()); + appSettings->isDarkMode = ui->darkModeCheckBox->isChecked(); + appSettings->hemistichDistance = ui->spinBoxHemistich->value(); + appSettings->appFN = ui->labelGlo->text(); + appSettings->appFS = ui->spinBoxGlo->text(); + appSettings->listFN = ui->labelList->text(); + appSettings->listFS = ui->spinBoxList->text(); + appSettings->viewFN = ui->labelText->text(); + appSettings->viewFS = ui->spinBoxText->text(); + appSettings->viewFSCurrent = appSettings->viewFS; + + if(appSettings->appFN != preAppFN || appSettings->appFS != preAppFS || appSettings->listFN != preListFN || + appSettings->listFS != preListFS || appSettings->viewFN != preViewFN || appSettings->viewFS != preViewFS || + appSettings->isDarkMode != preIsDarkMode || appSettings->hemistichDistance != preHemistichDistance) + { + applyChanges(); + emit sigTabTheme(); + emit sigTabFormSize(); + emit sigAdjustMenuFont(); + } + + if(appSettings->mainDBPath != preMainDBPath) + emit sigMainDBChanged(); + + preCreator(); +} + +void SettingsForm::applyChanges() +{ + QString addStyle = appStyleSheet(appSettings->appFN, appSettings->appFS, appSettings->listFN, appSettings->listFS, appSettings->viewFN, appSettings->viewFSCurrent); + if(appSettings->isDarkMode) + QApplication::setStyle(new DarkStyle(addStyle)); + else + QApplication::setStyle(new LightStyle(addStyle)); +} + +void SettingsForm::on_btnOK_clicked() +{ + on_btnApply_clicked(); + on_btnClose_clicked(); +} + +void SettingsForm::on_btnDefault_clicked() +{ + ui->darkModeCheckBox->setChecked(false); + ui->spinBoxHemistich->setValue(60); + ui->labelGlo->setText("Sahel"); + ui->spinBoxGlo->setValue(10.5); + ui->labelText->setText("Sahel"); + ui->spinBoxText->setValue(11); + ui->labelList->setText("Sahel"); + ui->spinBoxList->setValue(11); + + on_btnApply_clicked(); +} + +void SettingsForm::on_btnBrowse_clicked() +{ + QString filter = "Database files (*.s3db *.db *.sqlite3 *.sqlite *.gdb);;All files (*.*)"; + QString file_name = QFileDialog::getOpenFileName(this, "Open", QDir::homePath(), filter); + if(!file_name.isEmpty()) + { + if(isStdGanjoorDB(file_name)) + ui->lineEdit->setText(QDir::toNativeSeparators(file_name)); + else + messageBox("خطا", "خطا:
فایل انتخاب‌شده قالب استانداردی ندارد!", Critical, this); + } +} + +void SettingsForm::on_radioTextSahel_clicked() +{ + ui->labelText->setText("Sahel"); +} + +void SettingsForm::on_radioListSahel_clicked() +{ + ui->labelList->setText("Sahel"); +} + +void SettingsForm::on_radioGloSahel_clicked() +{ + ui->labelGlo->setText("Sahel"); +} diff --git a/src/settingsform.h b/src/settingsform.h new file mode 100644 index 0000000..8bd474c --- /dev/null +++ b/src/settingsform.h @@ -0,0 +1,71 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef SETTINGSFORM_H +#define SETTINGSFORM_H + +#include +#include "common_functions.h" + +namespace Ui { +class SettingsForm; +} + +class SettingsForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit SettingsForm(QWidget *parent = nullptr); + SettingsForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~SettingsForm(); + +signals: + void sigMainDBChanged(); + void sigTabTheme(); + void sigTabFormSize(); + void sigAdjustMenuFont(); + +public slots: + void applyChanges(); + void preCreator(); + +private slots: + void on_btnApply_clicked(); + void on_btnOK_clicked(); + void on_btnClose_clicked(); + void on_btnDefault_clicked(); + void on_btnBrowse_clicked(); + void on_btnGlo_clicked(); + void on_btnText_clicked(); + void on_btnList_clicked(); + void on_radioTextSahel_clicked(); + void on_radioListSahel_clicked(); + void on_radioGloSahel_clicked(); + +protected: + void keyPressEvent(QKeyEvent *e) override; + +private: + Ui::SettingsForm *ui; + AppSettings *appSettings; + + QString preMainDBPath; + QString preAppFN; + QString preAppFS; + QString preListFN; + QString preListFS; + QString preViewFN; + QString preViewFS; + bool preIsDarkMode; + int preHemistichDistance; +}; + +#endif // SETTINGSFORM_H diff --git a/src/settingsform.ui b/src/settingsform.ui new file mode 100644 index 0000000..72b4eac --- /dev/null +++ b/src/settingsform.ui @@ -0,0 +1,473 @@ + + + SettingsForm + + + + 0 + 0 + 678 + 383 + + + + + Sahel + 11 + + + + MainWindow + + + Qt::RightToLeft + + + + + + + + + + + class2 + + + فونت نمایش متون + + + + + + + + class2 + + + فونت ساحل + + + true + + + + + + + class2 + + + سیستمی + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + class2 + + + + + + + + + + class2 + + + 1 + + + 1.000000000000000 + + + 0.100000000000000 + + + + + + + class2 + + + انتخاب + + + + + + + + + + + + class2 + + + فونت نمایش لیست + + + + + + + + class2 + + + فونت ساحل + + + true + + + + + + + class2 + + + سیستمی + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + class2 + + + + + + + + + + class2 + + + 1 + + + 1.000000000000000 + + + 0.100000000000000 + + + + + + + class2 + + + انتخاب + + + + + + + + + + + + class2 + + + فونت سراسری + + + + + + + + class2 + + + فونت ساحل + + + true + + + + + + + class2 + + + سیستمی + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + class2 + + + + + + + + + + class2 + + + 1 + + + 1.000000000000000 + + + 0.100000000000000 + + + + + + + class2 + + + انتخاب + + + + + + + + + + + + + + + + class2 + + + حالت شب + + + + + + + + 0 + 0 + + + + class2 + + + فاصلهٔ بین مصرع‌ها در نمایش کنار هم: + + + + + + + + 0 + 0 + + + + class2 + + + 200 + + + 2 + + + 60 + + + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 0 + 0 + + + + + + + + + + class2 + + + مسیر پایگاه داده: + + + + + + + class2 + + + color: rgb(255, 255, 255); +background-color: rgb(21, 21, 21); + + + databasePath + + + false + + + true + + + + + + + class2 + + + مرور + + + + + + + + + + + class2 + + + اعمال + + + + + + + class2 + + + انصراف + + + + + + + class2 + + + تایید + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + class2 + + + بازگشت به پیش‌فرض + + + + + + + + + + + + + diff --git a/src/tabform.cpp b/src/tabform.cpp new file mode 100644 index 0000000..36c4f69 --- /dev/null +++ b/src/tabform.cpp @@ -0,0 +1,234 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "tabform.h" +#include "ui_tabform.h" +#include "event_functions.h" + +TabForm::TabForm(QWidget *parent) : + QWidget(parent), + ui(new Ui::TabForm) +{ + ui->setupUi(this); +} + +TabForm::TabForm(AppSettings *appSettings, QWidget *parent) : + QWidget(parent), + ui(new Ui::TabForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + ui->textBrowser->hide(); + ui->labelhr->hide(); + + ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->textBrowser, &QTextBrowser::customContextMenuRequested, this, &TabForm::contextMenuTextBrowser); + + ui->label->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->label, &QLabel::customContextMenuRequested, this, &TabForm::contextMenuLabel); + + connect(this, SIGNAL(sigTabLastLevelIDChanged()), parent, SLOT(slotTabLastLevelIDChanged())); + connect(this, SIGNAL(sigBookmarkChanged()), parent, SLOT(slotBookmarkChanged())); + connect(this, SIGNAL(sigSelectedText(const QString &)), parent, SLOT(slotSelectedText(const QString &))); + connect(new KeyPress(ui->listWidget), &KeyPress::keyPressed, this, &TabForm::listWidgetKeyPressed); + connect(new KeyPress(ui->textBrowser), &KeyPress::keyPressed, this, &TabForm::textBrowserKeyPressed); +} + +TabForm::~TabForm() +{ + delete ui; +} + +void TabForm::slotSetTabContent(const QString &levelID, bool setFocusListWidget, bool rememberScrollBarValue, const QStringList &highlightText, const QString &bookmarkVerseID) +{ + setContents(levelID, true, rememberScrollBarValue, highlightText, bookmarkVerseID); + if(setFocusListWidget) + { + ui->listWidget->setFocus(); + ui->listWidget->setCurrentRow(0); + } +} + +void TabForm::on_listWidget_doubleClicked(const QModelIndex &index) +{ + QString levelID(index.data(Qt::UserRole).toString()); + previousItemRow << index.row(); + setContents(levelID, false); +} + +void TabForm::on_label_linkActivated(const QString &link) +{ + setContents(link); + ui->listWidget->setFocus(); +} + +void TabForm::setContents(const QString &levelID, bool clearPreItemRow, bool rememberScrollBarValue, const QStringList &highlightText, const QString &bookmarkVerseID) +{ + const QString level(levelID.left(1)); + const QString id(levelID.right(levelID.size() - 2)); + + GanjoorPath gp = recursiveIDs(appSettings->mainDB, level, id); + int iLast = gp.text.count() - 1; + + appSettings->tabCurrentPoem.remove(this); + + if(iLast < 0) + return; + + ui->label->setText(getHyperLink(gp)); + + if(!appSettings->isDarkMode) + ui->labelhr->show(); + + if(clearPreItemRow) + previousItemRow.clear(); + + if(level == "1" || level == "2") + { + listWidgetItemList(ui->listWidget, appSettings->mainDB, id); + + ui->listWidget->show(); + ui->textBrowser->hide(); + ui->textBrowser->clear(); // Increase the speed of changing theme + } + else if(level == "3") + { + int pos = ui->textBrowser->verticalScrollBar()->value(); + if(appSettings->pDisplayType == Tak) + ui->textBrowser->setHtml(oldStyleHtml(appSettings->mainDB, id, appSettings->viewFSCurrent, appSettings->isDarkMode, highlightText, appSettings->showBookmarks, bookmarkVerseID)); + else if(appSettings->pDisplayType == Joft) + ui->textBrowser->setHtml(newStyleHtml(appSettings->mainDB, id, appSettings->viewFSCurrent, appSettings->isDarkMode, highlightText, appSettings->showBookmarks, bookmarkVerseID, appSettings->hemistichDistance)); + ui->listWidget->hide(); + ui->listWidget->clear(); // Increase the speed of changing theme + ui->textBrowser->show(); + ui->textBrowser->setFocus(); + if(rememberScrollBarValue) + ui->textBrowser->verticalScrollBar()->setValue(pos); + + appSettings->tabCurrentPoem.insert(this, tabPath.last()); + } + + appSettings->tabLastLevelID.insert(this, tabPath.last()); + emit sigTabLastLevelIDChanged(); +} + +void TabForm::slotTabFormSize() +{ + if(appSettings->tabCurrentPoem.contains(this)) + setContents(appSettings->tabCurrentPoem.value(this), false); +} + +void TabForm::slotTabTheme() +{ + slotTabHeaderLabel(); + if(appSettings->tabCurrentPoem.contains(this)) + setContents(appSettings->tabCurrentPoem.value(this), false); +} + +void TabForm::slotTabHeaderLabel() +{ + QString hyperLinkText(ui->label->text()); + ui->label->clear(); + ui->label->setText(hyperLinkText); + + if(!appSettings->isDarkMode && appSettings->tabLastLevelID.contains(this)) + ui->labelhr->show(); + else + ui->labelhr->hide(); +} + +QString TabForm::getHyperLink(const GanjoorPath &gp) +{ + QString hyperLinkText; + + for(int i = gp.text.count() - 1; i >= 0; i--) + { + QString level = gp.level[i]; + QString title = gp.text[i]; + QString id = gp.id[i]; + QString new_title(title); + + if(level == "1") + { + tabPath.clear(); + tabPath << level + "-" + id; + hyperLinkText = "\n"; + hyperLinkText += "

" + title + "

\n"; + hyperLinkText += ""; + } + else + { + if(level == "3") + new_title = spaceReplace(title, "…", 12); + tabPath << level + "-" + id; + hyperLinkText.replace("

", " | " + new_title + "

"); + } + } + + return hyperLinkText; +} + +void TabForm::listWidgetKeyPressed(QObject *object, QKeyEvent *event) +{ + Q_UNUSED(object); // (void)object; + + int key = event->key(); + + if(key == Qt::Key_Return || key == Qt::Key_Enter || key == Qt::Key_Left) + { + if(ui->listWidget->currentRow() >= 0) + on_listWidget_doubleClicked(ui->listWidget->currentIndex()); + } + else if(key == Qt::Key_Space && ui->listWidget->count() && ui->listWidget->currentRow() < 0) + { + ui->listWidget->setCurrentRow(0); + } + else if(key == Qt::Key_Right) + { + if(tabPath.count() > 1) + { + tabPath.removeLast(); + setContents(tabPath.last(), false); + + if(previousItemRow.isEmpty()) + { + ui->listWidget->setCurrentRow(0); + } + else + { + ui->listWidget->setCurrentRow(previousItemRow.last()); + previousItemRow.removeLast(); + } + } + else + { + appSettings->listWidget->setFocus(); + } + } +} + +void TabForm::textBrowserKeyPressed(QObject *object, QKeyEvent *event) +{ + Q_UNUSED(object); // (void)object; + + int key = event->key(); + + if(key == Qt::Key_Right) + { + listWidgetKeyPressed(nullptr, event); + ui->listWidget->setFocus(); + } +} diff --git a/src/tabform.h b/src/tabform.h new file mode 100644 index 0000000..3930655 --- /dev/null +++ b/src/tabform.h @@ -0,0 +1,75 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef TABFORM_H +#define TABFORM_H + +#include +#include +#include "common_functions.h" + +namespace Ui { +class TabForm; +} + +class TabForm : public QWidget +{ + Q_OBJECT + +public: + explicit TabForm(QWidget *parent = nullptr); + TabForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~TabForm(); + +signals: + void sigTabLastLevelIDChanged(); + void sigBookmarkChanged(); + void sigSelectedText(const QString &text); + +public slots: + void slotSetTabContent(const QString &levelID, bool setFocusListWidget = false, bool rememberScrollBarValue = false, const QStringList &highlightText = QStringList(), const QString &bookmarkVerseID = QString()); + void slotTabFormSize(); + void slotTabTheme(); + void slotTabHeaderLabel(); + void listWidgetKeyPressed(QObject *object, QKeyEvent *event); + void textBrowserKeyPressed(QObject *object, QKeyEvent *event); + void contextMenuTextBrowser(const QPoint &pos); + void contextMenuLabel(const QPoint &pos); + void setContents(const QString &levelID, bool clearPreItemRow = true, bool rememberScrollBarValue = false, const QStringList &highlightText = QStringList(), const QString &bookmarkVerseID = QString()); + QString getHyperLink(const GanjoorPath &gp); + void actionCopy(); + void actionCopyLabel(); + void actionCopyAddress(); + void actionCopyAddressLabel(); + void actionSelectAll(); + void actionSelectAllLabel(); + void actionBookmark(); + void actionAbjad(); + +private slots: + void on_listWidget_doubleClicked(const QModelIndex &index); + void on_label_linkActivated(const QString &link); + void on_textBrowser_highlighted(const QUrl &arg1); + void on_label_linkHovered(const QString &link); + void on_textBrowser_selectionChanged(); + +private: + Ui::TabForm *ui; + AppSettings *appSettings; + QList previousItemRow; + QStringList tabPath; + + QString fullAddress; + QString hrefAnchor; + QString hrefAnchorLabel; + QString verse_id; +}; + +#endif // TABFORM_H diff --git a/src/tabform.ui b/src/tabform.ui new file mode 100644 index 0000000..a0518d2 --- /dev/null +++ b/src/tabform.ui @@ -0,0 +1,93 @@ + + + TabForm + + + + 0 + 0 + 512 + 342 + + + + + Sahel + 11 + + + + Form + + + Qt::RightToLeft + + + + + + + + classViewListHeader + + + Qt::RichText + + + true + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + + + + + <hr> + + + Qt::RichText + + + + + + + + + + Sahel + 11 + + + + classViewListHeader + + + QFrame::NoFrame + + + + + + + classView + + + QFrame::NoFrame + + + false + + + + + + + + + + + + diff --git a/src/tabform_context_menu.cpp b/src/tabform_context_menu.cpp new file mode 100644 index 0000000..d69718c --- /dev/null +++ b/src/tabform_context_menu.cpp @@ -0,0 +1,237 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "tabform.h" +#include "ui_tabform.h" +#include "abjadformmini.h" + +#include +#include +#include +#include + +void TabForm::contextMenuTextBrowser(const QPoint &pos) +{ + Q_UNUSED(pos); // (void)pos; + + fullAddress.clear(); + + QMenu *contextMenu; + QAction *bookmarkAction; + QAction *abjadAction; + QAction *copyAction; + QAction *copyAddressAction; + QAction *selectAllAction; + + contextMenu = new QMenu("Context Menu", this); + abjadAction = new QAction("محاسبه ابجد", this); + copyAction = new QAction("کپی", this); + copyAddressAction = new QAction("کپی آدرس", this); + selectAllAction = new QAction("انتخاب همه", this); + + verse_id.clear(); + bool preValue = false; + if(!hrefAnchor.isEmpty()) + { + QStringList hrefAnchorList = hrefAnchor.split("-"); + if(hrefAnchorList.count() == 2) + verse_id = "-1"; + else + verse_id = hrefAnchorList.last(); + preValue = isBookmarked(appSettings->mainDB, appSettings->tabCurrentPoem.value(this), verse_id); + } + + if(preValue) + bookmarkAction = new QAction("حذف نشانه", this); + else + bookmarkAction = new QAction("نشانه‌گذاری", this); + + if(verse_id.isEmpty()) + bookmarkAction->setEnabled(false); + + if(!ui->textBrowser->textCursor().hasSelection()) + { + abjadAction->setEnabled(false); + copyAction->setEnabled(false); + } + + copyAction->setShortcut(QKeySequence("Ctrl+C")); + selectAllAction->setShortcut(QKeySequence("Ctrl+A")); + + contextMenu->addAction(bookmarkAction); + contextMenu->addSeparator(); + contextMenu->addAction(abjadAction); + contextMenu->addSeparator(); + contextMenu->addAction(copyAction); + if(QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier) && !hrefAnchor.isEmpty()) + { + QStringList hrefAnchorList = hrefAnchor.split("-"); + GanjoorPath gp = recursiveIDs(appSettings->mainDB, hrefAnchorList.at(0), hrefAnchorList.at(1)); + int iLast = gp.id.count() - 1; + for(int i = iLast; i >= 0; i--) + fullAddress += gp.id[i] + "->"; + if(hrefAnchorList.count() == 2) + fullAddress = getPoetIDByCatID(appSettings->mainDB, gp.id[iLast]) + ": " + fullAddress.left(fullAddress.size() - 2); + else + fullAddress = getPoetIDByCatID(appSettings->mainDB, gp.id[iLast]) + ": " + fullAddress.left(fullAddress.size() - 2) + ": " + hrefAnchorList.at(2) + " [" + getPositionByPoemIDVorder(appSettings->mainDB, hrefAnchorList.at(1), hrefAnchorList.at(2)) + "]"; + contextMenu->addAction(copyAddressAction); + } + contextMenu->addAction(selectAllAction); + + connect(bookmarkAction, &QAction::triggered, this, &TabForm::actionBookmark); + connect(abjadAction, &QAction::triggered, this, &TabForm::actionAbjad); + connect(copyAction, &QAction::triggered, this, &TabForm::actionCopy); + connect(copyAddressAction, &QAction::triggered, this, &TabForm::actionCopyAddress); + connect(selectAllAction, &QAction::triggered, this, &TabForm::actionSelectAll); + + contextMenu->exec(QCursor::pos()); + + disconnect(bookmarkAction, &QAction::triggered, this, &TabForm::actionBookmark); + disconnect(abjadAction, &QAction::triggered, this, &TabForm::actionAbjad); + disconnect(copyAction, &QAction::triggered, this, &TabForm::actionCopy); + disconnect(copyAddressAction, &QAction::triggered, this, &TabForm::actionCopyAddress); + disconnect(selectAllAction, &QAction::triggered, this, &TabForm::actionSelectAll); + + delete bookmarkAction; + delete abjadAction; + delete copyAction; + delete copyAddressAction; + delete selectAllAction; + delete contextMenu; +} + +void TabForm::actionCopy() +{ +// QClipboard *clipboard = QApplication::clipboard(); +// QTextDocumentFragment selectedText(ui->textBrowser->textCursor().selection()); +// clipboard->setText(selectedText.toPlainText()); + + ui->textBrowser->copy(); +} + +void TabForm::actionCopyAddress() +{ + QClipboard *clipboard = QApplication::clipboard(); + clipboard->setText(fullAddress); +} + +void TabForm::actionSelectAll() +{ + ui->textBrowser->selectAll(); +} + +void TabForm::actionBookmark() +{ + bool preValue = isBookmarked(appSettings->mainDB, appSettings->tabCurrentPoem.value(this), verse_id); + setBookmarked(appSettings->mainDB, appSettings->tabCurrentPoem.value(this), verse_id, !preValue); + + if(verse_id != "-1" && appSettings->showBookmarks) + setContents(appSettings->tabCurrentPoem.value(this), false, true); + + emit sigBookmarkChanged(); +} + +void TabForm::actionAbjad() +{ + if(!appSettings->isOpenAbjadFormMini) + { + AbjadFormMini *abjadFormMini = new AbjadFormMini(appSettings, this); + abjadFormMini->show(); + } + on_textBrowser_selectionChanged(); +} + +void TabForm::on_textBrowser_highlighted(const QUrl &arg1) +{ + hrefAnchor = arg1.toString(); +} + +void TabForm::contextMenuLabel(const QPoint &pos) +{ + Q_UNUSED(pos); // (void)pos; + + fullAddress.clear(); + + QMenu *contextMenu; + QAction *copyAction; + QAction *copyAddressAction; + QAction *selectAllAction; + + contextMenu = new QMenu("Context Menu", this); + copyAction = new QAction("کپی", this); + copyAddressAction = new QAction("کپی آدرس", this); + selectAllAction = new QAction("انتخاب همه", this); + + if(!ui->label->hasSelectedText()) + copyAction->setEnabled(false); + + copyAction->setShortcut(QKeySequence("Ctrl+C")); + selectAllAction->setShortcut(QKeySequence("Ctrl+A")); + + contextMenu->addAction(copyAction); + if(QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier) && !hrefAnchorLabel.isEmpty()) + { + QStringList hrefAnchorList = hrefAnchorLabel.split("-"); + GanjoorPath gp = recursiveIDs(appSettings->mainDB, hrefAnchorList.at(0), hrefAnchorList.at(1)); + int iLast = gp.id.count() - 1; + for(int i = iLast; i >= 0; i--) + fullAddress += gp.id[i] + "->"; + fullAddress = getPoetIDByCatID(appSettings->mainDB, gp.id[iLast]) + ": " + fullAddress.left(fullAddress.size() - 2); + contextMenu->addAction(copyAddressAction); + } + contextMenu->addAction(selectAllAction); + + connect(copyAction, &QAction::triggered, this, &TabForm::actionCopyLabel); + connect(copyAddressAction, &QAction::triggered, this, &TabForm::actionCopyAddressLabel); + connect(selectAllAction, &QAction::triggered, this, &TabForm::actionSelectAllLabel); + + contextMenu->exec(QCursor::pos()); + + disconnect(copyAction, &QAction::triggered, this, &TabForm::actionCopyLabel); + disconnect(copyAddressAction, &QAction::triggered, this, &TabForm::actionCopyAddressLabel); + disconnect(selectAllAction, &QAction::triggered, this, &TabForm::actionSelectAllLabel); + + delete copyAction; + delete copyAddressAction; + delete selectAllAction; + delete contextMenu; +} + +void TabForm::actionCopyLabel() +{ + QClipboard *clipboard = QApplication::clipboard(); + clipboard->setText(ui->label->selectedText()); +} + +void TabForm::actionCopyAddressLabel() +{ + QClipboard *clipboard = QApplication::clipboard(); + clipboard->setText(fullAddress); +} + +void TabForm::actionSelectAllLabel() +{ + QString plain = QTextDocumentFragment::fromHtml(ui->label->text()).toPlainText(); + ui->label->setSelection(0, plain.size()); +} + +void TabForm::on_label_linkHovered(const QString &link) +{ + hrefAnchorLabel = link; +} + +void TabForm::on_textBrowser_selectionChanged() +{ + if(appSettings->isOpenAbjadForm || appSettings->isOpenAbjadFormMini) + { + QTextDocumentFragment selectedText(ui->textBrowser->textCursor().selection()); + emit sigSelectedText(correctHtmlTableText(selectedText.toPlainText())); + } +} diff --git a/src/wordsearchform.cpp b/src/wordsearchform.cpp new file mode 100644 index 0000000..dd81fdc --- /dev/null +++ b/src/wordsearchform.cpp @@ -0,0 +1,137 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "wordsearchform.h" +#include "ui_wordsearchform.h" +#include "event_functions.h" + +WordSearchForm::WordSearchForm(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::WordSearchForm) +{ + ui->setupUi(this); +} + +WordSearchForm::WordSearchForm(AppSettings *appSettings, QWidget *parent) : + QMainWindow(parent), + ui(new Ui::WordSearchForm) +{ + ui->setupUi(this); + + this->appSettings = appSettings; + + appSettings->isOpenWordSearchForm = true; + setGeometry(QStyle::alignedRect(Qt::RightToLeft, Qt::AlignCenter, size(), QGuiApplication::primaryScreen()->availableGeometry())); + setWindowTitle("جست‌وجو"); + setWindowIcon(QIcon(":/files/images/ghazal-256x256.png")); + + lineEditDirectionCorrector(ui->lineEdit); + connect(new ZWNJPress(ui->lineEdit), &ZWNJPress::zwnjPressed, this, &WordSearchForm::lineEditZWNJPressed); +} + +WordSearchForm::~WordSearchForm() +{ + delete ui; +} + +void WordSearchForm::keyPressEvent(QKeyEvent *e) +{ + if(e->key() == Qt::Key_Return) + on_pushButton_clicked(); + if(e->key() == Qt::Key_Escape) + close(); +} + +void WordSearchForm::closeEvent(QCloseEvent *event) +{ + Q_UNUSED(event); // (void)event; + appSettings->isOpenWordSearchForm = false; +} + +void WordSearchForm::on_pushButton_clicked() +{ + QRegularExpression regex("^:{2}([123]\\-\\d+|\\d+)$"); // ^:{2}([123]\-\d+|\d+)$ + QRegularExpressionMatch match = regex.match(ui->lineEdit->text()); + if(match.hasMatch()) + { + if(match.captured(1).contains("-")) + { + QString levelID = match.captured(1); + QStringList list = levelID.split("-"); + + QSqlQuery query; + if(list[0] == "3") + query.exec("SELECT * FROM poem WHERE id = " + list[1]); + else + query.exec("SELECT * FROM cat WHERE id = " + list[1]); + + if(query.first()) + { + connect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), appSettings->activeTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); + emit sigSetTabContent(levelID, false, false, QStringList(), QString()); + disconnect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), appSettings->activeTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); + + GanjoorPath gp = recursiveIDs(appSettings->mainDB, levelID); + int tabIndex = appSettings->tabWidget->indexOf(appSettings->activeTab); + appSettings->tabWidget->setTabText(tabIndex, " " + gp.text[gp.text.count() - 1] + " "); + return; + } + } + else + { + QString level, id = match.captured(1); + QSqlQuery query; + query.exec("SELECT * FROM poem WHERE id = " + id); + if(query.first()) + level = "3"; + else + { + query.exec("SELECT * FROM cat WHERE id = " + id); + if(query.first()) + level = "2"; + } + + if(!level.isEmpty()) + { + connect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), appSettings->activeTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); + emit sigSetTabContent(level + "-" + id, false, false, QStringList(), QString()); + disconnect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), appSettings->activeTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); + + GanjoorPath gp = recursiveIDs(appSettings->mainDB, level + "-" + id); + int tabIndex = appSettings->tabWidget->indexOf(appSettings->activeTab); + appSettings->tabWidget->setTabText(tabIndex, " " + gp.text[gp.text.count() - 1] + " "); + return; + } + } + } + + QStringList list(textListHighlight(ui->lineEdit->text())); + + connect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), appSettings->activeTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); + emit sigSetTabContent(appSettings->tabLastLevelID.value(appSettings->activeTab), false, true, list, QString()); + disconnect(this, SIGNAL(sigSetTabContent(QString, bool, bool, QStringList, QString)), appSettings->activeTab, SLOT(slotSetTabContent(QString, bool, bool, QStringList, QString))); +} + +void WordSearchForm::lineEditZWNJPressed(QObject *object, Qt::KeyboardModifier key) +{ + Q_UNUSED(object); // (void)object; + Q_UNUSED(key); // (void)key; + checkDirection = false; + ui->lineEdit->insert(Constants::ZWNJ); +} + +void WordSearchForm::on_lineEdit_textChanged(const QString &arg1) +{ + if(checkDirection && arg1.contains(QRegularExpression("^:{2}"))) + lineEditDirectionCorrector(ui->lineEdit, Qt::LeftToRight); + else if(checkDirection) + lineEditDirectionCorrector(ui->lineEdit); + checkDirection = true; +} diff --git a/src/wordsearchform.h b/src/wordsearchform.h new file mode 100644 index 0000000..5b16637 --- /dev/null +++ b/src/wordsearchform.h @@ -0,0 +1,50 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef WORDSEARCHFORM_H +#define WORDSEARCHFORM_H + +#include +#include "common_functions.h" + +namespace Ui { +class WordSearchForm; +} + +class WordSearchForm : public QMainWindow +{ + Q_OBJECT + +public: + explicit WordSearchForm(QWidget *parent = nullptr); + WordSearchForm(AppSettings *appSettings, QWidget *parent = nullptr); + ~WordSearchForm(); + +signals: + void sigSetTabContent(const QString &levelID, bool setFocusListWidget, bool rememberScrollBarValue, const QStringList &highlightText, const QString &bookmarkVerseID); + +public slots: + void lineEditZWNJPressed(QObject *object, Qt::KeyboardModifier key); + +private slots: + void on_pushButton_clicked(); + void on_lineEdit_textChanged(const QString &arg1); + +protected: + void keyPressEvent(QKeyEvent *e) override; + void closeEvent(QCloseEvent *event) override; + +private: + Ui::WordSearchForm *ui; + AppSettings *appSettings; + bool checkDirection = true; +}; + +#endif // WORDSEARCHFORM_H diff --git a/src/wordsearchform.ui b/src/wordsearchform.ui new file mode 100644 index 0000000..be8320d --- /dev/null +++ b/src/wordsearchform.ui @@ -0,0 +1,84 @@ + + + WordSearchForm + + + + 0 + 0 + 247 + 88 + + + + + Sahel + 11 + 50 + false + + + + MainWindow + + + Qt::RightToLeft + + + + + + + + + class2 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + کلمه (کلمات) + + + + + + + + + class2 + + + بیاب + + + true + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + diff --git a/src/worker.cpp b/src/worker.cpp new file mode 100644 index 0000000..76f819a --- /dev/null +++ b/src/worker.cpp @@ -0,0 +1,123 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#include "worker.h" +#include + +Worker::Worker(const Worker::WorkerType &type, AppSettings *appSettings, const QString &filePath, bool removePreVersion, int speed) +{ + // Importer Worker + // ImporterZip Worker + + this->type = type; + this->appSettings = appSettings; + this->filePath = filePath; + this->removePreVersion = removePreVersion; + this->speed = speed; +} + +Worker::Worker(const Worker::WorkerType &type, AppSettings *appSettings, const QString &databasePath, const QStringList &poetIDs, int speed) +{ + // Exporter Worker + + this->type = type; + this->appSettings = appSettings; + this->filePath = databasePath; + this->poetIDs = poetIDs; + this->speed = speed; +} + +Worker::Worker(const Worker::WorkerType &type, AppSettings *appSettings, const QStringList &poetIDs) +{ + // Remover Worker + + this->type = type; + this->appSettings = appSettings; + this->poetIDs = poetIDs; +} + +Worker::Worker(const Worker::WorkerType &type, AppSettings *appSettings) +{ + // Vacuumer Worker + + this->type = type; + this->appSettings = appSettings; +} + +Worker::Worker(const Worker::WorkerType &type, AppSettings *appSettings, QWidget *widget, const QString &searchQuery) +{ + // Searcher Worker + + this->type = type; + this->appSettings = appSettings; + this->widget = widget; + this->searchQuery = searchQuery; +} + +void Worker::process() +{ + QVariant result; + + qRegisterMetaType >("QVector"); + qRegisterMetaType("Qt::Orientation"); + qRegisterMetaType("WorkerType"); + + if(type == Importer) + { + if(isStdGanjoorDB(filePath)) + importDatabase(appSettings->mainDB, filePath, removePreVersion, speed); + else + qDebug().noquote() << "Cannot open the input file as a database file!"; + } + else if(type == ImporterZip) + { + QDir qDir(QDir::tempPath()); + QString unzipDirName = Constants::Rosybit.toLower() + "-" + randString(); + + if(qDir.mkdir(unzipDirName)) + { + QStringList list = JlCompress::getFileList(filePath); + QStringList dbList; + + for(int i = 0; i < list.count(); i++) + if(dbExtCheck(list[i])) + dbList << list[i]; + + dbList = JlCompress::extractFiles(filePath, dbList, qDir.path() + "/" + unzipDirName); + + for(int i = 0; i < dbList.count(); i++) + if(isStdGanjoorDB(dbList[i])) + importDatabase(appSettings->mainDB, dbList[i], removePreVersion, speed); + + removeTempDir(unzipDirName); + } + } + else if(type == Exporter) + { + SqliteDB secondDB(filePath, "secondDatabase", false); + exportDatabase(appSettings->mainDB, secondDB.DB(), poetIDs, speed); + secondDB.remove(); + } + else if(type == Remover) + { + removePoet(appSettings->mainDB, poetIDs); + } + else if(type == Vacuumer) + { + QSqlQuery query(appSettings->mainDB); + result = query.exec("VACUUM"); + } + else if(type == Searcher) + { + result = searchTableWidget(appSettings, static_cast(widget), searchQuery); + } + + emit finished(type, result); +} diff --git a/src/worker.h b/src/worker.h new file mode 100644 index 0000000..aa8dae3 --- /dev/null +++ b/src/worker.h @@ -0,0 +1,55 @@ +/* + [Ghazal: The library of persian poetry] + Publisher: Rosybit + Url: http://www.rosybit.com + GitHub: https://github.com/abroshan39/ghazal + Version: 1.4 + Author: Aboutaleb Roshan [ab.roshan39@gmail.com] + License: MIT License +*/ + +#ifndef WORKER_H +#define WORKER_H + +#include +#include "common_functions.h" + +class Worker : public QObject +{ + Q_OBJECT + +public: + enum WorkerType + { + Importer, + ImporterZip, + Exporter, + Remover, + Vacuumer, + Searcher + }; + +public: + Worker(const WorkerType &type, AppSettings *appSettings, const QString &filePath, bool removePreVersion, int speed); + Worker(const WorkerType &type, AppSettings *appSettings, const QString &databasePath, const QStringList &poetIDs, int speed = 1000); + Worker(const WorkerType &type, AppSettings *appSettings, const QStringList &poetIDs); + Worker(const WorkerType &type, AppSettings *appSettings); + Worker(const WorkerType &type, AppSettings *appSettings, QWidget *widget, const QString &searchQuery); + +signals: + void finished(WorkerType, QVariant); + +public slots: + void process(); + +private: + WorkerType type; + AppSettings *appSettings; + QWidget *widget = nullptr; + QString searchQuery; + QString filePath; + bool removePreVersion; + int speed; + QStringList poetIDs; +}; +#endif // WORKER_H