diff --git a/.github/workflows/ubuntu_release.yml b/.github/workflows/ubuntu_release.yml new file mode 100644 index 000000000..72e4c8034 --- /dev/null +++ b/.github/workflows/ubuntu_release.yml @@ -0,0 +1,39 @@ +name: ubuntu_release + +on: + push: + branches: [ experimental ] + pull_request: + branches: [ experimental ] + +env: + BUILD_TYPE: Release + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Install Qt + uses: jurplel/install-qt-action@v3.1.0 + with: + version: 6.4.0 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_QT6=ON + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --verbose + + - name: Package + run: cpack -G DEB + working-directory: ${{github.workspace}}/build + + - uses: actions/upload-artifact@v3 + with: + name: mytetra_${{github.sha}}.deb + path: ${{github.workspace}}/build/mytetra*.deb diff --git a/.github/workflows/ubuntu_release_qt5.yml b/.github/workflows/ubuntu_release_qt5.yml new file mode 100644 index 000000000..2ce215134 --- /dev/null +++ b/.github/workflows/ubuntu_release_qt5.yml @@ -0,0 +1,39 @@ +name: ubuntu_release_qt5 + +on: + push: + branches: [ experimental ] + pull_request: + branches: [ experimental ] + +env: + BUILD_TYPE: Release + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Install Qt + uses: jurplel/install-qt-action@v3.1.0 + with: + version: 5.15.2 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_QT6=OFF + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --verbose + + - name: Package + run: cpack -G DEB + working-directory: ${{github.workspace}}/build + + - uses: actions/upload-artifact@v3 + with: + name: mytetra_qt5_${{github.sha}}.deb + path: ${{github.workspace}}/build/mytetra*.deb diff --git a/.github/workflows/windows_release.yml b/.github/workflows/windows_release.yml new file mode 100644 index 000000000..d526e01e9 --- /dev/null +++ b/.github/workflows/windows_release.yml @@ -0,0 +1,42 @@ +name: windows_release + +on: + push: + branches: [ experimental ] + pull_request: + branches: [ experimental ] + +env: + BUILD_TYPE: Release + +jobs: + build: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Install Qt + uses: jurplel/install-qt-action@v3.1.0 + with: + version: 6.4.0 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_SYSTEM_MIMETEX=OFF -DUSE_QT6=ON + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --verbose + + - name: Install + run: cmake --install ${{github.workspace}}/build + + - name: Package + run: windeployqt --verbose 2 --no-compiler-runtime ${{github.workspace}}/build/mytetra_distr/mytetra.exe + working-directory: ${{github.workspace}}/build + + - uses: actions/upload-artifact@v3 + with: + name: mytetra_${{github.sha}} + path: ${{github.workspace}}/build/mytetra_distr/ diff --git a/.github/workflows/windows_release_qt5.yml b/.github/workflows/windows_release_qt5.yml new file mode 100644 index 000000000..2dc131853 --- /dev/null +++ b/.github/workflows/windows_release_qt5.yml @@ -0,0 +1,42 @@ +name: windows_release_qt5 + +on: + push: + branches: [ experimental ] + pull_request: + branches: [ experimental ] + +env: + BUILD_TYPE: Release + +jobs: + build: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Install Qt + uses: jurplel/install-qt-action@v3.1.0 + with: + version: 5.15.2 + + - name: Configure CMake + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_SYSTEM_MIMETEX=OFF -DUSE_QT6=OFF + + - name: Build + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} --verbose + + - name: Install + run: cmake --install ${{github.workspace}}/build + + - name: Package + run: windeployqt --verbose 2 --no-compiler-runtime ${{github.workspace}}/build/mytetra_distr/mytetra.exe + working-directory: ${{github.workspace}}/build + + - uses: actions/upload-artifact@v3 + with: + name: mytetra_qt5_${{github.sha}} + path: ${{github.workspace}}/build/mytetra_distr/ diff --git a/.gitignore b/.gitignore index beb36d64e..ac318233f 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ qrc_mytetra.cpp /app/bin/* !/app/bin/resource !/app/bin/resource/* +!/app/bin/translations.qrc !/app/bin/mytetra.qrc !/app/bin/icons.qrc @@ -59,3 +60,4 @@ qrc_*.cpp /app/ui_* /app/user*appdatalocal* +CMakeLists.txt.user diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..a9101893a --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,116 @@ +cmake_minimum_required(VERSION 3.22) +project("mytetra" LANGUAGES "C" "CXX") + +if (NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Debug") +endif() + +set(CMAKE_C_STANDARD 17) +set(CMAKE_CXX_STANDARD 17) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules/") +include(GetGitRevisionDescription) +git_describe_working_tree(APP_VERSION) + +message("compiler: ${CMAKE_CXX_COMPILER_ID}\nbuild type: ${CMAKE_BUILD_TYPE}\napp version:${APP_VERSION}") + +if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + set(CMAKE_C_FLAGS "/W3 /WX /EHsc /O2") + set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} /permissive-") #`/permissive-` somewhy required for Qt5 build + + set(WIN_INSTALL_DIR "${CMAKE_BINARY_DIR}/mytetra_distr/") + + # add necessary MSVC libraries to windows package. windeployqt will add necessary Qt-related libraries. + set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION "${WIN_INSTALL_DIR}") + set(CMAKE_INSTALL_UCRT_LIBRARIES TRUE) + include(InstallRequiredSystemLibraries) +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + set(GCC_WARNS "-Wall -Wextra -Werror") + set(CMAKE_C_FLAGS_DEBUG "${GCC_WARNS} -O0 -ggdb3") + set(CMAKE_C_FLAGS_RELEASE "${GCC_WARNS} -O3") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}") + + include(CheckPIESupported) + check_pie_supported() # rpmlint wants PIE +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") + message(FATAL_ERROR "building under MacOS not supported") +endif() + +option(USE_QT6 "Use Qt6 instead of Qt5" ON) + +if(USE_QT6) + find_package(Qt6 COMPONENTS Core Linguist Network PrintSupport Widgets Xml REQUIRED) + set(QT_LIBS Qt6::Core Qt6::Network Qt6::PrintSupport Qt6::Widgets Qt6::Xml) +else() + find_package(Qt5 COMPONENTS Core LinguistTools Network PrintSupport Widgets Xml REQUIRED) + set(QT_LIBS Qt5::Core Qt5::Network Qt5::PrintSupport Qt5::Widgets Qt5::Xml) +endif() + +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) +set(CMAKE_AUTOUIC ON) + +option(USE_SYSTEM_MIMETEX "If off, build own version of mimetex. Major linux distros have mimetex package, so no need one more" ON) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + include(GNUInstallDirs) + set(CMAKE_INSTALL_PREFIX "/usr") + install(FILES "app/desktop/any/mytetra.desktop" DESTINATION "${CMAKE_INSTALL_DATADIR}/applications/") + install(FILES "app/desktop/mytetra.png" DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/48x48/apps/") + install(FILES "app/desktop/mytetra.svg" DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/scalable/apps/") +endif() + +add_subdirectory("app/src") +if (NOT USE_SYSTEM_MIMETEX) + add_subdirectory("thirdParty/mimetex") +endif() + +find_package(Doxygen OPTIONAL_COMPONENTS dot) +if (DOXYGEN_FOUND) + # output inside "${CMAKE_CURRENT_BINARY_DIR}/html/" + doxygen_add_docs(doc ".." WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/app/doc") +endif() + + +set(CPACK_PACKAGE_NAME "mytetra") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Personal manager for information accumulation") +set(CPACK_PACKAGE_VERSION "${APP_VERSION}") +set(CPACK_PACKAGE_HOMEPAGE_URL "https://webhamster.ru/site/page/index/articles/projectcode/105") +set(CPACK_STRIP_FILES TRUE) +set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) + +set(CPACK_RPM_PACKAGE_LICENSE "GPLv3") +set(CPACK_RPM_PACKAGE_ARCHITECTURE "x86_64") +set(CPACK_RPM_PACKAGE_DESCRIPTION "This is effective personal manager for information accumulation.") +set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "/usr/share/icons") + +string(REGEX MATCH "[0-9]+\.[0-9]+\.[0-9]+" DEBIAN_APP_VERSION "${APP_VERSION}") +set(CPACK_DEBIAN_PACKAGE_VERSION "${DEBIAN_APP_VERSION}") +set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "${CPACK_RPM_PACKAGE_DESCRIPTION}") +set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Sergey M. Stepanov ") +if(USE_QT6) + set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6,libqt6core6,libqt6gui6,libqt6network6,libqt6printsupport6,libqt6widgets6,libqt6xml6") +else() + set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6,libqt5core5a,libqt5gui5,libqt5network5,libqt5printsupport5,libqt5widgets5,libqt5xml5") +endif() +set(CPACK_GENERATOR "DEB" "RPM") +include(CPack) + + +# Use only Release build type when building packages. +# Generate packages with 'cpack -G DEB/RPM'. +# To build RPM need to install cmake gcc-c++ git rpmdevtools qt{5/6}-qtbase qt6-tools/{qt5-qttools qt5-qttools-devel qt5-linguist}. +# Recommend to check result with {rpmlint + desktop-file-utils}/lintian. +# To build DEB need to install cmake g++ linguist-qt6 qt6-base-dev qt6-l10n-tools qt6-tools-dev qt6-tools-dev-tools. +# For Qt5 version install qtbase5-dev qttools5-dev qttools5-dev-tools instead of qt6-related packages. +# If using virtual machine need to install libgl1-mesa-dev also (https://forum.qt.io/post/633525). + + +# to run static analysis: +# scan-build cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ +# scan-build make + +# TODO: +# more warnings check +# static analyzer +# option for build crypto diff --git a/README.md b/README.md index cf52025c1..a1a6ca2f2 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,13 @@ MyTetra - smart manager for information collecting MyTetra is open source and cross platform personal manager for information accumulation. It is powerful program for data memorization and structuring notes. +Build status +====================== +![ubuntu build](https://github.com/fftmp-forked/mytetra_dev/actions/workflows/ubuntu_release.yml/badge.svg?branch=experimental) +![ubuntu Qt5 build](https://github.com/fftmp-forked/mytetra_dev/actions/workflows/ubuntu_release_qt5.yml/badge.svg?branch=experimental) + +![windows build](https://github.com/fftmp-forked/mytetra_dev/actions/workflows/windows_release.yml/badge.svg?branch=experimental) +![windows Qt5 build](https://github.com/fftmp-forked/mytetra_dev/actions/workflows/windows_release_qt5.yml/badge.svg?branch=experimental) Repository mytetra_dev ====================== @@ -45,7 +52,7 @@ RUS: Основной репозитарий исходников для раз * название метода строится по принципу: этоМетодКласса; * название переменных строится по принципу: этоПеременная; * Открывающая "{" и закрывающая блок скобка "}" должны стоять на отдельных строчках. -* Каждый вновь создаваемый метод должен содержать комментарий, описывающий что делает метод. Так же желательно описать назначение параметров метода; +* Каждый вновь создаваемый метод должен содержать комментарий, описывающий что делает метод. Также желательно описать назначение параметров метода; * В заголовочном файле класса, после секции #include необходимо в комментарии написать назначение класса. * Каждый заголовочный файл должен иметь следующую конструкцию: @@ -81,7 +88,8 @@ MyTetra является программой, написанной по при В Linux сборка проводится командами: ``` -qmake . +cd +сmake make ``` @@ -92,21 +100,11 @@ make install Установленный бинарник размещается по пути: ``` -/usr/local/bin/mytetra +/usr/bin/mytetra ``` В Linux, Windows и MacOs сборку можно сделать через QtCreator. -Для этого в QtCreator надо открыть проект mytetra.pro, и выбрать: +Для этого в QtCreator надо открыть корневой CMakeLists.txt и выбрать: ``` Сборка - Собрать проект "mytetra" ``` - -Запуск -====== - -Для запуска MyTetra надо запустить собранный бинарник. -В разных операционных системах бинарник размещается по разным путям. -Для выяснения, по какому пути расположен собранный или установленный бинарник, надо просмотреть вывод сборки или вывод установки. - -Для Linux и MacOs, при сборке генерируется бинарник с именем **mytetra**. -Для Windows при сборке генерируется бинарник с именем **mytetra.exe**. diff --git a/README_ENG.md b/README_ENG.md index 69d4f3e86..3a4bd587b 100644 --- a/README_ENG.md +++ b/README_ENG.md @@ -63,7 +63,8 @@ No additional build libraries are required. In Linux, the assembly is carried out by the commands: ``` -qmake. +cd +сmake make ``` @@ -74,21 +75,11 @@ make install The installed binary is located along the path: ``` -/ usr / local / bin / mytetra +/usr/bin/mytetra ``` On Linux, Windows and MacOs, building can be done through QtCreator. -To do this, open the mytetra.pro project in QtCreator, and select: +To do this, open root CMakeLists.txt in QtCreator, and select: ``` Build - Build project "mytetra" ``` - -Running -====== - -To run MyTetra, you need to run the compiled binary. -Different operating systems place the binary in different paths. -To find out which path the built or installed binary is located in, you need to view the build output or the installation output. - -For Linux and MacOs, build generates a binary named **mytetra**. -For Windows, the build generates a binary named **mytetra.exe**. diff --git a/app/app.pro b/app/app.pro deleted file mode 100644 index d01071044..000000000 --- a/app/app.pro +++ /dev/null @@ -1,513 +0,0 @@ -# Please, set manual your target OS -# ANY_OS - for desktop Windows and Linux -# MEEGO_OS - for MEEGO -# ANDROID_OS - for Android -TARGET_OS=ANY_OS - -# Build type -# "debug" or "release" -BUILD_TYPE="debug" - -# Enable console for Windows -# 0 - disable, 1 - enable (this is for compile mytetra.exe and rename to mytetra_debug.exe) -WINDOWS_CONSOLE_ENABLE=1 - -# Profiling enable -# 0 - disable, 1 - enable -PROFILING_ENABLE=0 - - -################## -# Configure logic -################## - -message(Building running in Qt major version: $${QT_MAJOR_VERSION}) - -# message(Value of QT_NO_SESSIONMANAGER is: $${QT_NO_SESSIONMANAGER}) - -# Flags for profile application -equals(PROFILING_ENABLE, 1) { - message(Enable profiling) - QMAKE_CXXFLAGS_DEBUG += -pg - QMAKE_LFLAGS_DEBUG += -pg -} - -# Enable C++14 -greaterThan(QT_MAJOR_VERSION, 4) { - CONFIG += c++14 -} else { - QMAKE_CXXFLAGS += -std=c++14 -} - -# Create define variable in C++ code -DEFINES+="ANY_OS=1" -DEFINES+="MEEGO_OS=2" -DEFINES+="ANDROID_OS=3" -DEFINES+="TARGET_OS=$${TARGET_OS}" - -TEMPLATE = app -QT = gui \ - core \ - xml \ - svg \ - network -CONFIG += qt \ - warn_on - -# If debug build -equals(BUILD_TYPE, "debug") { - message(Is debug build) - CONFIG += debug -} else { - message(Is release build) -} - -# If Windows console enable -equals(WINDOWS_CONSOLE_ENABLE, 1) { - message(Is enable Windows console) - CONFIG += console -} - -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets \ - printsupport - -contains(TARGET_OS, ANY_OS) { - DESTDIR = bin - OBJECTS_DIR = build - MOC_DIR = build - UI_DIR = build -} - - -TARGET = mytetra -RESOURCES = bin/mytetra.qrc \ - bin/icons.qrc -TRANSLATIONS = bin/resource/translations/mytetra_ru.ts \ - bin/resource/translations/mytetra_fr.ts -CODECFORTR = utf8 - -# QMAKE_LFLAGS += -L/usr/lib/qt4/lib -INCLUDEPATH += $${_PRO_FILE_PWD_}/src - -contains(TARGET_OS, ANY_OS) { - message(Building the any OS version...) - SYSTEM_PROGRAM_NAME=mytetra - BINARY_INSTALL_PATH=/usr/local/bin -} - -contains(TARGET_OS, MEEGO_OS){ - message(Building the MeeGo OS version...) - SYSTEM_PROGRAM_NAME=ru.webhamster.mytetra - BINARY_INSTALL_PATH=/opt/$${SYSTEM_PROGRAM_NAME}/bin -} - -contains(TARGET_OS, ANDROID_OS){ - message(Building the Android OS version...) - SYSTEM_PROGRAM_NAME=mytetra - BINARY_INSTALL_PATH=/ -} - - -message(Set installation directory for binary file to $${BINARY_INSTALL_PATH}) - -# mytetra_binary.path=$${BINARY_INSTALL_PATH} -# mytetra_binary.files=bin/mytetra -# INSTALLS+=mytetra_binary -target.path=$${BINARY_INSTALL_PATH} -INSTALLS+=target - -desktop_file.path=/usr/share/applications -contains(TARGET_OS, ANY_OS) { - desktop_file.files=desktop/any/mytetra.desktop -} -contains(TARGET_OS, MEEGO_OS) { - desktop_file.files=desktop/meego/mytetra.desktop -} -contains(TARGET_OS, ANDROID_OS) { - desktop_file.files=desktop/any/mytetra.desktop -} -INSTALLS+=desktop_file - -icon_scalable_file.path=/usr/share/icons/hicolor/scalable/apps -icon_scalable_file.files=desktop/mytetra.svg -INSTALLS+=icon_scalable_file - -icon_48_file.path=/usr/share/icons/hicolor/48x48/apps -icon_48_file.files=desktop/mytetra.png -INSTALLS+=icon_48_file - - -HEADERS = src/main.h \ - src/controllers/databasesManagement/DatabasesManagementController.h \ - src/libraries/RandomInitter.h \ - src/libraries/helpers/ActionHelper.h \ - src/libraries/helpers/ConfigEditorHelper.h \ - src/libraries/helpers/CssHelper.h \ - src/libraries/helpers/DebugHelper.h \ - src/libraries/helpers/DiskHelper.h \ - src/libraries/helpers/GestureHelper.h \ - src/libraries/helpers/HtmlHelper.h \ - src/libraries/helpers/MessageHelper.h \ - src/libraries/helpers/ObjectHelper.h \ - src/libraries/helpers/ScreenHelper.h \ - src/libraries/helpers/SortHelper.h \ - src/libraries/helpers/UniqueIdHelper.h \ - src/libraries/wyedit/EditorConfigMathExpression.h \ - src/libraries/wyedit/EditorFontToolFocus.h \ - src/libraries/wyedit/EditorShowTextContextMenu.h \ - src/libraries/wyedit/EditorShowTextDispatcher.h \ - src/libraries/wyedit/mvc/models/editorToolbarSettings/EditorToolbarSettingsAbstractModel.h \ - src/libraries/wyedit/mvc/models/editorToolbarSettings/EditorToolbarSettingsAvailableToolsModel.h \ - src/libraries/wyedit/mvc/models/editorToolbarSettings/EditorToolbarSettingsUsedToolsModel.h \ - src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarCommandsListView.h \ - src/models/databasesManagement/DatabasesManagementModel.h \ - src/models/databasesManagement/KnownBasesConfig.h \ - src/views/appConfigWindow/AppConfigPage_Appearance.h \ - src/views/appConfigWindow/AppConfigPage_History.h \ - src/views/consoleEmulator/CommandRun.h \ - src/views/databasesManagement/DatabasesManagementScreen.h \ - src/views/databasesManagement/DatabasesManagementTable.h \ - src/views/installDialog/InstallDialog.h \ - src/views/recordTable/RecordTableScreen.h \ - src/views/recordTable/RecordTableView.h \ - src/views/record/RecordInfoFieldsEditor.h \ - src/views/record/InfoFieldEnter.h \ - src/views/record/MetaEditor.h \ - src/libraries/wyedit/Editor.h \ - src/libraries/wyedit/EditorConfig.h \ - src/libraries/wyedit/EditorConfigDialog.h \ - src/libraries/wyedit/EditorConfigFont.h \ - src/libraries/wyedit/EditorConfigMisc.h \ - src/libraries/wyedit/EditorFindDialog.h \ - src/views/mainWindow/MainWindow.h \ - src/views/printPreview/PrintPreview.h \ - src/views/printPreview/PreviewView.h \ - src/models/tree/XmlTree.h \ - src/models/tree/TreeModel.h \ - src/models/tree/TreeItem.h \ - src/models/tree/KnowTreeModel.h \ - src/models/recordTable/RecordTableData.h \ - src/models/recordTable/RecordTableModel.h \ - src/models/recordTable/RecordTableProxyModel.h \ - src/models/appConfig/AppConfig.h \ - src/views/record/AddNewRecord.h \ - src/libraries/ClipboardRecords.h \ - src/views/tree/TreeScreen.h \ - src/views/findInBaseScreen/FindScreen.h \ - src/views/findInBaseScreen/FindTableWidget.h \ - src/views/appConfigWindow/AppConfigDialog.h \ - src/views/appConfigWindow/ConfigDialog.h \ - src/views/appConfigWindow/ConfigPage.h \ - src/views/appConfigWindow/AppConfigPage_Main.h \ - src/views/appConfigWindow/AppConfigPage_Misc.h \ - src/views/appConfigWindow/AppConfigPage_Crypt.h \ - src/views/appConfigWindow/AppConfigPage_Synchro.h \ - src/views/appConfigWindow/AppConfigPage_RecordTable.h \ - src/models/appConfig/AppConfigUpdater.h \ - src/libraries/TrashMonitoring.h \ - src/libraries/wyedit/EditorContextMenu.h \ - src/libraries/wyedit/EditorTextArea.h \ - src/libraries/wyedit/indentslider/IndentSlider.h \ - src/libraries/wyedit/EditorSplitCellForm.h \ - src/libraries/wyedit/EditorAbsTableCell.h \ - src/libraries/wyedit/EditorAbsTable.h \ - src/libraries/wyedit/EditorAddTableForm.h \ - src/libraries/wyedit/EditorImageProperties.h \ - src/libraries/wyedit/EditorMultiLineInputDialog.h \ - src/libraries/FixedParameters.h \ - src/libraries/WindowSwitcher.h \ - src/libraries/wyedit/EditorShowText.h \ - src/views/recordTable/RecordTablePrint.h \ - src/models/recordTable/Record.h \ - src/models/attachTable/Attach.h \ - src/models/attachTable/AttachTableData.h \ - src/models/attachTable/AttachTableModel.h \ - src/views/attachTable/AttachTableView.h \ - src/views/attachTable/AttachTableScreen.h \ - src/controllers/attachTable/AttachTableController.h \ - src/controllers/recordTable/RecordTableController.h \ - src/views/dialog/ReduceMessageBox.h \ - src/views/dialog/OverTextToolButton.h \ - src/libraries/crypt/CryptService.h \ - src/libraries/wyedit/EditorToolBar.h \ - src/libraries/wyedit/formatters/TypefaceFormatter.h \ - src/libraries/wyedit/formatters/Formatter.h \ - src/libraries/wyedit/formatters/PlacementFormatter.h \ - src/libraries/wyedit/formatters/ListFormatter.h \ - src/libraries/wyedit/formatters/TableFormatter.h \ - src/libraries/wyedit/formatters/ImageFormatter.h \ - src/libraries/wyedit/EditorIndentSliderAssistant.h \ - src/libraries/wyedit/EditorToolBarAssistant.h \ - src/libraries/TraceLogger.h \ - src/libraries/wyedit/formatters/ReferenceFormatter.h \ - src/libraries/wyedit/EditorCursorPositionDetector.h \ - src/libraries/Downloader.h \ - src/views/actionLog/ActionLogScreen.h \ - src/views/actionLog/ActionLogView.h \ - src/controllers/actionLog/ActionLogController.h \ - src/models/actionLog/ActionLogModel.h \ - src/libraries/ActionLogger.h \ - src/libraries/wyedit/EditorTablePropertiesForm.h \ - src/views/appConfigWindow/AppConfigPage_Attach.h \ - src/libraries/TimerMonitoring.h \ - src/libraries/PreviewFileDialog.h \ - src/libraries/IconSelectDialog.h \ - src/libraries/PeriodicCheckBase.h \ - src/libraries/PeriodicSyncro.h \ - src/libraries/wyedit/EditorFontSizeComboBox.h \ - src/libraries/wyedit/EditorFontFamilyComboBox.h \ - src/libraries/wyedit/formatters/MathExpressionFormatter.h \ - src/libraries/ShortcutManager.h \ - src/views/shortcutSettings/ShortcutSettingsScreen.h \ - src/views/shortcutSettings/ShortcutSettingsView.h \ - src/controllers/shortcutSettings/ShortcutSettingsController.h \ - src/models/shortcutSettings/ShortcutSettingsModel.h \ - src/views/appConfigWindow/AppConfigPage_Keyboard.h \ - src/views/shortcutSettings/HotKeyGrabber.h \ - src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarSettingsScreen.h \ - src/libraries/wyedit/mvc/controllers/editorToolbarSettings/EditorToolbarUsedCommandsController.h \ - src/libraries/wyedit/mvc/controllers/editorToolbarSettings/EditorToolbarAvailableCommandsController.h \ - src/libraries/wyedit/EditorConfigToolbars.h \ - src/libraries/wyedit/EditorMathExpressionDialog.h - -lessThan(QT_MAJOR_VERSION,5) { -HEADERS+=src/libraries/qtSingleApplication/qtsingleapplication.h \ - src/libraries/qtSingleApplication/qtlockedfile.h \ - src/libraries/qtSingleApplication/qtlocalpeer.h \ - src/libraries/qtSingleApplication/qtsinglecoreapplication.h -} -else { -HEADERS+=src/libraries/qtSingleApplication5/qtsingleapplication.h \ - src/libraries/qtSingleApplication5/qtlockedfile.h \ - src/libraries/qtSingleApplication5/qtlocalpeer.h \ - src/libraries/qtSingleApplication5/qtsinglecoreapplication.h -} - -HEADERS+=\ - src/libraries/ClipboardBranch.h \ - src/libraries/GlobalParameters.h \ - src/models/dataBaseConfig/DataBaseConfig.h \ - src/views/enterPassword/EnterPassword.h \ - src/views/consoleEmulator/ConsoleEmulator.h \ - src/views/waitClock/WaitClock.h \ - src/libraries/WalkHistory.h \ - src/libraries/crypt/Pbkdf2Qt.h \ - src/libraries/crypt/RC5Simple.h \ - src/libraries/crypt/Password.h \ - src/libraries/MtComboBox.h \ - src/libraries/MtTableWidget.h \ - src/views/tree/KnowTreeView.h \ - src/libraries/MtStyledItemDelegate.h - -SOURCES = src/main.cpp \ - src/controllers/databasesManagement/DatabasesManagementController.cpp \ - src/libraries/RandomInitter.cpp \ - src/libraries/helpers/ActionHelper.cpp \ - src/libraries/helpers/ConfigEditorHelper.cpp \ - src/libraries/helpers/CssHelper.cpp \ - src/libraries/helpers/DebugHelper.cpp \ - src/libraries/helpers/DiskHelper.cpp \ - src/libraries/helpers/GestureHelper.cpp \ - src/libraries/helpers/HtmlHelper.cpp \ - src/libraries/helpers/MessageHelper.cpp \ - src/libraries/helpers/ObjectHelper.cpp \ - src/libraries/helpers/ScreenHelper.cpp \ - src/libraries/helpers/SortHelper.cpp \ - src/libraries/helpers/UniqueIdHelper.cpp \ - src/libraries/wyedit/EditorConfigMathExpression.cpp \ - src/libraries/wyedit/EditorFontToolFocus.cpp \ - src/libraries/wyedit/EditorShowTextContextMenu.cpp \ - src/libraries/wyedit/EditorShowTextDispatcher.cpp \ - src/libraries/wyedit/mvc/models/editorToolbarSettings/EditorToolbarSettingsAbstractModel.cpp \ - src/libraries/wyedit/mvc/models/editorToolbarSettings/EditorToolbarSettingsAvailableToolsModel.cpp \ - src/libraries/wyedit/mvc/models/editorToolbarSettings/EditorToolbarSettingsUsedToolsModel.cpp \ - src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarCommandsListView.cpp \ - src/models/databasesManagement/DatabasesManagementModel.cpp \ - src/models/databasesManagement/KnownBasesConfig.cpp \ - src/views/appConfigWindow/AppConfigPage_Appearance.cpp \ - src/views/appConfigWindow/AppConfigPage_History.cpp \ - src/views/consoleEmulator/CommandRun.cpp \ - src/views/databasesManagement/DatabasesManagementScreen.cpp \ - src/views/databasesManagement/DatabasesManagementTable.cpp \ - src/views/installDialog/InstallDialog.cpp \ - src/views/recordTable/RecordTableScreen.cpp \ - src/views/recordTable/RecordTableView.cpp \ - src/views/record/RecordInfoFieldsEditor.cpp \ - src/views/record/InfoFieldEnter.cpp \ - src/views/record/MetaEditor.cpp \ - src/libraries/wyedit/Editor.cpp \ - src/libraries/wyedit/EditorConfig.cpp \ - src/libraries/wyedit/EditorConfigDialog.cpp \ - src/libraries/wyedit/EditorConfigFont.cpp \ - src/libraries/wyedit/EditorConfigMisc.cpp \ - src/libraries/wyedit/EditorFindDialog.cpp \ - src/views/mainWindow/MainWindow.cpp \ - src/views/printPreview/PrintPreview.cpp \ - src/views/printPreview/PreviewView.cpp \ - src/models/tree/XmlTree.cpp \ - src/models/tree/TreeModel.cpp \ - src/models/tree/TreeItem.cpp \ - src/models/tree/KnowTreeModel.cpp \ - src/models/recordTable/RecordTableData.cpp \ - src/models/recordTable/RecordTableModel.cpp \ - src/models/recordTable/RecordTableProxyModel.cpp \ - src/models/appConfig/AppConfig.cpp \ - src/views/record/AddNewRecord.cpp \ - src/libraries/ClipboardRecords.cpp \ - src/views/tree/TreeScreen.cpp \ - src/views/findInBaseScreen/FindScreen.cpp \ - src/views/findInBaseScreen/FindTableWidget.cpp \ - src/views/appConfigWindow/AppConfigDialog.cpp \ - src/views/appConfigWindow/ConfigDialog.cpp \ - src/views/appConfigWindow/ConfigPage.cpp \ - src/views/appConfigWindow/AppConfigPage_Main.cpp \ - src/views/appConfigWindow/AppConfigPage_Misc.cpp \ - src/views/appConfigWindow/AppConfigPage_Crypt.cpp \ - src/views/appConfigWindow/AppConfigPage_Synchro.cpp \ - src/views/appConfigWindow/AppConfigPage_RecordTable.cpp \ - src/models/appConfig/AppConfigUpdater.cpp \ - src/libraries/TrashMonitoring.cpp \ - src/libraries/wyedit/EditorContextMenu.cpp \ - src/libraries/wyedit/EditorTextArea.cpp \ - src/libraries/wyedit/indentslider/IndentSlider.cpp \ - src/libraries/wyedit/EditorSplitCellForm.cpp \ - src/libraries/wyedit/EditorAbsTableCell.cpp \ - src/libraries/wyedit/EditorAbsTable.cpp \ - src/libraries/wyedit/EditorAddTableForm.cpp \ - src/libraries/wyedit/EditorImageProperties.cpp \ - src/libraries/wyedit/EditorMultiLineInputDialog.cpp \ - src/libraries/FixedParameters.cpp \ - src/libraries/WindowSwitcher.cpp \ - src/libraries/wyedit/EditorShowText.cpp \ - src/views/recordTable/RecordTablePrint.cpp \ - src/models/recordTable/Record.cpp \ - src/models/attachTable/Attach.cpp \ - src/models/attachTable/AttachTableData.cpp \ - src/models/attachTable/AttachTableModel.cpp \ - src/views/attachTable/AttachTableView.cpp \ - src/views/attachTable/AttachTableScreen.cpp \ - src/controllers/recordTable/RecordTableController.cpp \ - src/controllers/attachTable/AttachTableController.cpp \ - src/views/dialog/ReduceMessageBox.cpp \ - src/views/dialog/OverTextToolButton.cpp \ - src/libraries/crypt/CryptService.cpp \ - src/libraries/wyedit/EditorToolBar.cpp \ - src/libraries/wyedit/formatters/TypefaceFormatter.cpp \ - src/libraries/wyedit/formatters/Formatter.cpp \ - src/libraries/wyedit/formatters/PlacementFormatter.cpp \ - src/libraries/wyedit/formatters/ListFormatter.cpp \ - src/libraries/wyedit/formatters/TableFormatter.cpp \ - src/libraries/wyedit/formatters/ImageFormatter.cpp \ - src/libraries/wyedit/EditorIndentSliderAssistant.cpp \ - src/libraries/wyedit/EditorToolBarAssistant.cpp \ - src/libraries/TraceLogger.cpp \ - src/libraries/wyedit/formatters/ReferenceFormatter.cpp \ - src/libraries/wyedit/EditorCursorPositionDetector.cpp \ - src/libraries/Downloader.cpp \ - src/views/actionLog/ActionLogScreen.cpp \ - src/views/actionLog/ActionLogView.cpp \ - src/controllers/actionLog/ActionLogController.cpp \ - src/models/actionLog/ActionLogModel.cpp \ - src/libraries/ActionLogger.cpp \ - src/libraries/wyedit/EditorTablePropertiesForm.cpp \ - src/views/appConfigWindow/AppConfigPage_Attach.cpp \ - src/libraries/TimerMonitoring.cpp \ - src/libraries/PreviewFileDialog.cpp \ - src/libraries/IconSelectDialog.cpp \ - src/libraries/PeriodicCheckBase.cpp \ - src/libraries/PeriodicSyncro.cpp \ - src/libraries/wyedit/EditorFontSizeComboBox.cpp \ - src/libraries/wyedit/EditorFontFamilyComboBox.cpp \ - src/libraries/wyedit/formatters/MathExpressionFormatter.cpp \ - src/libraries/ShortcutManager.cpp \ - src/views/shortcutSettings/ShortcutSettingsScreen.cpp \ - src/views/shortcutSettings/ShortcutSettingsView.cpp \ - src/controllers/shortcutSettings/ShortcutSettingsController.cpp \ - src/models/shortcutSettings/ShortcutSettingsModel.cpp \ - src/views/appConfigWindow/AppConfigPage_Keyboard.cpp \ - src/views/shortcutSettings/HotKeyGrabber.cpp \ - src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarSettingsScreen.cpp \ - src/libraries/wyedit/mvc/controllers/editorToolbarSettings/EditorToolbarUsedCommandsController.cpp \ - src/libraries/wyedit/mvc/controllers/editorToolbarSettings/EditorToolbarAvailableCommandsController.cpp \ - src/libraries/wyedit/EditorConfigToolbars.cpp \ - src/libraries/wyedit/EditorMathExpressionDialog.cpp - -lessThan(QT_MAJOR_VERSION,5) { -SOURCES+=src/libraries/qtSingleApplication/qtsingleapplication.cpp \ - src/libraries/qtSingleApplication/qtlockedfile.cpp \ - src/libraries/qtSingleApplication/qtlockedfile_unix.cpp \ - src/libraries/qtSingleApplication/qtlockedfile_win.cpp \ - src/libraries/qtSingleApplication/qtlocalpeer.cpp \ - src/libraries/qtSingleApplication/qtsinglecoreapplication.cpp -} -else { -SOURCES+=src/libraries/qtSingleApplication5/qtsingleapplication.cpp \ - src/libraries/qtSingleApplication5/qtlockedfile.cpp \ - src/libraries/qtSingleApplication5/qtlockedfile_unix.cpp \ - src/libraries/qtSingleApplication5/qtlockedfile_win.cpp \ - src/libraries/qtSingleApplication5/qtlocalpeer.cpp \ - src/libraries/qtSingleApplication5/qtsinglecoreapplication.cpp -} - -SOURCES+=\ - src/libraries/ClipboardBranch.cpp \ - src/libraries/GlobalParameters.cpp \ - src/models/dataBaseConfig/DataBaseConfig.cpp \ - src/views/enterPassword/EnterPassword.cpp \ - src/views/consoleEmulator/ConsoleEmulator.cpp \ - src/views/waitClock/WaitClock.cpp \ - src/libraries/WalkHistory.cpp \ - src/libraries/crypt/Pbkdf2Qt.cpp \ - src/libraries/crypt/RC5Simple.cpp \ - src/libraries/crypt/Password.cpp \ - src/libraries/MtComboBox.cpp \ - src/libraries/MtTableWidget.cpp \ - src/views/tree/KnowTreeView.cpp \ - src/libraries/MtStyledItemDelegate.cpp - -wince* { - CONFIG(debug, release|debug):addPlugins.sources = $$QT_BUILD_TREE/plugins/imageformats/qsvgd4.dll - CONFIG(release, release|debug):addPlugins.sources = $$QT_BUILD_TREE/plugins/imageformats/qsvg4.dll - addPlugins.path = imageformats - DEPLOYMENT += addPlugins -} - -ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android - -OTHER_FILES += \ - android/AndroidManifest.xml - -# win icon -win32:RC_FILE = desktop/win.rc - - -################### -# Post linking copy -################### -defineReplace(copyToDir) { - files = $$1 - DIR = $$2 - LINK = - - for(FILE, files) { - LINK += $$QMAKE_COPY $$shell_path($$FILE) $$shell_path($$DIR) $$escape_expand(\\n\\t) - # LINK += $$QMAKE_COPY $$quote($$FILE) $$quote($$DIR) $$escape_expand(\\n\\t) - } - return($$LINK) -} - -win32 { - MIMETEX_BINARY=mimetex.exe -} -!win32 { - MIMETEX_BINARY=mimetex -} - -!android { -QMAKE_POST_LINK += $$copyToDir($${_PRO_FILE_PWD_}/../thirdParty/mimetex/build/bin/$${MIMETEX_BINARY}, $${OUT_PWD}/bin/$${MIMETEX_BINARY}) -} - -FORMS += \ - src/samples/buttonwidth.ui \ - src/views/installDialog/InstallDialog.ui - diff --git a/app/bin/mytetra.qrc b/app/bin/mytetra.qrc index 7372fad48..572f03664 100644 --- a/app/bin/mytetra.qrc +++ b/app/bin/mytetra.qrc @@ -80,8 +80,6 @@ resource/pic/mobile_back.svg resource/pic/sort.svg resource/pic/installation/installCover.png - resource/translations/mytetra_ru.qm - resource/translations/mytetra_fr.qm resource/standartconfig/any/conf.ini resource/standartconfig/any/editorconf.ini resource/standartconfig/any/stylesheet.css @@ -116,6 +114,7 @@ resource/pic/edit_fixBreakSymbol.svg resource/pic/attach_add_from_url.svg resource/pic/edit_text_only.svg + resource/pic/countryFlags/France.png resource/pic/countryFlags/Russia.png resource/pic/countryFlags/United-Kingdom.png resource/pic/edit_math_expression.svg diff --git a/app/bin/resource/pic/countryFlags/France.png b/app/bin/resource/pic/countryFlags/France.png new file mode 100644 index 000000000..97a741334 Binary files /dev/null and b/app/bin/resource/pic/countryFlags/France.png differ diff --git a/app/bin/resource/pic/edit_createtable.svg b/app/bin/resource/pic/edit_createtable.svg index adc16f2d4..287f7ffce 100644 --- a/app/bin/resource/pic/edit_createtable.svg +++ b/app/bin/resource/pic/edit_createtable.svg @@ -1,151 +1 @@ - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_expand_text_area.svg b/app/bin/resource/pic/edit_expand_text_area.svg index c055922c4..88748e921 100644 --- a/app/bin/resource/pic/edit_expand_text_area.svg +++ b/app/bin/resource/pic/edit_expand_text_area.svg @@ -1,310 +1 @@ - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_findtext.svg b/app/bin/resource/pic/edit_findtext.svg index 81922510e..df70020e9 100644 --- a/app/bin/resource/pic/edit_findtext.svg +++ b/app/bin/resource/pic/edit_findtext.svg @@ -1,178 +1 @@ - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_showhtml.svg b/app/bin/resource/pic/edit_showhtml.svg index 7871a5114..81504b471 100644 --- a/app/bin/resource/pic/edit_showhtml.svg +++ b/app/bin/resource/pic/edit_showhtml.svg @@ -1,178 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_add_col.svg b/app/bin/resource/pic/edit_table_add_col.svg index 8a020a4dc..2c34a2bdd 100644 --- a/app/bin/resource/pic/edit_table_add_col.svg +++ b/app/bin/resource/pic/edit_table_add_col.svg @@ -1,151 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_add_row.svg b/app/bin/resource/pic/edit_table_add_row.svg index 191f788b5..145387b9a 100644 --- a/app/bin/resource/pic/edit_table_add_row.svg +++ b/app/bin/resource/pic/edit_table_add_row.svg @@ -1,151 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_merge_cells.svg b/app/bin/resource/pic/edit_table_merge_cells.svg index 8f464150f..b5039f95e 100644 --- a/app/bin/resource/pic/edit_table_merge_cells.svg +++ b/app/bin/resource/pic/edit_table_merge_cells.svg @@ -1,128 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_properties.svg b/app/bin/resource/pic/edit_table_properties.svg index acd18050e..807f60ce2 100644 --- a/app/bin/resource/pic/edit_table_properties.svg +++ b/app/bin/resource/pic/edit_table_properties.svg @@ -1,158 +1 @@ - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_remove_col.svg b/app/bin/resource/pic/edit_table_remove_col.svg index 75a6e74aa..e4c8d4d03 100644 --- a/app/bin/resource/pic/edit_table_remove_col.svg +++ b/app/bin/resource/pic/edit_table_remove_col.svg @@ -1,155 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_remove_row.svg b/app/bin/resource/pic/edit_table_remove_row.svg index e5c72343c..a86ccd04c 100644 --- a/app/bin/resource/pic/edit_table_remove_row.svg +++ b/app/bin/resource/pic/edit_table_remove_row.svg @@ -1,155 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/edit_table_split_cell.svg b/app/bin/resource/pic/edit_table_split_cell.svg index 7ced0b69a..f1878d0df 100644 --- a/app/bin/resource/pic/edit_table_split_cell.svg +++ b/app/bin/resource/pic/edit_table_split_cell.svg @@ -1,187 +1 @@ - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/pic/note_edit.svg b/app/bin/resource/pic/note_edit.svg index b73441ba7..37e949b3b 100644 --- a/app/bin/resource/pic/note_edit.svg +++ b/app/bin/resource/pic/note_edit.svg @@ -1,132 +1 @@ - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/app/bin/resource/standartconfig/any/conf.ini b/app/bin/resource/standartconfig/any/conf.ini index 22be4af48..88a55d12e 100644 --- a/app/bin/resource/standartconfig/any/conf.ini +++ b/app/bin/resource/standartconfig/any/conf.ini @@ -16,7 +16,7 @@ enableDecryptFileToTrashDirectory=false enableLogging=false enablePeriodicCheckBase=false enablePeriodicCheckMessage=true -enablePeriodicSyncro=false +enablePeriodicSynchro=false enableRecordWithAttachHighlight=false findInBaseExpand=true findScreenTreeSearchArea=0 @@ -40,7 +40,7 @@ interfacelanguage=en mainwingeometry="AdnQywACAAAAAAAAAAAAGwAAAqkAAAI/AAAAAAAAAEAAAAKpAAACPwAAAAAAAAAABAA=" passwordMiddleHash= passwordSaveFlag=false -periodicSyncroPeriod=300 +periodicSynchroPeriod=300 previewIconSize=24 printdebugmessages=false programm=mytetra @@ -57,7 +57,7 @@ showSplashScreen=false synchrocommand= synchroonexit=false synchroonstartup=false -syncroConsoleDetails=true +synchroConsoleDetails=true tetradir=./data trashdir=./trash trashmaxfilecount=200 diff --git a/app/bin/resource/translations/mytetra_fr.qm b/app/bin/resource/translations/mytetra_fr.qm deleted file mode 100644 index 2b2c4a743..000000000 Binary files a/app/bin/resource/translations/mytetra_fr.qm and /dev/null differ diff --git a/app/bin/resource/translations/mytetra_fr.ts b/app/bin/resource/translations/mytetra_fr.ts index ddaf58451..af7354c35 100644 --- a/app/bin/resource/translations/mytetra_fr.ts +++ b/app/bin/resource/translations/mytetra_fr.ts @@ -4,12 +4,12 @@ ActionLogModel - + Time Temps - + Action @@ -17,7 +17,7 @@ ActionLogScreen - + Copy selected rows @@ -25,7 +25,7 @@ ActionLogView - + Action log is empty Please enable action logging in Tools -> Preferences -> Misc @@ -34,17 +34,17 @@ Please enable action logging in Tools -> Preferences -> Misc ActionLogger - + Program started - + Program stop - + Create note "%1" with ID %2 in tree item "%3" with ID %4 @@ -54,92 +54,92 @@ Please enable action logging in Tools -> Preferences -> Misc - + Edit fields of note "%1" with ID %2 - + Edit fields of crypt note "%1" with ID %2 - + Edit text of note "%1" with ID %2 - + Edit text of crypt note "%1" with ID %2 - + Move up note "%1" with ID %2 - + Move down note "%1" with ID %2 - + Delete note "%1" with ID %2 - + Copy note "%1" with ID %2 to clipboard - + Cut note "%1" with ID %2 to clipboard - + Paste note "%1" with ID %2 from clipboard - + Start drag note "%1" with ID %2 from tree item "%3" with ID %4 - + Drop note "%1" with ID %2 to tree item "%3" with ID %4 - + Start synchronization - + Stop synchronization - + Synchronization process error detected. Error code: %1 - + Synchronization error - + Critical error: %1 - + Unavailable action %1 @@ -147,83 +147,58 @@ Please enable action logging in Tools -> Preferences -> Misc AddNewRecord - + Enter a new note - + Please enter the note's <b>title</b>. - + Please enter the note's <b>text</b>. - + A new note cannot be added - AppConfigDialog - - - MyTetra settings - - - - - Main - - + AppConfigPage_Appearance - - Crypt - - - - - Synchro - - - - - Note area - - - - - Attaches + + Run MyTetra in a minimized window - - Keyboard + + Hide detached windows if close main window - - Misc + + Windows behavior AppConfigPage_Attach - + Enable highlight notes with attachments - + Highlight color: - + Displaying notes with attachments @@ -326,6 +301,24 @@ Please enable action logging in Tools -> Preferences -> Misc + + AppConfigPage_History + + + Remember cursor position at history navigation + + + + + Try remember cursor position at ordinary selection + + + + + History of visited notes + + + AppConfigPage_Keyboard @@ -388,43 +381,43 @@ Please enable action logging in Tools -> Preferences -> Misc - + Displaying date and time format - + Locale settings - + Custom format - + Select data directory - + Select trash directory - - + + Warning - + The data directory does not exists or unavailable for reading. - + The trash directory does not exists or unavailable for reading. @@ -432,52 +425,32 @@ Please enable action logging in Tools -> Preferences -> Misc AppConfigPage_Misc - + Confirm item cut - + Print debug messages to console - - Run MyTetra in a minimized window - - - - + Enable action logging (experimental) - + Create empty note enable - - Remember cursor position at history navigation - - - - - Try remember cursor position at ordinary selection - - - - + Edit config file - - History of visited notes - - - - + Danger actions (Attention!) @@ -485,22 +458,22 @@ Please enable action logging in Tools -> Preferences -> Misc AppConfigPage_RecordTable - + Show horisontal header - + Show row number - + Headers and numbers visible - + Columns visible @@ -508,73 +481,73 @@ Please enable action logging in Tools -> Preferences -> Misc AppConfigPage_Synchro - + Synchronize at MyTetra startup - + Synchronize when exit from MyTetra - + Enable periodic background synchronize - + Synchronization command - + Use <b>%a</b> macro for get database directory path - + Automatic start synchronization - + Synchronization period: - - + + sec. - + Periodic check database tree for change at 3rd-party app - + Checking period: - + Show message if a database tree was changed by external app - + Periodic checking database tree - + The first background <b>synchronizing</b> starting.<br/>Maybe a slight delay or freezing window... - + The first background <b>checking base</b> starting.<br/>Maybe a slight delay or freezing window... @@ -582,110 +555,110 @@ Please enable action logging in Tools -> Preferences -> Misc AttachTableController - - + + Enter file URL - + Download file - + Probably error in a process of files download. - + Cannot add a directory. Please select a file(s). - + Error copying file(s). Unable to attach file(s). - + Attach file - + Add link to file - + Please, select at least one attached file to save. - + Save as... - + To save single file you must set single result file name. - + Save attaches to directory... - + Unable to save the file: file %1 not found in the database. - + Unable to save the file: file %1 input/output error. - + Please select single attach for edit. - + File name editing - + File name: - - Cant save file with empty name. + + Can't save file with empty name. - + Please select any attach(es) for delete. - + Do you want to delete attached file(s)? - + Unable to preview the encrypted attached file %1. Please, use «Save As...» button, or enable «Decrypt to a temporary file» option in Settings. - + Please, select a single file to see information about one. @@ -706,7 +679,7 @@ enable «Decrypt to a temporary file» option in Settings. AttachTableView - + No attach files @@ -714,12 +687,12 @@ enable «Decrypt to a temporary file» option in Settings. ConfigDialog - + Warning - + The program will have to be restarted for changes to take effect. @@ -727,48 +700,35 @@ enable «Decrypt to a temporary file» option in Settings. ConsoleEmulator - + Cancel - + Commands running error - - Dialog - - - Dialog - - - - - PushButton - - - Downloader - + Url - + % - + Cancel - + Has problem with save file to directory %1 @@ -776,22 +736,22 @@ enable «Decrypt to a temporary file» option in Settings. Editor - + Edit HTML source - + Search result - + String '<b> - + </b>' not found @@ -865,43 +825,43 @@ enable «Decrypt to a temporary file» option in Settings. EditorConfigFont - + Default font - + Monospace font - - + + Font size follows formatting - + Code font - + Indent size follows formatting - + Code color - + Monospace font options - + Code font options @@ -909,12 +869,12 @@ enable «Decrypt to a temporary file» option in Settings. EditorConfigMathExpression - + Formula update timer - + sec. @@ -922,32 +882,32 @@ enable «Decrypt to a temporary file» option in Settings. EditorConfigMisc - + Indent step - + pixels - + Tab size - + letters - + Edit config file - + Danger actions (Attention!) @@ -1052,41 +1012,59 @@ enable «Decrypt to a temporary file» option in Settings. EditorMathExpressionDialog - + Picture formula - + Fit to scroll area for big formula - + Timer update (%1) sec. - + Real time update - + Formula text - + Zoom in - + Zoom out + + EditorShowTextContextMenu + + + Copy + + + + + Select All + + + + + Go to current note + + + EditorSplitCellForm @@ -1181,17 +1159,17 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolBar - + Save (Ctrl+S) - + Back - + Find in base @@ -1199,7 +1177,7 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsAbstractModel - + Command @@ -1207,7 +1185,7 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsAvailableToolsModel - + <Separator> @@ -1215,27 +1193,27 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsScreen - + Toolbars settings - + Current buttons - + Available tools - + Line 1 - + Line 2 @@ -1245,42 +1223,42 @@ enable «Decrypt to a temporary file» option in Settings. - + <b>%1:</b> This command is already in <b>%2</b>. - + ToolBar 1 - + <b>%1</b>: This command is already in <b>%2</b>. - + ToolBar 2 - + <b>Information</b> for inserting the selected command (list of all available commands) in the list of working toolbars: - + The command is inserted <b>above the cursor</b> in the command list of the text editor toolbar. - + Information - + The Settings command <b>%1</b> must be on the toolbar line 1! @@ -1288,7 +1266,7 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsUsedToolsModel - + <Separator> @@ -1304,28 +1282,28 @@ enable «Decrypt to a temporary file» option in Settings. EnterPassword - + Enter a your password for access to encrypted data - - + + Password: - + Enter your password. This password is used to encrypt your notes. Do not forget it, otherwise you can not access to your encrypted data. - + Confirm password: - + Change password. Enter your old password and new password. @@ -1334,29 +1312,29 @@ Enter your old password and new password. - + Old password: - + New password: - + Confirm new password: - + OK - - + + Cancel @@ -1366,30 +1344,30 @@ Enter your old password and new password. - - - - - - + + + + + + Error passwords entering - - - + + + The password must not be empty. - - + + Password and confirm it is not equivalent! - + Old and new passwords is equivalent. @@ -1397,128 +1375,128 @@ Enter your old password and new password. FindScreen - + Find - + Any word - + All words - + Whole words - + Substring - + Entire base - + Current tree item - + Find in: - + Title - + Author(s) - + Url - + Tags - + Text - + Name tree item - - + + Cannot start find process - + Verify that you selected fields for search for starting find process. - - - + + + OK - + Can not start find process - + The search request is too short. Enter at least one word. - + Starting position for a tree searching is not set. - + Search... - + No search results. Hint: encrypted items has been detected. For searching in encrypted items you have to enter the password. - + No search results. Hint: search produced in current tree item. Try to search for entire database. - + [Tree item] @@ -1526,12 +1504,12 @@ Try to search for entire database. FindTableWidget - + Title - + Details @@ -1602,47 +1580,47 @@ Try to search for entire database. IconSelectDialog - + Select icon - + Section - + Unset icon - + Ok - + Cancel - + The icons directory %1 is not readable. - + The directory %1 has not any icon section. - + Unable to set a default section %1. - + The section "%1" has not any icons @@ -1650,32 +1628,32 @@ Try to search for entire database. ImageFormatter - + Real image size - + pixels - + Insert image - + Images download initiating... - + Download images - + Probably error in a process of images download. @@ -1683,63 +1661,28 @@ Try to search for entire database. InfoFieldEnter - + Title - + Author(s) - + Url - + Tags InstallDialog - - - Dialog - - - - - Title - - - - - Any text - - - - - Standart - - - - - Standart text - - - - - Portable - - - - - Portable text - - Welcome to MyTetra v. @@ -1758,19 +1701,19 @@ and create application files in it. - + Create application files in current directory "%1". - + Can't create portable version. Сan't write data to MyTetra binary file directory "%1". - + Please select one of install mode. @@ -1778,23 +1721,23 @@ in current directory "%1". KnowTreeModel - + Unsupported version of the database format. You need to update MyTetra. - + The exporting file %1 is not writable. - + Import error: unable to read the XML file %1. - + Find record id="%1" without dir attribute @@ -1802,12 +1745,12 @@ You need to update MyTetra. KnowTreeView - + Warning! - + Unable to move the item to an encrypted item. You have to enter the password for this action. @@ -1815,155 +1758,155 @@ You need to update MyTetra. MainWindow - + &File - + &Print... - + Print Preview... - + &Export PDF... - + Export tree item - + Import tree item - - + + &Quit - + &Tools - + Action &log - - + + &Preferences - + Main - + Crypt - + Synchro - + RecordTable - + Misc - + &Help - + About MyTetra - + About Qt - - + + Technical info - + Print Document - + Select an empty directory to export data - + Select directory to import data - + <b>Technical info</b> - + MyTetra: can't synchronization - + Do not set synchronization command.<br>Check the setting in "Sync" section in "Tools" menu - + MyTetra synchronization - + Synchronization in progress, please wait... - + &Restore window - + Ma&ximize window - + Mi&nimize window @@ -1971,12 +1914,12 @@ You need to update MyTetra. MathExpressionFormatter - + Edit TeX math expression - + Error while input TeX source @@ -1989,17 +1932,17 @@ You need to update MyTetra. MetaEditor - + <B>Url:</B> - + <B>Tags:</B> - + <b>Path: </b> @@ -2007,58 +1950,58 @@ You need to update MyTetra. Password - - + + Password entering - + Wrong old password - + Change Password - + Password successfully changed - + Password - + The password is saved - + Wrong password - + Reset crypt password - + Your items tree no more of encrypted data. Would you like to remove the encrypt password? - + Cancel - + Remove password @@ -2066,9 +2009,9 @@ You need to update MyTetra. PeriodicCheckBase - - The database was changed by external application. -MyTetra needs to reload the database tree to keep data consistency. + + The database was changed by external application or services. +MyTetra reload the database tree to keep data consistency. @@ -2116,91 +2059,141 @@ MyTetra needs to reload the database tree to keep data consistency. QObject - + Edit config file (Be careful!) - + Warning - + The program will have to be restarted for changes to take effect. - - + + Unable to rename a file which attached as a link. - + Bad link. File not found. - + Can't open file %1. File not exists. - + Can't copy file %1. May be directory %2 not writable, or target file %3 already exists. - + Unable to delete the file %1 from disk: file not found. - + Invalid empty file name. - + Unable to rename the file %1 from disk: file not found. - + The database is not consistent. The directory %1 is not found. MyTetra will try to create a blank entry to fix it. - - + + Warning! - + The database is not consistent. The file %1 is not found. MyTetra will try to create a blank entry to fix it. - + Closed + + + MyTetra settings + + + + + Main + + + + + Appearance + + + + + Crypt + + + + + Synchro + + + + + Note area + + + + + Attaches + + + + + Keyboard + + + + + History + + + + + Misc + + RecordInfoFieldsEditor - + Please enter the note's <b>title</b>. - + The note's fields cannot be modified @@ -2208,22 +2201,22 @@ MyTetra will try to create a blank entry to fix it. RecordTableController - + Unblock this note? - + Are you sure to delete this record(s)? - + Cancel - + Delete @@ -2231,8 +2224,8 @@ MyTetra will try to create a blank entry to fix it. RecordTableModel - - + + ... @@ -2278,73 +2271,73 @@ MyTetra will try to create a blank entry to fix it. RecordTableScreen - + View settings - + Setup table view settins - + Previous viewing note - + Next viewing note - - + + Back to item tree - + Toggle sorting - + Enable/disable sorting by column - + Print table - + Print current notes table - + Copy note reference - + Copy note reference to clipboard - + Switch select/multiselect - + Switch note selection mode (Notice: if multiselect is on, drag-and-drop is disabled) - + <b>Path:</b> @@ -2352,37 +2345,37 @@ MyTetra will try to create a blank entry to fix it. RecordTableView - + Block/Unblock note - + Unblock note - + Block note - + Set multiple selection - + Set single selection - + Enable sorting - + Disable sorting @@ -2390,8 +2383,8 @@ MyTetra will try to create a blank entry to fix it. ReferenceFormatter - + Reference or URL @@ -2399,657 +2392,657 @@ MyTetra will try to create a blank entry to fix it. ShortcutManager - + Add a new note - + Add a note before - + Add a note before current selected note - + Add a note after - + Add a note after current selected note - + Edit properties - + Edit note properties (name, author, tags...) - + Block/Unblock note - + Block or unblock current selected note - + Delete note(s) - + Cut notes(s) - + Cut notes(s) to clipboard - + Copy note(s) - + Copy note(s) to clipboard - + Paste note(s) - + Paste note(s) from clipboard - + Move up - + Move up current note - + Move down - + Move down current note - + Previous note - + Previous note has been viewing - + Next note - + Next note has been viewing - + Expand all sub items - + Collapse all sub items - + Move item up - + Move item down - + Insert a new sub item - + Insert a new sub item into selected - + Insert a new sibling item - + Insert a new sibling item after selected - + Edit item name - + Edit name of selected item - + Delete item - + Delete selected item and all sub items - + Cut item - + Cut item including sub items - + Copy item - + Copy item including sub items - + Paste item - + Paste sibling item after selected - + Paste as sub item - + Paste item as sub item for selected - + Encrypt item - + Encrypt item and all subitem - + Decrypt item - + Decrypt item and all subitem - + Set icon - + Set item icon - + Select all - + Copy - + Paste - + Paste plain text - + Cut - + Undo - + Redo - + Bold - + Italic - + Underline - + Strike out - + Superscript - + Subscript - + Monospace - + Code - + Select a whole paragraphs to format text as code - + Lowercase - + Uppercase - + Clear format - + When selected whole paragraph both text and paragraph format is reset to default or just text format in other case - + Text only - + Return type replace - + Replace soft carriage return to standard carriage return - + Numeric list - + Marked list - + Increase indent - + Decrease indent - + Align left - + Align center - + Align right - + Align width - + Text color - + Background color - + Select font - + Select font size - + Find text - + Find text in current note - + Editor settings - + Edit reference URL - + Edit HTML code - + Show special chars - + Create a new table - + Remove row(s) - + Remove column(s) - + Add row(s) - + Add column(s) - + Merge cells - + Split cell - + Table properties - + Insert/edit image - + Insert image from file or edit selected image properties - + Insert horizontal line - + Insert a horizontal line into the empty paragraph from cursor - + Insert/edit math expression - + Expand edit area - + Expand tools - + Forse save note - + Show detached window - + Attach files - + Go to URL or reference - + Copy selected rows - + Attach file - + Attach file from URL - + Add link - + Add link without file copying - + Edit file name - + Delete file - + Preview file - + Save as... - + Attach info - + Return to editor - + Set focus to items tree - + Set focus to notes table - + Set focus to editor - + Find in base - + Synchronization - + Run synchronization - + Ok - + Print - + Export PDF - + Quit @@ -3191,208 +3184,208 @@ MyTetra will try to create a blank entry to fix it. TreeScreen - - + + Find in base - - - - - - - + + + + + + + Unavailable action - - - - + + + + You've selected - + items. Please select single item for moving. - - - - - - - + + + + + + + OK - + items. Please select single item for enabling insert operation. - + Create new item - - + + Item name: - + Create new sub item - + Sub item name: - + items. Please select single item for enabling edit operation. - + Edit item name - + In your selected data found closed item. Action canceled. - + Confirmation request - + In the selected item has been found blocked notes. Do you really want to delete one? - + Delete item(s) - + Are you sure you wish to delete item(s) <b> - - + + </b> and all sub items? - + Delete - + Cut item - + Are you sure you wish to cut item <b> - + Cut - + Cancel - + Please select a single item for copy. - + This item contains both unencrypted and encrypted data. Copy/paste operation is possible only for item that contain similar type data. - + items. Please select single item for enabling paste operation. - + No icon selected. - + The export directory %1 is not empty. Please, select an empty directory. - + No export tree item selected. Please select a item. - + Exported tree item contains encrypted data. Please click OK and enter the password. All data will be exported unencrypted. - + Done exporting into <b>%1</b>. - + Errors occurred while exporting. - + No tree item selected for importing. Please select a item. - + You are importing into an encrypted item. Please click Ok and enter the password. All data imported will be encrypted. - + Item importing finished. - + Rename me @@ -3400,17 +3393,17 @@ All data imported will be encrypted. TypefaceFormatter - + Unreliable parsing of complexly formatted text. Expect formatting inconsistencies. - + Select text color - + Select background color @@ -3418,23 +3411,23 @@ All data imported will be encrypted. XmlTree - + Error - + Cannot read file %1: %2. - + Error converting to DOM - + Parse error at line %1, column %2: %3 diff --git a/app/bin/resource/translations/mytetra_ru.qm b/app/bin/resource/translations/mytetra_ru.qm deleted file mode 100644 index 177734251..000000000 Binary files a/app/bin/resource/translations/mytetra_ru.qm and /dev/null differ diff --git a/app/bin/resource/translations/mytetra_ru.ts b/app/bin/resource/translations/mytetra_ru.ts index 2fb37aed5..10af9db2d 100644 --- a/app/bin/resource/translations/mytetra_ru.ts +++ b/app/bin/resource/translations/mytetra_ru.ts @@ -1,15 +1,15 @@ - + ActionLogModel - + Time Время - + Action Действие @@ -17,7 +17,7 @@ ActionLogScreen - + Copy selected rows Копировать выделенные строки @@ -31,7 +31,7 @@ Please set enable for action logging in Tools -> Preferences -> Misc - + Action log is empty Please enable action logging in Tools -> Preferences -> Misc Журнал действий пуст. @@ -41,12 +41,12 @@ Please enable action logging in Tools -> Preferences -> Misc ActionLogger - + Program started Запуск программы - + Program stop Завершение работы программы @@ -107,7 +107,7 @@ Please enable action logging in Tools -> Preferences -> Misc Завершение перетаскивания записи "%1" с ID %2 в ветку "%3" с ID %4 - + Create note "%1" with ID %2 in tree item "%3" with ID %4 Создана запись "%1" с ID %2 в ветке "%3" с ID %4 @@ -117,92 +117,92 @@ Please enable action logging in Tools -> Preferences -> Misc Создана зашифрованная запись "%1" с ID %2 в ветке "%3" с ID %4 - + Edit fields of note "%1" with ID %2 Отредактированы поля записи "%1" с ID %2 - + Edit fields of crypt note "%1" with ID %2 Отредактированы поля зашифрованной записи "%1" с ID %2 - + Edit text of note "%1" with ID %2 Отредактирован текст записи "%1" с ID %2 - + Edit text of crypt note "%1" with ID %2 Отредактирован текст зашифрованной записи "%1" с ID %2 - + Move up note "%1" with ID %2 Перемещение записи вверх. Запись: "%1" с ID %2 - + Move down note "%1" with ID %2 Перемещение записи вниз. Запись: "%1" с ID %2 - + Delete note "%1" with ID %2 Удаление записи "%1" с ID %2 - + Copy note "%1" with ID %2 to clipboard Копирование записи "%1" с ID %2 в буфер обмена - + Cut note "%1" with ID %2 to clipboard Запись "%1" с ID %2 вырезана в буфер обмена - + Paste note "%1" with ID %2 from clipboard Вставка записи "%1" с ID %2 из буфера обмена - + Start drag note "%1" with ID %2 from tree item "%3" with ID %4 Начало перетаскивания записи "%1" с ID %2 из ветки "%3" с ID %4 - + Drop note "%1" with ID %2 to tree item "%3" with ID %4 Завершение перетаскивания записи "%1" с ID %2 в ветку "%3" с ID %4 - + Start synchronization Запуск синхронизации - + Stop synchronization Завершение синхронизации - + Synchronization process error detected. Error code: %1 Обнаружена ошибка процесса синхронизации. Код ошибки: %1 - + Synchronization error Ошибка синхронизации - + Critical error: %1 Критическая ошибка: %1 - + Unavailable action %1 Неизвестное действие %1 @@ -210,7 +210,7 @@ Please enable action logging in Tools -> Preferences -> Misc AddNewRecord - + Enter a new note Добавление новой записи @@ -219,17 +219,17 @@ Please enable action logging in Tools -> Preferences -> Misc Ctrl+Enter - + Please enter the note's <b>title</b>. Пожалуйста, введите <b>название</b> записи. - + Please enter the note's <b>text</b>. Пожалуйста, введите <b>текст</b> записи. - + A new note cannot be added Невозможно добавить новую запись @@ -237,60 +237,70 @@ Please enable action logging in Tools -> Preferences -> Misc AppConfigDialog - MyTetra settings - Настройки MyTetra + Настройки MyTetra - Main - Основные + Основные - Crypt - Шифрование + Шифрование - Synchro - Синхронизация + Синхронизация - Note area - Список записей + Список записей - Attaches - Прикрепляемые файлы + Прикрепляемые файлы - Keyboard - Клавиатура + Клавиатура - Misc - Разное + Разное + + + + AppConfigPage_Appearance + + + Run MyTetra in a minimized window + Запускать MyTetra в свернутом окне + + + + Hide detached windows if close main window + Скрыть откреплённые окна при закрытии главного окна + + + + Windows behavior + Поведение окон AppConfigPage_Attach - + Enable highlight notes with attachments Включить подсветку записей с прикрепленными файлами - + Highlight color: Цвет выделения: - + Displaying notes with attachments Отображение записей с прикрепленными файлами @@ -370,7 +380,7 @@ Stored password will be cleared if uncheck this checkbox. No password is set. - Пароль не задан. + Пароль не задан. @@ -411,6 +421,24 @@ Stored password will be cleared if uncheck this checkbox. При смене пароля все зашифрованные ветки будут заново зашифрованы с новым паролем. + + AppConfigPage_History + + + Remember cursor position at history navigation + Вспоминать позицию курсора при навигации по истории + + + + Try remember cursor position at ordinary selection + Пытаться вспомнить позицию курсора при обычном выборе записи + + + + History of visited notes + История просмотренных записей + + AppConfigPage_Keyboard @@ -472,7 +500,7 @@ Stored password will be cleared if uncheck this checkbox. Язык - + Displaying date and time format Отображение даты и времени @@ -489,12 +517,12 @@ Stored password will be cleared if uncheck this checkbox. Использовать вручную заданный формат даты и времени - + The data directory does not exists or unavailable for reading. Директория с данными либо не существует, либо недоступна для чтения. - + The trash directory does not exists or unavailable for reading. Директория корзины либо не существует, либо недоступна для чтения. @@ -508,28 +536,28 @@ Stored password will be cleared if uncheck this checkbox. Формат времени и даты - + Locale settings Локальные установки ОС - + Custom format Собственный формат - + Select data directory Выбор директории с данными - + Select trash directory Выбор директории корзины - - + + Warning Внимание @@ -541,27 +569,26 @@ Stored password will be cleared if uncheck this checkbox. Запрашивать подтверждение перед вырезанием ветки - + Confirm item cut Подтверждение перед вырезанием ветки - + Print debug messages to console Выводить отладочные сообщения в консоль - Run MyTetra in a minimized window - Запускать MyTetra в свернутом окне + Запускать MyTetra в свернутом окне - + Enable action logging (experimental) Включить журнал действий (экспериментально) - + Create empty note enable Разрешить создавать пустые записи @@ -570,17 +597,16 @@ Stored password will be cleared if uncheck this checkbox. Разрешить создавать пустые записи - + Edit config file Редактировать конфиг-файл - History of visited notes - История просмотренных записей + История просмотренных записей - + Danger actions (Attention!) Опасные действия (Будьте внимательны!) @@ -589,35 +615,33 @@ Stored password will be cleared if uncheck this checkbox. Опасные действия (Будьте внимательны!) - Remember cursor position at history navigation - Вспоминать позицию курсора при навигации по истории + Вспоминать позицию курсора при навигации по истории - Try remember cursor position at ordinary selection - Пытаться вспомнить позицию курсора при обычном выборе записи + Пытаться вспомнить позицию курсора при обычном выборе записи AppConfigPage_RecordTable - + Show horisontal header Показать горизонтальные заголовки - + Show row number Показать номера строк - + Headers and numbers visible Видимость заголовков и номеров строк - + Columns visible Отображаемые колонки @@ -625,12 +649,12 @@ Stored password will be cleared if uncheck this checkbox. AppConfigPage_Synchro - + Synchronize at MyTetra startup Синхронизировать при старте MyTetra - + Synchronize when exit from MyTetra Синхронизировать при выходе из MyTetra @@ -639,63 +663,63 @@ Stored password will be cleared if uncheck this checkbox. Включить периодическую синхронизацию - + Enable periodic background synchronize Включить периодическую фоновую синхронизацию - + Synchronization command Команда синхронизации - + Use <b>%a</b> macro for get database directory path Используйте макрос <b>%a</b> для получения имени директории с данными - + Automatic start synchronization Автоматический запуск синхронизации - + Synchronization period: Периодичность синхронизации: - - + + sec. сек. - + Periodic check database tree for change at 3rd-party app Периодическая проверка дерева записей на изменение сторонними программами - + Checking period: - Периодичность проверки: + Периодичность проверки: - + Show message if a database tree was changed by external app Отображать сообщение если дерево записей было изменено сторонней программой - + Periodic checking database tree Периодическая проверка дерева записей - + The first background <b>synchronizing</b> starting.<br/>Maybe a slight delay or freezing window... Первый фоновый запуск <b>синхронизации</b>.<br/>Возможна небольшая задержка или "замерзание" окна программы... - + The first background <b>checking base</b> starting.<br/>Maybe a slight delay or freezing window... Первый фоновый запуск <b>проверки базы на изменение сторонней программой</b>.<br/>Возможна небольшая задержка или "замерзание" окна программы... @@ -703,13 +727,13 @@ Stored password will be cleared if uncheck this checkbox. AttachTableController - - + + Enter file URL Ввод URL файла - + Download file Скачивание файла @@ -718,92 +742,92 @@ Stored password will be cleared if uncheck this checkbox. Невозможно добавить директорию. Пожалуйста, выберите файлы. - + Attach file Прикрепить файл - + Add link to file Добавление линка на файл - + Save as... Сохранить как... - + Save attaches to directory... Сохранить прикрепленные файлы в директорию... - + Probably error in a process of files download. Возникла ошибка в процессе скачивания изображений. - + Cannot add a directory. Please select a file(s). Невозможно добавить директорию. Для добавления выберите файл(ы). - + Error copying file(s). Unable to attach file(s). Ошибка копирования файла. Невозможно прикрепить файл. - + Please, select at least one attached file to save. Пожалуйста, выберите хотя бы один прикрепленный файл для сохранения. - + To save single file you must set single result file name. Для сохранения одного файла, пожалуйста, укажите одно результирующее имя файла. - + Unable to save the file: file %1 not found in the database. Невозможно сохранить файл. Файл %1 отсутствует в базе данных. - + Unable to save the file: file %1 input/output error. Невозможно сохранить файл %1. Возникла ошибка ввода/вывода. - + Please select single attach for edit. Для редактирования свойств необходимо выбрать один файл. - + File name editing Редактирование имени файла - + File name: Имя файла: - - Cant save file with empty name. + + Can't save file with empty name. Не могу сохранить файл с не заданным именем. - + Please select any attach(es) for delete. Пожалуйста, выберите прикрепляемый файл(ы) для удаления. - + Do you want to delete attached file(s)? Удалить прикрепленный файл(ы)? - + Unable to preview the encrypted attached file %1. Please, use «Save As...» button, or enable «Decrypt to a temporary file» option in Settings. @@ -812,7 +836,7 @@ enable «Decrypt to a temporary file» option in Settings. или включите настройку «Расшифровка во временный файл в директории корзины». - + Please, select a single file to see information about one. Просмотр информации возможен только если выбран один файл. @@ -876,7 +900,7 @@ enable «Decrypt to a temporary file» option in Settings. AttachTableView - + No attach files Нет прикрепленных файлов @@ -884,12 +908,12 @@ enable «Decrypt to a temporary file» option in Settings. ConfigDialog - + Warning Внимание - + The program will have to be restarted for changes to take effect. Для применения изменений программа будет закрыта. Новые изменения вступят в силу при следующем запуске программы. @@ -897,12 +921,12 @@ enable «Decrypt to a temporary file» option in Settings. ConsoleEmulator - + Cancel Отмена - + Commands running error Ошибка во время выполнения команд @@ -910,35 +934,29 @@ enable «Decrypt to a temporary file» option in Settings. Dialog - Dialog - Диалог инсталляции - - - - PushButton - + Диалог инсталляции Downloader - + Url Url - + % % - + Cancel Отмена - + Has problem with save file to directory %1 Возникли проблемы при сохранении файла в директорию %1 @@ -1093,22 +1111,22 @@ enable «Decrypt to a temporary file» option in Settings. Сохранить (Ctrl+S) - + Edit HTML source Редактирование исходного HTML кода - + Search result Результат поиска - + String '<b> Строка '<b> - + </b>' not found </b>' не найдена @@ -1163,17 +1181,17 @@ enable «Decrypt to a temporary file» option in Settings. Columns: - Количество столбцов: + Количество столбцов: Rows: - Количество строк: + Количество строк: Width: - Ширина: + Ширина: @@ -1222,43 +1240,43 @@ enable «Decrypt to a temporary file» option in Settings. EditorConfigFont - + Default font Основной шрифт - + Monospace font Моноширинный шрифт - - + + Font size follows formatting Устанавливать размер шрифта - + Indent size follows formatting Устанавливать отступ - + Code color Цвет кода - + Monospace font options Настройка моноширинного шрифта - + Code font options Настройка шрифта для кода - + Code font Шрифт для кода @@ -1266,12 +1284,12 @@ enable «Decrypt to a temporary file» option in Settings. EditorConfigMathExpression - + Formula update timer Период обновления формулы - + sec. сек. @@ -1279,24 +1297,24 @@ enable «Decrypt to a temporary file» option in Settings. EditorConfigMisc - + Indent step Шаг отступа - + pixels точек - + Tab size Размер табуляции - + letters - симв. + символов Formula update timer @@ -1307,12 +1325,12 @@ enable «Decrypt to a temporary file» option in Settings. сек. - + Edit config file Редактировать конфиг-файл - + Danger actions (Attention!) Опасные действия (Будьте внимательны!) @@ -1384,12 +1402,12 @@ enable «Decrypt to a temporary file» option in Settings. &Case sensitive - С учётом регистра + С учётом &регистра &Whole words only - Только отдельные слова + Только &отдельные слова @@ -1399,7 +1417,7 @@ enable «Decrypt to a temporary file» option in Settings. &Find - Найти + &Найти @@ -1453,39 +1471,39 @@ enable «Decrypt to a temporary file» option in Settings. EditorMathExpressionDialog - + Picture formula - + Изображение формулы - + Fit to scroll area for big formula - + подгонять размер для больших формул - + Timer update (%1) sec. - + обновлять с периодом %1 с. - + Real time update - + обновлять мгновенно - + Formula text - + Текст формулы - + Zoom in - + Увеличить - + Zoom out - + Уменьшить @@ -1503,6 +1521,24 @@ enable «Decrypt to a temporary file» option in Settings. Ctrl+Enter + + EditorShowTextContextMenu + + + Copy + Копировать + + + + Select All + Выбрать всё + + + + Go to current note + Перейти к текущей записи + + EditorSplitCellForm @@ -1541,7 +1577,7 @@ enable «Decrypt to a temporary file» option in Settings. Width: - Ширина: + Ширина: @@ -1765,7 +1801,7 @@ enable «Decrypt to a temporary file» option in Settings. Развернуть панель инструментов - + Save (Ctrl+S) Сохранить (Ctrl+S) @@ -1774,12 +1810,12 @@ enable «Decrypt to a temporary file» option in Settings. Ctrl+S - + Back Назад - + Find in base Найти в базе @@ -1806,7 +1842,7 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsAbstractModel - + Command Команда @@ -1818,7 +1854,7 @@ enable «Decrypt to a temporary file» option in Settings. <Разделитель> - + <Separator> <Разделитель> @@ -1826,7 +1862,7 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsScreen - + Toolbars settings Настройки панели инструментов @@ -1863,7 +1899,7 @@ enable «Decrypt to a temporary file» option in Settings. Панель инструментов, линия 2 - + Current buttons Текущие элементы @@ -1872,17 +1908,17 @@ enable «Decrypt to a temporary file» option in Settings. Элементы для - + Available tools Доступные инструменты - + Line 1 Линия 1 - + Line 2 Линия 2 @@ -1892,42 +1928,42 @@ enable «Decrypt to a temporary file» option in Settings. Инструменты на - + <b>%1:</b> This command is already in <b>%2</b>. - <b>%1:</b> Эта кнопка уже использцется в <b>%2</b> + <b>%1:</b> Эта кнопка уже используется в <b>%2</b>. - + ToolBar 1 Линия кнопок 1 - + <b>%1</b>: This command is already in <b>%2</b>. <b>%1</b>: Эта команда уже используется в <b>%2</b>. - + ToolBar 2 Линия кнопок 2 - + <b>Information</b> for inserting the selected command (list of all available commands) in the list of working toolbars: - + <b>информация</b> для вставки выбранной команды в панель инструментов редактора: - + The command is inserted <b>above the cursor</b> in the command list of the text editor toolbar. - + Команда вставляется <b>над курсором</b>. - + Information Информация - + The Settings command <b>%1</b> must be on the toolbar line 1! Элемент настроек <b>%1</b> должен размещаться только на первой линии! @@ -1939,7 +1975,7 @@ enable «Decrypt to a temporary file» option in Settings. EditorToolbarSettingsUsedToolsModel - + <Separator> <Разделитель> @@ -1962,28 +1998,28 @@ enable «Decrypt to a temporary file» option in Settings. EnterPassword - + Enter a your password for access to encrypted data Введите пароль для доступа к зашифрованным данным - - + + Password: Пароль: - + Enter your password. This password is used to encrypt your notes. Do not forget it, otherwise you can not access to your encrypted data. Введите пароль.<br><br>Этот пароль будет использоваться для шифрования выбранных вами записей. Не забывайте его, так как в противном случае вы не сможете получить доступ к зашифрованным данным. - + Confirm password: Пароль повторно: - + Change password. Enter your old password and new password. @@ -1992,29 +2028,29 @@ Enter your old password and new password. <b>Внимание!</b> При нажатии на клавишу ОК начнется перешифрация на новый пароль всех зашифрованных данных. - + Old password: Старый пароль: - + New password: Новый пароль: - + Confirm new password: Новый пароль повторно: - + OK ОК - - + + Cancel Отмена @@ -2028,34 +2064,34 @@ Enter your old password and new password. Пароль - - + + Password and confirm it is not equivalent! Пароль и его подтверждение не совпадают! - + Old and new passwords is equivalent. - Старый и новый пароль совпадают! + Старый и новый пароль совпадают. Enter password Ввод пароля - - - - - - + + + + + + Error passwords entering Ошибка при вводе пароля - - - + + + The password must not be empty. Пароль не должен быть пустым. @@ -2067,32 +2103,32 @@ Enter your old password and new password. FindScreen - + Find Поиск - + Any word Любое слово - + All words Все слова - + Whole words Только целые слова - + Substring Подстрока - + Entire base Вся база @@ -2101,80 +2137,80 @@ Enter your old password and new password. Текущая ветка - + Current tree item Текущая ветка - + Find in: Искать в: - + Title Название - + Author(s) Автор - + Url - + Tags Метки - + Text Текст - + Name tree item Название ветки - - + + Cannot start find process Невозможно начать поиск - + Verify that you selected fields for search for starting find process. Проверьте, включены ли поля, по которым надо проводить поиск. - - - + + + OK ОК - + Can not start find process Невозможно начать поиск - + The search request is too short. Enter at least one word. Слишком короткий запрос поиска. Необходимо написать хотя бы одно слово. - + Starting position for a tree searching is not set. Не установлена начальная позиция для поиска по дереву. - + No search results. Hint: encrypted items has been detected. For searching in encrypted items you have to enter the password. Ничего не найдено. @@ -2182,7 +2218,7 @@ Hint: encrypted items has been detected. For searching in encrypted items you ha Для поиска внутри зашифрованных веток введите пароль. - + No search results. Hint: search produced in current tree item. Try to search for entire database. @@ -2191,7 +2227,7 @@ Try to search for entire database. Попробуйте сделать поиск по всей базе. - + [Tree item] [Ветка] @@ -2200,7 +2236,7 @@ Try to search for entire database. Ветка - + Search... Поиск... @@ -2208,12 +2244,12 @@ Try to search for entire database. FindTableWidget - + Title Название - + Details Описание @@ -2284,47 +2320,47 @@ Try to search for entire database. IconSelectDialog - + Select icon Выбор иконки - + Section Раздел - + Unset icon Снять иконку - + Ok ОК - + Cancel Отмена - + The icons directory %1 is not readable. Невозможно прочитать данные из директории с иконками %1. - + The directory %1 has not any icon section. Не найдено ни одного раздела иконок в директории %1. - + Unable to set a default section %1. Невозможно установить стандартный раздел: %1. - + The section "%1" has not any icons Не найдены иконки в разделе "%1" @@ -2332,32 +2368,32 @@ Try to search for entire database. ImageFormatter - + Real image size Истинный размер изображения - + pixels точек - + Insert image Вставка изображения - + Images download initiating... Инициализация загрузки изображений... - + Download images Скачивание картинок - + Probably error in a process of images download. Возникла ошибка в процессе скачивания изображений. @@ -2365,22 +2401,22 @@ Try to search for entire database. InfoFieldEnter - + Title Название - + Author(s) Автор - + Url - + Tags Метки @@ -2388,39 +2424,32 @@ Try to search for entire database. InstallDialog - Dialog - Диалог инсталляции + Диалог инсталляции - Title - Название + Название - Any text - Некий текст + Некий текст - Standart - Стандартный + Стандартный - Standart text - Текст стандартного режима + Текст стандартного режима - Portable - Портабельный + Портабельный - Portable text - Текст портабельного режима + Текст портабельного режима @@ -2448,19 +2477,19 @@ and create application files in it. Будет создана поддиректория "%1" в директории пользователя "%2", и в ней будут размещены все файлы приложения. - + Create application files in current directory "%1". Файлы приложения будут созданы в текущей директории "%1" рядом с исполняемым файлом MyTetra. - + Can't create portable version. Сan't write data to MyTetra binary file directory "%1". Невозможно установить портабельную версию. Невозможно создать файлы в текущей директории "%1" рядом с исполняемым файлом MyTetra. - + Please select one of install mode. Пожалуйста, выберите один из режимов инсталляции. @@ -2468,23 +2497,23 @@ in current directory "%1". KnowTreeModel - + Unsupported version of the database format. You need to update MyTetra. Неподдерживаемый формат базы данных. Пожалуйста, обновите версию MyTetra. - + The exporting file %1 is not writable. Невозможно открыть экспортируемый файл %1 для записи. - + Import error: unable to read the XML file %1. Невозможно открыть XML-файл %1. Импорт невозможен. - + Find record id="%1" without dir attribute Найдена запись с id="%1" без аттрибута директории @@ -2492,12 +2521,12 @@ You need to update MyTetra. KnowTreeView - + Warning! Внимание! - + Unable to move the item to an encrypted item. You have to enter the password for this action. Невозможно переместить эту ветку в зашифрованную ветку. Вначале введите пароль для открытия зашифрованной ветки. @@ -2505,24 +2534,24 @@ You need to update MyTetra. MainWindow - + &File - Файл + &Файл - + &Print... - Печать... + &Печать... - + Print Preview... - Предварительный просмотр + Предварительный просмотр... - + &Export PDF... - Экспорт в PDF... + &Экспорт в PDF... Export branch @@ -2533,84 +2562,84 @@ You need to update MyTetra. Импорт ветки - + Export tree item Экспорт ветки - + Import tree item Импорт ветки - - + + &Quit - Выход + &Выход - + &Tools - Инструменты + &Инструменты Find in ba&se Поиск в базе - + Action &log - Журнал действий + &Журнал действий - - + + &Preferences - Настройки + &Настройки - + Main Основные - + Crypt Шифрование - + Synchro Синхронизация - + RecordTable Таблица записей - + Misc Разное - + &Help Справка - + About MyTetra О программе MyTetra - + About Qt О фреймворке Qt - - + + Technical info Техническая информация @@ -2619,34 +2648,34 @@ You need to update MyTetra. Печать - + Print Document Печать документа - + Select an empty directory to export data Укажите пустую директорию для экспорта данных - + Select directory to import data Укажите директорию для импорта данных - + <b>Technical info</b> <b>Техническая информация</b> - + MyTetra: can't synchronization MyTetra: Синхронизация невозможна - + Do not set synchronization command.<br>Check the setting in "Sync" section in "Tools" menu - Не задана команда синхронизации.<br>Проверьте меню "Инструменты", "Настройки", раздел "Синхронизация". + Не задана команда синхронизации.<br>Проверьте меню "Инструменты", "Настройки", раздел "Синхронизация" Do not set synchronization command. @@ -2654,40 +2683,40 @@ Check the setting in "Sync" section in "Tools" menu Не задана команда синхронизации.\nПроверьте меню \"Инструменты\", \"Настройки\", раздел \"Синхронизация\". - + MyTetra synchronization Синхронизация MyTetra - + Synchronization in progress, please wait... Происходит синхронизация. Пожалуйста, подождите... - + &Restore window - Показать окно + Показать &окно - + Ma&ximize window - Развернуть окно + &Развернуть окно - + Mi&nimize window - Свернуть окно + &Свернуть окно MathExpressionFormatter - + Edit TeX math expression Редактор формулы в формате TeX - + Error while input TeX source Ошибка при вводе TeX-кода @@ -2700,17 +2729,17 @@ Check the setting in "Sync" section in "Tools" menu MetaEditor - + <B>Url:</B> <B>Url:</B> - + <B>Tags:</B> <B>Метки:</B> - + <b>Path: </b> <b>Путь: </b> @@ -2718,58 +2747,58 @@ Check the setting in "Sync" section in "Tools" menu Password - + Wrong old password Введен неправильный старый пароль - + Change Password Смена пароля - + Password successfully changed Пароль успешно изменен - + Password Пароль - + The password is saved - Пароль сохранен локально. + Пароль сохранен локально - + Reset crypt password Сброс шифрующего пароля - + Your items tree no more of encrypted data. Would you like to remove the encrypt password? В ваших записях не осталось веток с зашифрованными данными. Желаете ли вы очистить шифрующий пароль? - + Cancel Отмена - + Remove password Очистить пароль - - + + Password entering Ввод пароля - + Wrong password Неверный пароль @@ -2777,9 +2806,15 @@ Check the setting in "Sync" section in "Tools" menu PeriodicCheckBase - The database was changed by external application. MyTetra needs to reload the database tree to keep data consistency. + База данных была изменена сторонней программой. +MyTetra перечитает дерево для продолжения работы с новыми данными. + + + + The database was changed by external application or services. +MyTetra reload the database tree to keep data consistency. База данных была изменена сторонней программой. MyTetra перечитает дерево для продолжения работы с новыми данными. @@ -2844,50 +2879,50 @@ MyTetra перечитает дерево для продолжения рабо Закрыть - + Closed Закрыто - - + + Unable to rename a file which attached as a link. Нельзя менять имя прикрепляемого файла если файл прикреплен как линк. - + Bad link. File not found. Некорректный линк. Файл не найден. - + Can't open file %1. File not exists. Невозможно открыть файл %1. Файл не существует. - + Can't copy file %1. May be directory %2 not writable, or target file %3 already exists. Не могу скопировать файл %1. Возможно, директория %2 недоступна для записи, или целевой файл %3 уже существует. - + Unable to delete the file %1 from disk: file not found. Не могу удалить файл %1 на диске. Файл не существует. - + Invalid empty file name. - Некорректное пустое имя файла + Некорректное пустое имя файла. - + Unable to rename the file %1 from disk: file not found. - Невозможно переименовать файл %1 на диске: файл не найден + Невозможно переименовать файл %1 на диске: файл не найден. - + The database is not consistent. The directory %1 is not found. MyTetra will try to create a blank entry to fix it. @@ -2896,13 +2931,13 @@ MyTetra will try to create a blank entry to fix it. Чтобы исправить ошибку, MyTetra создаст пустую запись. - - + + Warning! Внимание! - + The database is not consistent. The file %1 is not found. MyTetra will try to create a blank entry to fix it. @@ -2915,17 +2950,17 @@ MyTetra will try to create a blank entry to fix it. Редактирование конфиг-файла (Аккуратно!) - + Edit config file (Be careful!) Редактирование конфиг-файла (Аккуратно!) - + Warning Внимание - + The program will have to be restarted for changes to take effect. Для применения изменений программа будет закрыта. Новые изменения вступят в силу при следующем запуске программы. @@ -3233,6 +3268,56 @@ MyTetra will try to create a blank entry to fix it. Print Печать + + + MyTetra settings + Настройки MyTetra + + + + Main + Основные + + + + Appearance + Внешний вид + + + + Crypt + Шифрование + + + + Synchro + Синхронизация + + + + Note area + Список записей + + + + Attaches + Прикрепляемые файлы + + + + Keyboard + Клавиатура + + + + History + История + + + + Misc + Разное + RecordInfoFieldsEditor @@ -3241,12 +3326,12 @@ MyTetra will try to create a blank entry to fix it. Ctrl+Enter - + Please enter the note's <b>title</b>. Пожалуйста, введите <b>название</b> записи. - + The note's fields cannot be modified Поля записи не могут быть отредактированы @@ -3254,22 +3339,22 @@ MyTetra will try to create a blank entry to fix it. RecordTableController - + Unblock this note? Разблокировать эту запись? - + Are you sure to delete this record(s)? Вы уверены, что хотите удалить эти записи? - + Cancel Отмена - + Delete Удалить @@ -3277,8 +3362,8 @@ MyTetra will try to create a blank entry to fix it. RecordTableModel - - + + ... ... @@ -3408,7 +3493,7 @@ MyTetra will try to create a blank entry to fix it. Настройка внешнего вида - + Setup table view settins Настройка таблицы записей @@ -3433,7 +3518,7 @@ MyTetra will try to create a blank entry to fix it. Запуск синхронизации - + Previous viewing note Предыдущая запись @@ -3442,7 +3527,7 @@ MyTetra will try to create a blank entry to fix it. Предыдущая запись, которая была просмотрена - + Next viewing note Следующая запись @@ -3451,53 +3536,53 @@ MyTetra will try to create a blank entry to fix it. Следующая запись, которая была просмотрена - + View settings Настройка внешнего вида - - + + Back to item tree Назад к дереву данных - + Toggle sorting Переключить возможность сортировки - + Enable/disable sorting by column Разрешить/запретить сортировку по столбцу - + Print table Печать таблицы - + Print current notes table Печать таблицы записей - + Copy note reference Копировать ссылку на запись - + Copy note reference to clipboard Копировать ссылку на запись в буфер обмена - + Switch select/multiselect Переключить выбор / множественный выбор - + Switch note selection mode (Notice: if multiselect is on, drag-and-drop is disabled) Переключить режим выбора записи (Примечание: если включен множественный выбор, Drag-And-Drop записей отключается) @@ -3562,7 +3647,7 @@ MyTetra will try to create a blank entry to fix it. Следующая запись - + <b>Path:</b> <b>Путь:</b> @@ -3578,37 +3663,37 @@ MyTetra will try to create a blank entry to fix it. RecordTableView - + Block/Unblock note Блокировать/Разблокировать запись - + Unblock note Разблокировать запись - + Block note Блокировать запись - + Set multiple selection Включить множественный выбор - + Set single selection Выключить множественный выбор - + Enable sorting Разрешить сортировку - + Disable sorting Запретить сортировку @@ -3616,8 +3701,8 @@ MyTetra will try to create a blank entry to fix it. ReferenceFormatter - + Reference or URL Ссылка или URL @@ -3625,7 +3710,7 @@ MyTetra will try to create a blank entry to fix it. ShortcutManager - + Add a new note Добавить новую запись @@ -3634,502 +3719,502 @@ MyTetra will try to create a blank entry to fix it. Нобавить новую запись - + Add a note before Добавить перед - + Add a note before current selected note Добавить новую запись перед выбранной записью - + Add a note after Добавить после - + Add a note after current selected note Добавить новую запись после выбранной записи - + Edit properties Редактировать свойства - + Edit note properties (name, author, tags...) Редактировать свойства записи (название, автор, текстовые метки...) - + Block/Unblock note Блокировать/Разблокировать запись - + Block or unblock current selected note Блокировать/Разблокировать возможность изменения записи - + Delete note(s) Удалить - + Cut notes(s) Вырезать - + Cut notes(s) to clipboard Вырезать запись (записи) в буфер обмена - + Copy note(s) Копировать - + Copy note(s) to clipboard Копировать запись (записи) в буфер обмена - + Paste note(s) Вставить - + Paste note(s) from clipboard Вставить запись (записи) из буфера обмена - + Move up Передвинуть вверх - + Move up current note Передвинуть вверх текущую запись - + Move down Передвинуть вниз - + Move down current note Передвинуть вниз текущую запись - + Previous note Предыдущая запись - + Previous note has been viewing Предыдущая запись, которая была просмотрена - + Next note Следующая запись - + Next note has been viewing Следующая запись, которая была просмотрена - + Expand all sub items Развернуть все подветки - + Collapse all sub items Свернуть все подветки - + Move item up Переместить ветку вверх - + Move item down Переместить ветку вниз - + Insert a new sub item Добавить подветку - + Insert a new sub item into selected Добавить подветку к выделенной ветке - + Insert a new sibling item Добавить ветку такого же уровня - + Insert a new sibling item after selected Добавить ветку такого же уровня вложения после выделенной ветки - + Edit item name Редактировать название ветки - + Edit name of selected item Редактировать название выделенной ветки - + Delete item Удалить ветку - + Delete selected item and all sub items Удалить выделенную ветку и все её подветки - + Cut item Вырезать ветку - + Cut item including sub items Вырезать выделенную ветку и все её подветки - + Copy item Копировать ветку - + Copy item including sub items Скопировать ветку и все её подветки в буфер обмена - + Paste item Вставить ветку - + Paste sibling item after selected Вставить ветку из буфера обмена после выделенной на том же уровне - + Paste as sub item Вставить ветку как подветку - + Paste item as sub item for selected Вставить ветку из буфера обмена как подветку для выбранной ветки - + Encrypt item Зашифровать ветку - + Encrypt item and all subitem Зашифровать ветку и все подветки - + Decrypt item Расшифровать ветку - + Decrypt item and all subitem Расшифровать ветку и все подветки - + Set icon Задать иконку - + Set item icon Задать иконку для ветки - + Select all Выбрать всё - + Copy Копировать - + Paste Вставить - + Paste plain text Вставить только текст - + Cut Вырезать - + Undo Отмена - + Redo Повтор - + Bold Жирный - + Italic Курсив - + Underline Подчёркнутый - + Strike out Зачеркнутый - + Superscript Верхний индекс - + Subscript Нижний индекс - + Monospace Моноширинный - + Code Код - + Select a whole paragraphs to format text as code Требуется целиком выделить абзац(ы) для полного форматирования в код - + Lowercase Нижний регистр - + Uppercase Верхний регистр - + Clear format Очистка форматирования - + When selected whole paragraph both text and paragraph format is reset to default or just text format in other case Сброс форматирования к стандартному. Если выбрана часть строки, очищается начертание. Если выбран абзац, очищается всё форматирование - + Text only Только текст - + Return type replace Замена символов перевода строк - + Replace soft carriage return to standard carriage return Заменить "мягкий" перевод строки на стандартный перевод строки - + Numeric list Нумерованный список - + Marked list Маркированный список - + Increase indent Увеличить отступ - + Decrease indent Уменьшить отступ - + Align left По левому краю - + Align center По центру - + Align right По правому краю - + Align width По ширине - + Text color Цвет текста - + Background color Цвет фона - + Select font Выбор шрифта - + Select font size Выбор размера шрифта - + Find text Поиск текста - + Find text in current note Поиск текста в текущей записи - + Editor settings Настройки редактора - + Edit reference URL Редактировать ссылку - + Edit HTML code Редактирование HTML кода - + Show special chars Показать символы форматирования - + Create a new table Создать новую таблицу - + Remove row(s) Удалить строку - + Remove column(s) Удалить столбец - + Add row(s) Добавить строки - + Add column(s) Добавить столбец - + Merge cells Объединить ячейки - + Split cell Разделить ячейку - + Table properties Свойства таблицы - + Insert/edit image Вставка изображения - + Insert image from file or edit selected image properties Вставка картинки из файла / Редактирование свойств картинки @@ -4138,152 +4223,152 @@ MyTetra will try to create a blank entry to fix it. Вставка картинки из файла / Редактирование свойств картинки - + Insert horizontal line Вставка горизонтальной линии - + Insert a horizontal line into the empty paragraph from cursor Вставка горизонтальной линии для разграничения параграфов - + Insert/edit math expression Вставить формулу / редактировать формулу - + Expand edit area Распахнуть область редактирования - + Expand tools Развернуть панель инструментов - + Forse save note Быстрое сохранение записи - + Show detached window Показать открепляемое окно - + Attach files Прикрепить файл - + Go to URL or reference Перейти по URL или по ссылке - + Copy selected rows Копировать выделенные строки - + Attach file Прикрепить файл - + Attach file from URL Прикрепить файл по URL - + Add link Добавить линк - + Add link without file copying Добавить линк на файл без копирования самого файла - + Edit file name Изменить имя файла - + Delete file Удалить файл - + Preview file Предпросмотр файла - + Save as... Сохранить как... - + Attach info Информация о прикрепленном файле - + Return to editor Вернуться в редактор - + Set focus to items tree Устновить фокус на дереве - + Set focus to notes table Устновить фокус на списке записей - + Set focus to editor Устновить фокус на редакторе - + Find in base Найти в базе - + Synchronization Синхронизация - + Run synchronization Запуск синхронизации - + Ok ОК - + Print Печать - + Export PDF Экспорт в PDF - + Quit Выход @@ -4425,32 +4510,33 @@ MyTetra will try to create a blank entry to fix it. TreeScreen - - - - - - - + + + + + + + Unavailable action Недопустимое действие - - - - + + + + You've selected У вас выделены - + items. Please select single item for enabling insert operation. - ветки. Выделите одну ветку, чтобы была доступна операция вставки ветки. + ветки. +Выделите одну ветку, чтобы была доступна операция вставки ветки. - + Delete Удалить @@ -4487,7 +4573,7 @@ Please select single item for enabling insert operation. Добавить ветку такого же уровня вложения после выделенной ветки - + Edit item name Редактировать название ветки @@ -4504,7 +4590,7 @@ Please select single item for enabling insert operation. Удалить выделенную ветку и все её подветки - + Cut item Вырезать ветку @@ -4561,46 +4647,46 @@ Please select single item for enabling insert operation. Задать иконку для ветки - - + + Find in base Найти в базе - + items. Please select single item for moving. - ветки. + ветки. Для перемещения выберите, пожалуйста, одну ветку. - + In your selected data found closed item. Action canceled. В выбранных вами данных обнаружена закрытая ветка. Действие отменено. - + Confirmation request Запрос на подтверждение - + No icon selected. Вы не выбрали иконку. - + The export directory %1 is not empty. Please, select an empty directory. Директория <b>%1</b> не является пустой. Пожалуйста, выберите пустую директорию для экспорта данных. - + No export tree item selected. Please select a item. Не указана ветка для экспорта. Пожалуйста, выберите нужную ветку. - + Exported tree item contains encrypted data. Please click OK and enter the password. All data will be exported unencrypted. @@ -4609,22 +4695,22 @@ All data will be exported unencrypted. Все данные будут экспортированы в расшифрованном виде. - + Done exporting into <b>%1</b>. Экспорт данных в директорию <b>%1</b> завершен. - + Errors occurred while exporting. Обнаружены ошибки при экспорте данных. - + No tree item selected for importing. Please select a item. Не выбрана ветка для экспорта. Пожалуйста, выберите какую-нибудь ветку. - + You are importing into an encrypted item. Please click Ok and enter the password. All data imported will be encrypted. @@ -4633,20 +4719,20 @@ All data imported will be encrypted. Все данные будут импортированы и зашифрованы. - + Item importing finished. Импорт ветки завершен. - + This item contains both unencrypted and encrypted data. Copy/paste operation is possible only for item that contain similar type data. Данная ветка содержит как незашифрованные, так и зашифрованные данные. Команды Copy/Paste разрешены только для веток, которые содержат однотипные данные. - + items. Please select single item for enabling paste operation. - ветки. + ветки. Выделите одну ветку, чтобы была доступна операция вставки ветки. @@ -4654,82 +4740,83 @@ Please select single item for enabling paste operation. У вас выделены - - - - - - - + + + + + + + OK ОК - + Create new item Создание новой ветки - - + + Item name: Название ветки: - + Create new sub item Создание подветки - + Sub item name: Имя подветки: - + items. Please select single item for enabling edit operation. - ветки. Для редактирования, выберите, пожалуйста, одну ветку. + ветки. + Для редактирования, выберите, пожалуйста, одну ветку. - + In the selected item has been found blocked notes. Do you really want to delete one? В выбранной вами ветке обнаружены заблокированные записи. Тем не менее, вы желаете удалить выбранную ветку? - + Delete item(s) Удаление - + Are you sure you wish to delete item(s) <b> Вы уверены, что хотите удалить ветку (ветки) <b> - - + + </b> and all sub items? </b> и все подветки? - + Are you sure you wish to cut item <b> Вы уверены, что хотите вырезать ветку <b> - + Cut Вырезать - + Cancel Отмена - + Please select a single item for copy. Выберите, пожалуйста, одну ветку для копирования. @@ -4738,7 +4825,7 @@ Please select single item for enabling edit operation. Группы информации - + Rename me Переименуй меня @@ -4746,19 +4833,19 @@ Please select single item for enabling edit operation. TypefaceFormatter - + Unreliable parsing of complexly formatted text. Expect formatting inconsistencies. Слишком сложное форматирование текста. Невозможно правильно обработать выбранный текст. Возможно искажение в форматировании. - + Select text color Выбор цвта текста - + Select background color Выбор цвета фона @@ -4766,28 +4853,28 @@ Please select single item for enabling edit operation. XmlTree - + Error Ошибка - + Cannot read file %1: %2. Невозможно прочитать файл %1: %2. - + Error converting to DOM Ошибка при конвертировании данных в DOM-представление - + Parse error at line %1, column %2: %3 Ошибка парсера на строке %1, в позиции %2: -%3. +%3 diff --git a/app/bin/resource/translations/workdata/convert_01.php b/app/bin/resource/translations/workdata/convert_01.php deleted file mode 100644 index 39eda4141..000000000 --- a/app/bin/resource/translations/workdata/convert_01.php +++ /dev/null @@ -1,44 +0,0 @@ -load($inFile); - - - // Список элементов - $contexts=$dom->getElementsByTagName('context'); - - echo ''; - - // Перебираются контексты - foreach($contexts as $context) - { - // Выясняется имя контекста - $names=$context->getElementsByTagName('name'); - $context_name=$names->item(0)->textContent; - - echo '\n"; - - $messages=$context->getElementsByTagName('message'); - - // Перебираются сообщения - foreach($messages as $message) - { - $sources=$message->getElementsByTagName('source'); - $sources_text=$sources->item(0)->textContent; - - echo "\n"; - echo '\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - - } - - echo '
'.$context_name."
'.$sources_text."--
'; - -?> \ No newline at end of file diff --git a/app/bin/resource/translations/workdata/mytetra_lang_01.html b/app/bin/resource/translations/workdata/mytetra_lang_01.html deleted file mode 100644 index 9f445a7e2..000000000 --- a/app/bin/resource/translations/workdata/mytetra_lang_01.html +++ /dev/null @@ -1,1091 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AddNewRecord
Enter new record--
Please enter title of record. --
Please enter text of record. --
New record cannot added--
AppConfigDialog
MyTetra config--
Main--
Misc--
AppConfigPage_Main
Data directory--
...--
Trash directory--
Trash size--
Mb--
Maximum quantity of file in trash--
files--
Select data directory--
Select trash directory--
Warning--
The data directory not exists or not readable.--
The trash directory not exists or not readable.--
AppConfigPage_Misc
Confirm before cut branch--
Print debug messages to console--
ConfigDialog
Warning--
For apply changes, program has close. -New changes actualise in next start.--
EditRecord
Please enter title of record.--
Record fields cannot edit--
Editor
Bold text (Ctrl+B)--
Italic text (Ctrl+I)--
Underline text (Ctrl+U)--
Ctrl+T--
Monospace text (Ctrl+T)--
Ctrl+M--
Code text (Ctrl+M). For format to code, please select paragraph(s).--
Ctrl+K--
Clear formatting to default (Ctrl+K). If select side string, clear symbols outline. If select paragrapf(s), clear all formatting.--
Numeric list--
Marked list--
Indent increase--
Indent decrease--
Ctrl+L--
Align at left (Ctrl+L)--
Ctrl+E--
Align on center (Ctrl+E)--
Ctrl+R--
Align at right (Ctrl+R)--
Ctrl+J--
Align to width (Ctrl+J)--
Ctrl+F--
Find text (Ctrl+F)--
Configure editor--
Show HTML code--
Show formating symbols--
Create new table--
Remove row(s)--
Remove column(s)--
Add row(s)--
Add column(s)--
Merge cells--
Split cell--
Search result--
String "--
" not found--
Append rows to table--
Append rows:--
Append columns to table--
Append columns:--
You must selected only single cell.--
EditorAddTableForm
Create new table--
Columns: --
Rows: --
Width: --
%--
Ok--
Cancel--
EditorConfigDialog
Editor config--
Font--
Misc--
EditorConfigFont
Default font--
Monospace font--
Enable set font size--
Code font--
Enable set indent size--
Monospace button preferences--
Code button preferences--
EditorConfigMisc
Indent step--
pix--
EditorContextMenu
Undo--
Redo--
Cut--
Copy--
Paste--
Select All--
EditorFindDialog
Match &case--
&Whole words--
Search &backward--
&Find--
Find in text--
EditorSplitCellForm
Split cell--
Split by horisontal to: --
Split by vertical to: --
Ok--
Cancel--
FindScreen
Find--
Any word--
All words--
Separate word--
Substring--
Find in: --
Title--
Author(s)--
Url--
Tags--
Text--
Can not start find process--
Please checked one or more find field--
Ok--
Too small query, try write at least one word.--
Search...--
FindTableWidget
Title--
About--
InfoFieldEnter
Title--
Author(s)--
Url--
Tags--
MainWindow
&File--
&Print...--
Print Preview...--
&Export PDF...--
&Quit--
&Tools--
Find in ba&se--
&Preferences--
&Help--
About MyTetra--
About Qt--
Print Document--
&Restore window--
Ma&ximize window--
Mi&nimize window--
MetaEditor
Url: --
Tags: --
PrintPreview
MyTetra - Print Preview--
&Print...--
Page Setup...--
Zoom In--
Zoom Out--
&Close--
QObject
Close--
RecordTableScreen
Add new--
Add new record--
Add new before--
Add new record before selected record--
Add new after--
Add new record after selected record--
Edit property (name, author, tags...)--
Edit record property (name, author, tags...)--
Delete--
Delete record(s)--
&Cut--
Cut record(s) to clipboard--
&Copy--
Copy record(s) to clipboard--
&Paste--
Paste record(s) from clipboard--
&Move Up--
Move record up--
&Move Down--
Move record down--
Find in base--
Cancel--
TreeScreen
Expand all subbranches--
Collapse all subbranches--
Move up branch--
Move down branch--
Insert new subbranch--
Insert new subbranch into selected branch--
Insert new sibling branch--
Insert new sibling branch after selected branch--
Edit branch name--
Edit name of selected branch--
Delete branch--
Delete selected branch and all subbranches--
Cut branch--
Cut branch and all subbranches, with copy to clipboard--
Copy branch--
Copy branch and all subbranches to clipboard--
Paste branch--
Paste sibling branch after selected--
Paste branch as subbranch--
Paste branch as subbranch for selected--
Unavailable action--
You select --
branches. -Please select one branch for moving.--
Ok--
branches. -Please select one branch for insert branch enabled.--
Insert new branch--
Branch name:--
Subbranch name:--
branches. -Please select one branch for edit name.--
Delete branch(es)--
Are you sure to delete branch(es) --
and it subbranches?--
Delete--
Are you sure to cut branch --
Cut--
Cancel--
Please select one branch for copy.--
Group of info--
Rename me--
XmlTree
Error--
Cannot read file %1: -%2.--
Error convert to DOM dataform--
Parse error at line %1, column %2: -%3--
\ No newline at end of file diff --git a/app/bin/resource/translations/workdata/mytetra_table_01.doc b/app/bin/resource/translations/workdata/mytetra_table_01.doc deleted file mode 100644 index 8f77b5e54..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_01.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_01.odt b/app/bin/resource/translations/workdata/mytetra_table_01.odt deleted file mode 100644 index 4bd101820..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_01.odt and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_02.doc b/app/bin/resource/translations/workdata/mytetra_table_02.doc deleted file mode 100644 index 2ad978871..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_02.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_03.doc b/app/bin/resource/translations/workdata/mytetra_table_03.doc deleted file mode 100644 index 4b8c74903..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_03.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_04.doc b/app/bin/resource/translations/workdata/mytetra_table_04.doc deleted file mode 100644 index fb2457c99..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_04.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_04_kirsanov.doc b/app/bin/resource/translations/workdata/mytetra_table_04_kirsanov.doc deleted file mode 100644 index 4b9a3982f..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_04_kirsanov.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_04_volk.doc b/app/bin/resource/translations/workdata/mytetra_table_04_volk.doc deleted file mode 100644 index 6a55d9b2d..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_04_volk.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/mytetra_table_05.doc b/app/bin/resource/translations/workdata/mytetra_table_05.doc deleted file mode 100644 index ecdb936cb..000000000 Binary files a/app/bin/resource/translations/workdata/mytetra_table_05.doc and /dev/null differ diff --git a/app/bin/resource/translations/workdata/xml_01.php b/app/bin/resource/translations/workdata/xml_01.php deleted file mode 100644 index e8daeb09a..000000000 --- a/app/bin/resource/translations/workdata/xml_01.php +++ /dev/null @@ -1,24 +0,0 @@ -load($inFile); - - - // Список элементов - $contexts=$dom->getElementsByTagName('context'); - - // Перебираются контексты - foreach($contexts as $context) - { - // Выясняется имя контекста - $name_elements=$context->getElementsByTagName('name'); - $context_name=$name_elements->item(0)->textContent; - - echo $context_name."\n"; - } - -?> \ No newline at end of file diff --git a/app/bin/translations.qrc b/app/bin/translations.qrc new file mode 100644 index 000000000..e893dbfab --- /dev/null +++ b/app/bin/translations.qrc @@ -0,0 +1,6 @@ + + + mytetra_ru.qm + mytetra_fr.qm + + diff --git a/app/mytetra.spec b/app/mytetra.spec deleted file mode 100644 index e1c055293..000000000 --- a/app/mytetra.spec +++ /dev/null @@ -1,45 +0,0 @@ -# no post install -#%define __os_install_post %{nil} -# no strip -#%define __strip /bin/true -# no debug package -#%define debug_package %{nil} -# disable automatic dependency processing -#AutoReqProv: no - -Name: ru.webhamster.mytetra -Version: 1.28.5 -Release: 1 -License: GPL v.3.0 -Summary: Personal manager for information accumulation -Url: http://webhamster.ru/site/page/index/articles/projectcode/138 -Group: Utility -Source0: %{name}-%{version}.tar.gz -#BuildRequires: pkgconfig(QtCore) -BuildRequires: libqt-devel - -%description -This is effective personal manager for information accumulation. - -%prep -%setup -q - -%build -# Add here commands to configure the package. -#%qmake -#qmake -makefile -nocache QMAKE_STRIP=: PREFIX=%{_prefix} - -# Add here commands to compile the package. -#make %{?jobs:-j%jobs} -#make %{?_smp_mflags} -make - -%install -# Add here commands to install the package. -#%qmake_install -make install INSTALL_ROOT=%{buildroot} - -%files -%defattr(-,root,root,-) -# %{_prefix}/* -/* diff --git a/app/src/CMakeLists.txt b/app/src/CMakeLists.txt new file mode 100644 index 000000000..aee93d287 --- /dev/null +++ b/app/src/CMakeLists.txt @@ -0,0 +1,45 @@ +add_subdirectory("libraries/qtSingleApplication") + +file(GLOB SRC_1 "libraries/*.cpp") +file(GLOB_RECURSE SRC_2 + "controllers/*.cpp" + "libraries/crypt/*.cpp" + "libraries/helpers/*.cpp" + "libraries/wyedit/*.cpp" + "models/*.cpp" + "views/*.cpp" +) + +add_executable(mytetra "main.cpp" "../bin/mytetra.qrc" "../bin/icons.qrc" ${SRC_1} ${SRC_2}) + +target_include_directories(mytetra PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + +target_link_libraries(mytetra PRIVATE qtsingleapplication ${QT_LIBS}) + +set_target_properties(mytetra PROPERTIES + POSITION_INDEPENDENT_CODE TRUE # rpmlint wants PIE + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/mytetra/" # for search qtSingleApplication +) + +target_compile_definitions(mytetra PRIVATE APPLICATION_VERSION="${APP_VERSION}") + +set(TS_FILES "../bin/resource/translations/mytetra_fr.ts" "../bin/resource/translations/mytetra_ru.ts") + +if(USE_QT6) + # require Qt 6.2 + qt_add_translations(mytetra TS_FILES ${TS_FILES} RESOURCE_PREFIX "resource/translations") +else() + # mask deprecation QLabel.pixmap(). In Qt6 return by value works again. + target_compile_definitions(mytetra PRIVATE "QT_DISABLE_DEPRECATED_BEFORE=0x050F00") + + configure_file("../bin/translations.qrc" ${CMAKE_CURRENT_BINARY_DIR} COPYONLY) + qt5_create_translation(QM_FILES ${SRC_1} ${SRC_2} ${TS_FILES}) + target_sources(mytetra PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/translations.qrc" ${QM_FILES}) +endif() + + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + install(TARGETS mytetra DESTINATION "${CMAKE_INSTALL_BINDIR}") +elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") + install(TARGETS mytetra DESTINATION "${WIN_INSTALL_DIR}") +endif() diff --git a/app/src/controllers/attachTable/AttachTableController.cpp b/app/src/controllers/attachTable/AttachTableController.cpp index 2ba74a73e..a370041e1 100644 --- a/app/src/controllers/attachTable/AttachTableController.cpp +++ b/app/src/controllers/attachTable/AttachTableController.cpp @@ -375,7 +375,7 @@ void AttachTableController::onSaveAsAttach(void) { // Диалог выбора имени директории QFileDialog fileSelectDialog; - fileSelectDialog.setFileMode(QFileDialog::DirectoryOnly); // Выбор директории + fileSelectDialog.setOption(QFileDialog::ShowDirsOnly, true); // Выбор директории fileSelectDialog.setWindowTitle(tr("Save attaches to directory...")); fileSelectDialog.setDirectory(QDir::homePath()); @@ -404,7 +404,6 @@ void AttachTableController::onSaveAsAttach(void) { QString attachType=attachTableData->getAttach(id).getField("type"); QString fileName=attachTableData->getFileNameById(id); - QString fromFileName=attachTableData->getInnerFileNameById(id); QString fromFullFileName=attachTableData->getAbsoluteInnerFileNameById(id); QString toFullFileName=toDir+"/"+fileName; @@ -475,7 +474,7 @@ void AttachTableController::onEditFileName(void) if(newFileName.size()==0) { - showMessageBox(tr("Cant save file with empty name.")); + showMessageBox(tr("Can't save file with empty name.")); return; } diff --git a/app/src/libraries/ActionLogger.cpp b/app/src/libraries/ActionLogger.cpp index b800b8a3d..19488f01a 100644 --- a/app/src/libraries/ActionLogger.cpp +++ b/app/src/libraries/ActionLogger.cpp @@ -48,10 +48,10 @@ ActionLogger::ActionLogger(QObject *pobj) actionStructure["moveBranchDown"]=(QStringList() << "branchId" << "branchName" ); actionStructure["deleteBranch"] =(QStringList() << "branchId" << "branchName" ); - actionStructure["startSyncro"]; - actionStructure["stopSyncro"]; - actionStructure["syncroProcessError"] = (QStringList() << "errCode" ); - actionStructure["syncroError"]; + actionStructure["startSynchro"]; + actionStructure["stopSynchro"]; + actionStructure["synchroProcessError"] = (QStringList() << "errCode" ); + actionStructure["synchroError"]; actionStructure["criticalError"] =(QStringList() << "errorMessage" ); @@ -84,7 +84,7 @@ void ActionLogger::openLogFileForWrite() logFile.setFileName(logFileName); // Открывается файл лога bool result=logFile.open(QIODevice::Append | QIODevice::Text); if(!result) - criticalError("Cant open log file "+logFileName+" for write data"); + criticalError("Can't open log file "+logFileName+" for write data"); } @@ -97,7 +97,7 @@ void ActionLogger::openLogFileForRead() logFile.setFileName(logFileName); // Открывается файл лога bool result=logFile.open(QIODevice::ReadOnly | QIODevice::Text); if(!result) - criticalError("Cant open log file "+logFileName+" for readind data"); + criticalError("Can't open log file "+logFileName+" for readind data"); } @@ -232,10 +232,7 @@ QString ActionLogger::getFullDescription(QMap iData) line=tr("Program stop"); else if( iData["a"] == "createRecord") - line=tr("Create note \"%1\" with ID %2 in tree item \"%3\" with ID %4").arg( iData["recordName"] ). - arg( iData["recordId"] ). - arg( iData["branchName"] ). - arg( iData["branchId"] ); + line=tr("Create note \"%1\" with ID %2 in tree item \"%3\" with ID %4").arg(iData["recordName"], iData["recordId"], iData["branchName"], iData["branchId"]); else if( iData["a"] == "createCryptRecord") { @@ -251,15 +248,11 @@ QString ActionLogger::getFullDescription(QMap iData) iData["branchName"]=CryptService::decryptString(globalParameters.getCryptKey(), iData["branchName"]); } - line=tr("Create crypt note \"%1\" with ID %2 in tree item \"%3\" with ID %4").arg( iData["recordName"] ). - arg( iData["recordId"] ). - arg( iData["branchName"] ). - arg( iData["branchId"] ); + line=tr("Create crypt note \"%1\" with ID %2 in tree item \"%3\" with ID %4").arg(iData["recordName"], iData["recordId"], iData["branchName"], iData["branchId"]); } else if( iData["a"] == "editRecord") - line=tr("Edit fields of note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Edit fields of note \"%1\" with ID %2").arg( iData["recordName"], iData["recordId"] ); else if( iData["a"] == "editCryptRecord") { @@ -269,14 +262,12 @@ QString ActionLogger::getFullDescription(QMap iData) else iData["recordName"]=CryptService::decryptString(globalParameters.getCryptKey(), iData["recordName"]); - line=tr("Edit fields of crypt note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Edit fields of crypt note \"%1\" with ID %2").arg(iData["recordName"], iData["recordId"]); } else if( iData["a"] == "editRecordText") - line=tr("Edit text of note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Edit text of note \"%1\" with ID %2").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "editCryptRecordText") { @@ -286,57 +277,46 @@ QString ActionLogger::getFullDescription(QMap iData) else iData["recordName"]=CryptService::decryptString(globalParameters.getCryptKey(), iData["recordName"]); - line=tr("Edit text of crypt note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Edit text of crypt note \"%1\" with ID %2").arg(iData["recordName"], iData["recordId"]); } else if( iData["a"] == "moveRecordUp") - line=tr("Move up note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Move up note \"%1\" with ID %2").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "moveRecordDown") - line=tr("Move down note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Move down note \"%1\" with ID %2").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "deleteRecord") - line=tr("Delete note \"%1\" with ID %2").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Delete note \"%1\" with ID %2").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "copyRecordToBuffer") - line=tr("Copy note \"%1\" with ID %2 to clipboard").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Copy note \"%1\" with ID %2 to clipboard").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "cutRecordToBuffer") - line=tr("Cut note \"%1\" with ID %2 to clipboard").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Cut note \"%1\" with ID %2 to clipboard").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "pasteRecordFromBuffer") // Добавить, какой новый ID у вставленной записи получился - line=tr("Paste note \"%1\" with ID %2 from clipboard").arg( iData["recordName"] ). - arg( iData["recordId"]); + line=tr("Paste note \"%1\" with ID %2 from clipboard").arg(iData["recordName"], iData["recordId"]); else if( iData["a"] == "startDragRecord") - line=tr("Start drag note \"%1\" with ID %2 from tree item \"%3\" with ID %4").arg( iData["recordName"] ). - arg( iData["recordId"] ). - arg( iData["branchName"] ). - arg( iData["branchId"] ); + line=tr("Start drag note \"%1\" with ID %2 from tree item \"%3\" with ID %4").arg(iData["recordName"], iData["recordId"], iData["branchName"], iData["branchId"]); + else if( iData["a"] == "dropRecord") - line=tr("Drop note \"%1\" with ID %2 to tree item \"%3\" with ID %4").arg( iData["recordName"] ). - arg( iData["recordId"] ). - arg( iData["branchName"] ). - arg( iData["branchId"] ); + line=tr("Drop note \"%1\" with ID %2 to tree item \"%3\" with ID %4").arg(iData["recordName"], iData["recordId"], iData["branchName"], iData["branchId"]); + - else if( iData["a"] == "startSyncro") + else if( iData["a"] == "startSynchro") line=tr("Start synchronization"); - else if( iData["a"] == "stopSyncro") + else if( iData["a"] == "stopSynchro") line=tr("Stop synchronization"); - else if( iData["a"] == "syncroProcessError") + else if( iData["a"] == "synchroProcessError") line=tr("Synchronization process error detected. Error code: %1").arg( iData["errCode"]); - else if( iData["a"] == "syncroError") + else if( iData["a"] == "synchroError") line=tr("Synchronization error"); else if( iData["a"] == "criticalError") @@ -388,7 +368,7 @@ void ActionLogger::addAction(QString iName, QMap iData) line+="v=\"" + QString().setNum(version) +"\" "; // Добавляется атрибут со временем совершения данного действия (timestamp) - uint timestamp=QDateTime::currentDateTime().toTime_t(); + uint timestamp=QDateTime::currentDateTime().toSecsSinceEpoch(); line+="t=\"" + QString().setNum(timestamp) +"\" "; // Добавляется атрибут с именем действия diff --git a/app/src/libraries/ClipboardBranch.cpp b/app/src/libraries/ClipboardBranch.cpp index 67fe77d19..15019dfad 100644 --- a/app/src/libraries/ClipboardBranch.cpp +++ b/app/src/libraries/ClipboardBranch.cpp @@ -105,12 +105,8 @@ void ClipboardBranch::printIdTree(void) const // Добавление ветки void ClipboardBranch::addBranch( QString parent_id, QMap branch_fields) { - QMap line; - - line["parent_id"]=parent_id; - line.unite(branch_fields); - - branchData.branch << line; + branch_fields["parent_id"]=parent_id; + branchData.branch << branch_fields; } @@ -161,7 +157,11 @@ QStringList ClipboardBranch::formats() const } -QVariant ClipboardBranch::retrieveData(const QString &format,QVariant::Type preferredType) const +#if QT_VERSION > 0x060000 + QVariant ClipboardBranch::retrieveData(const QString &format, QMetaType preferredType) const +#else + QVariant ClipboardBranch::retrieveData(const QString &format, QVariant::Type preferredType) const +#endif { Q_UNUSED(preferredType) diff --git a/app/src/libraries/ClipboardBranch.h b/app/src/libraries/ClipboardBranch.h index 5a94e4137..5c89fbaf0 100644 --- a/app/src/libraries/ClipboardBranch.h +++ b/app/src/libraries/ClipboardBranch.h @@ -68,8 +68,12 @@ class ClipboardBranch : public QMimeData protected: // Этот метод QMimeData надо переопределить, так как он виртуальный - QVariant retrieveData(const QString &format,QVariant::Type preferredType) const; - +#if QT_VERSION > 0x060000 + QVariant retrieveData(const QString &format, QMetaType preferredType) const; +#else + QVariant retrieveData(const QString &format, QVariant::Type preferredType) const; +#endif + private: CLIPB_BRANCH_STRUCT branchData; // Данные, которые передаются через буфер обмена diff --git a/app/src/libraries/ClipboardRecords.cpp b/app/src/libraries/ClipboardRecords.cpp index 356081d96..bb635842c 100644 --- a/app/src/libraries/ClipboardRecords.cpp +++ b/app/src/libraries/ClipboardRecords.cpp @@ -168,8 +168,11 @@ QStringList ClipboardRecords::formats() const return clipbRecordsFormat; } - -QVariant ClipboardRecords::retrieveData(const QString &format,QVariant::Type preferredType) const +#if QT_VERSION > 0x060000 + QVariant ClipboardRecords::retrieveData(const QString &format, QMetaType preferredType) const +#else + QVariant ClipboardRecords::retrieveData(const QString &format, QVariant::Type preferredType) const +#endif { Q_UNUSED(preferredType); diff --git a/app/src/libraries/ClipboardRecords.h b/app/src/libraries/ClipboardRecords.h index d909c2d94..cf54cf0a1 100644 --- a/app/src/libraries/ClipboardRecords.h +++ b/app/src/libraries/ClipboardRecords.h @@ -7,8 +7,8 @@ #include // class Record; -#include "models/recordTable/Record.h" -#include "models/attachTable/AttachTableData.h" +#include "../models/recordTable/Record.h" +#include "../models/attachTable/AttachTableData.h" // Определяется структура данных набора записей // которая будет передаваться через буфер обмена @@ -45,7 +45,11 @@ class ClipboardRecords : public QMimeData protected: // Этот метод QMimeData надо переопределить, так как он виртуальный - QVariant retrieveData(const QString &format,QVariant::Type preferredType) const; +#if QT_VERSION > 0x060000 + QVariant retrieveData(const QString &format, QMetaType preferredType) const; +#else + QVariant retrieveData(const QString &format, QVariant::Type preferredType) const; +#endif private: CLIPB_RECORDS_STRUCT records; // Данные, которые передаются через буфер обмена diff --git a/app/src/libraries/Downloader.cpp b/app/src/libraries/Downloader.cpp index 3bae48d26..e7a2d88c4 100644 --- a/app/src/libraries/Downloader.cpp +++ b/app/src/libraries/Downloader.cpp @@ -185,7 +185,7 @@ QString Downloader::getAboutText() QVector Downloader::getMemoryFiles() const { if(downloadMode==disk) - criticalError("Cant execute Downloader::getMemoryFiles() for disk mode. Current Download instance use memory mode."); + criticalError("Can't execute Downloader::getMemoryFiles() for disk mode. Current Download instance use memory mode."); return memoryFiles; } @@ -194,7 +194,7 @@ QVector Downloader::getMemoryFiles() const QMap Downloader::getReferencesAndMemoryFiles() const { if(downloadMode==disk) - criticalError("Cant execute Downloader::getReferencesAndMemoryFiles() for disk mode. Current Download instance use memory mode."); + criticalError("Can't execute Downloader::getReferencesAndMemoryFiles() for disk mode. Current Download instance use memory mode."); QMap tempReferencesAndMemoryFiles; @@ -208,7 +208,7 @@ QMap Downloader::getReferencesAndMemoryFiles() const QMap Downloader::getReferencesAndFileNames() const { if(downloadMode==memory) - criticalError("Cant execute Downloader::getReferencesAndFileNames() for memory mode. Current Download instance use disk mode."); + criticalError("Can't execute Downloader::getReferencesAndFileNames() for memory mode. Current Download instance use disk mode."); QMap tempReferencesAndFileNames; @@ -222,7 +222,7 @@ QMap Downloader::getReferencesAndFileNames() const QStringList Downloader::getDiskFilesList() const { if(downloadMode==memory) - criticalError("Cant execute Downloader::getDiskFilesList() for memory mode. Current Download instance use disk mode."); + criticalError("Can't execute Downloader::getDiskFilesList() for memory mode. Current Download instance use disk mode."); return QStringList(); } @@ -362,7 +362,7 @@ void Downloader::onFileDownloadFinished(QNetworkReply *reply) isSuccessFlag=true; - emit accept(); // Программно закрывается окно диалога, как будто нажали Ok + accept(); // Программно закрывается окно диалога, как будто нажали Ok } } diff --git a/app/src/libraries/Downloader.h b/app/src/libraries/Downloader.h index 7a8f8da96..dcfc53421 100644 --- a/app/src/libraries/Downloader.h +++ b/app/src/libraries/Downloader.h @@ -2,17 +2,10 @@ #define DOWNLOADER_H #include +#include #include #include -class QString; -class QStringList; -class QByteArray; -class QPushButton; -class QLabel; -class QTableWidget; -class QNetworkReply; -class QUrl; class Downloader : public QDialog { diff --git a/app/src/libraries/GlobalParameters.cpp b/app/src/libraries/GlobalParameters.cpp index 25eb6b7f8..8d88127dc 100644 --- a/app/src/libraries/GlobalParameters.cpp +++ b/app/src/libraries/GlobalParameters.cpp @@ -24,6 +24,8 @@ #ifdef Q_OS_WIN32 #include "windows.h" +#elif defined(Q_OS_LINUX) +#include #endif @@ -59,8 +61,6 @@ void GlobalParameters::init(void) pointStatusBar=nullptr; windowSwitcher=nullptr; - initCodepage(); // устанавливаются кодеки локали и кодеки консоли - // После установки кодеков можно показать имя бинарника, и оно должно отобразиться правильно // даже если путь содержит каталог с национальными символами qDebug() << "Set main program file to " << mainProgramFile; @@ -69,64 +69,6 @@ void GlobalParameters::init(void) } -QString GlobalParameters::getInitSystemCodepage() -{ -#ifdef Q_OS_WIN32 - return "CP "+QString::number( GetACP() ); -#endif - -#ifdef Q_OS_LINUX - return "UTF-8"; -#endif - - return ""; -} - - -QString GlobalParameters::getInitConsoleCodepage() -{ -#ifdef Q_OS_WIN32 - return "CP "+QString::number( GetOEMCP() ); -#endif - -#ifdef Q_OS_LINUX - return "UTF-8"; -#endif - - return ""; -} - - -void GlobalParameters::initCodepage(void) -{ - mSystemCodepage=getInitSystemCodepage(); - qDebug() << "System code page: " << mSystemCodepage; - - mConsoleCodepage=getInitConsoleCodepage(); - qDebug() << "Console code page: " << mConsoleCodepage; - - // Системная кодировка (кодировка локали) устанавливается как основная - if(mSystemCodepage.size()>0) { - QTextCodec::setCodecForLocale(QTextCodec::codecForName(mSystemCodepage.toLatin1())); - } -} - - -// Системная кодировка, она же кодировка локали -// В этой кодировке происходит работа с именами файлов и директорий -QString GlobalParameters::getSystemCodepage() -{ - return mSystemCodepage; -} - - -// Кодировка консоли -QString GlobalParameters::getConsoleCodepage() -{ - return mConsoleCodepage; -} - - // Инициализация рабочей директории // Если рабочая директория уже существует, она будет установлена как рабочая // Если ребочая директория не будет найдена, будут создана новая рабочая директория @@ -263,7 +205,7 @@ void GlobalParameters::createFirstProgramFiles(QString dirName) // Синхронизация файловой системы, почему-то после создания файлы // не всегда доступны на Linux. Под windows такой утилиты нет в стандартной поставке #ifdef Q_OS_LINUX - std::system("sync"); + sync(); #endif } @@ -340,7 +282,7 @@ bool GlobalParameters::findWorkDirectory(void) // Если рабочая директория не определена if(workDirectory.length()==0) { - qDebug() << "Cant find work directory with mytetra data"; + qDebug() << "Can't find work directory with mytetra data"; return false; } else @@ -541,18 +483,6 @@ WindowSwitcher *GlobalParameters::getWindowSwitcher() } -void GlobalParameters::setSyncroCommandRun(CommandRun *point) -{ - syncroCommandRun=point; -} - - -CommandRun *GlobalParameters::getSyncroCommandRun() -{ - return syncroCommandRun; -} - - void GlobalParameters::setCryptKey(QByteArray hash) { passwordHash=hash; diff --git a/app/src/libraries/GlobalParameters.h b/app/src/libraries/GlobalParameters.h index dc27d39d1..9027ddf19 100644 --- a/app/src/libraries/GlobalParameters.h +++ b/app/src/libraries/GlobalParameters.h @@ -24,9 +24,6 @@ class GlobalParameters : public QObject void init(void); - QString getSystemCodepage(void); - QString getConsoleCodepage(void); - // Получение рабочей директории. Рабочая директория - это та, где лежит файл conf.ini QString getWorkDirectory(void); @@ -54,9 +51,6 @@ class GlobalParameters : public QObject void setWindowSwitcher(WindowSwitcher *point); WindowSwitcher *getWindowSwitcher(); - void setSyncroCommandRun(CommandRun *point); - CommandRun *getSyncroCommandRun(); - void setCryptKey(QByteArray hash); QByteArray getCryptKey(void); @@ -83,10 +77,6 @@ class GlobalParameters : public QObject private: - void initCodepage(void); - QString getInitSystemCodepage(); - QString getInitConsoleCodepage(); - void initWorkDirectory(void); bool findWorkDirectory(void); bool isMytetraIniConfig(QString fileName); @@ -100,14 +90,10 @@ class GlobalParameters : public QObject MetaEditor *pointMetaEditor=nullptr; QStatusBar *pointStatusBar=nullptr; WindowSwitcher *windowSwitcher=nullptr; - CommandRun *syncroCommandRun=nullptr; //! Объект выполнения команд синхронизации базы MyTetra QString mainProgramFile; QString workDirectory; - QString mSystemCodepage; - QString mConsoleCodepage; - QByteArray passwordHash; //! Язык, который был автоопределен если запускалась инсталляция базы знаний. diff --git a/app/src/libraries/IconSelectDialog.cpp b/app/src/libraries/IconSelectDialog.cpp index 0e0cd5354..8fca41536 100644 --- a/app/src/libraries/IconSelectDialog.cpp +++ b/app/src/libraries/IconSelectDialog.cpp @@ -146,7 +146,7 @@ void IconSelectDialog::setupUI() void IconSelectDialog::setupSignals() { // Выбор раздела - connect(§ionComboBox, qOverload(&QComboBox::currentIndexChanged), + connect(§ionComboBox, qOverload(&QComboBox::currentIndexChanged), this, &IconSelectDialog::onSectionCurrentIndexChanged); // Выбор иконки @@ -207,7 +207,7 @@ void IconSelectDialog::setPath(QString iPath) // Если переданный путь не является директорией if( !QFileInfo(iPath).isDir() ) { - criticalError("Cant set icon directory path for IconSelectDialog. Path is not directory: "+iPath); + criticalError("Can't set icon directory path for IconSelectDialog. Path is not directory: "+iPath); return; } @@ -248,22 +248,12 @@ void IconSelectDialog::setPath(QString iPath) // Если была задана секция по-умолчанию - if(defaultSectionName.length()>0) + if(defaultSectionIndex != -1) { - bool find=false; - for(int i=0; i0) { - criticalError("Cant set icon default section. Set default section before set path."); + criticalError("Can't set icon default section. Set default section before set path."); return; } - - defaultSectionName=iSectionName; + for (int i = 0; sectionComboBox.count(); ++i) + if(sectionComboBox.itemText(i) == iSectionName) { + defaultSectionIndex = i; + break; + } } QString IconSelectDialog::getCurrentSection() { - return currentSectionName; + return sectionComboBox.itemText(currentSectionIndex); } // Обновление экранного списка иконок void IconSelectDialog::updateIcons() { - if(defaultSectionName.length()>0) - onSectionCurrentIndexChanged(defaultSectionName); + if(defaultSectionIndex != -1) + onSectionCurrentIndexChanged(defaultSectionIndex); else - onSectionCurrentIndexChanged( sectionComboBox.itemText(0) ); + onSectionCurrentIndexChanged(0); } // Слот при изменении строки раздела в sectionComboBox -void IconSelectDialog::onSectionCurrentIndexChanged(const QString &iText) +void IconSelectDialog::onSectionCurrentIndexChanged(int idx) { // Если еще не разрешено обновлять список иконок if(!enableIconUpdate) return; - currentSectionName=iText; + currentSectionIndex=idx; // Очищается экранный список иконок iconList.clear(); // todo: Здесь сегфолт... Разобраться. - QString iconDirName=path+"/"+iText; + QString iconDirName=path+"/"+sectionComboBox.itemText(idx); QDir dir(iconDirName); dir.setFilter(QDir::Files | QDir::Readable); @@ -319,7 +312,7 @@ void IconSelectDialog::onSectionCurrentIndexChanged(const QString &iText) // Если в выбранной секции нет никаких иконок if(iconFileList.count()==0) { - showMessageBox(tr("The section \"%1\" has not any icons").arg(iText)); + showMessageBox(tr("The section \"%1\" has not any icons").arg(sectionComboBox.itemText(idx))); this->close(); return; } @@ -353,7 +346,7 @@ void IconSelectDialog::onIconItemSelectionChanged() // QString shortSelectFileName=iconList.selectedItems().at(0)->text(); // Неясно, но похоже что после этой конструкции идет сегфолт в методе clean() QString shortSelectFileName=iconList.currentItem()->text(); - currentFileName=path+"/"+currentSectionName+"/"+shortSelectFileName; + currentFileName=path+"/"+sectionComboBox.itemText(currentSectionIndex)+"/"+shortSelectFileName; } diff --git a/app/src/libraries/IconSelectDialog.h b/app/src/libraries/IconSelectDialog.h index 0dc78f3ba..b6d99b4de 100644 --- a/app/src/libraries/IconSelectDialog.h +++ b/app/src/libraries/IconSelectDialog.h @@ -35,7 +35,7 @@ protected slots: void onRemoveIconClick(); void onOkClick(); void onCancelClick(); - void onSectionCurrentIndexChanged(const QString &iText); + void onSectionCurrentIndexChanged(int idx); void updateIcons(); void onIconItemSelectionChanged(); @@ -55,8 +55,8 @@ protected slots: QProgressBar progressBar; QString path; - QString defaultSectionName; - QString currentSectionName; + int defaultSectionIndex = -1; + int currentSectionIndex; bool enableIconUpdate; diff --git a/app/src/libraries/PeriodicSyncro.cpp b/app/src/libraries/PeriodicSynchro.cpp similarity index 75% rename from app/src/libraries/PeriodicSyncro.cpp rename to app/src/libraries/PeriodicSynchro.cpp index f76b19693..5f716de70 100644 --- a/app/src/libraries/PeriodicSyncro.cpp +++ b/app/src/libraries/PeriodicSynchro.cpp @@ -2,7 +2,7 @@ #include "main.h" #include "TimerMonitoring.h" -#include "PeriodicSyncro.h" +#include "PeriodicSynchro.h" #include "models/appConfig/AppConfig.h" #include "views/mainWindow/MainWindow.h" #include "libraries/helpers/ObjectHelper.h" @@ -12,18 +12,18 @@ extern AppConfig mytetraConfig; // Переопределяемый метод -bool PeriodicSyncro::isStartEnabled() +bool PeriodicSynchro::isStartEnabled() { - return mytetraConfig.getEnablePeriodicSyncro(); + return mytetraConfig.getEnablePeriodicSynchro(); } // Действия, происходящие по таймеру -void PeriodicSyncro::timerEvent(QTimerEvent *event) +void PeriodicSynchro::timerEvent(QTimerEvent *event) { Q_UNUSED(event) - qDebug() << "In timer PeriodicSyncro working method"; + qDebug() << "In timer PeriodicSynchro working method"; // Если команда синхронизации пуста, нечего выполнять if(mytetraConfig.get_synchrocommand().trimmed().length()==0) diff --git a/app/src/libraries/PeriodicSynchro.h b/app/src/libraries/PeriodicSynchro.h new file mode 100644 index 000000000..e5118773d --- /dev/null +++ b/app/src/libraries/PeriodicSynchro.h @@ -0,0 +1,19 @@ +#ifndef _PERIODICSYNCHRO_H_ +#define _PERIODICSYNCHRO_H_ + +#include "TimerMonitoring.h" + + +class PeriodicSynchro : public TimerMonitoring +{ + Q_OBJECT + +protected: + + bool isStartEnabled(); + void timerEvent(QTimerEvent *event); + +}; + +#endif /* _PERIODICSYNCHRO_H_ */ + diff --git a/app/src/libraries/PeriodicSyncro.h b/app/src/libraries/PeriodicSyncro.h deleted file mode 100644 index 73c82d6b6..000000000 --- a/app/src/libraries/PeriodicSyncro.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _PERIODICSYNCRO_H_ -#define _PERIODICSYNCRO_H_ - -#include "TimerMonitoring.h" - - -class PeriodicSyncro : public TimerMonitoring -{ - Q_OBJECT - -protected: - - bool isStartEnabled(); - void timerEvent(QTimerEvent *event); - -}; - -#endif /* _PERIODICSYNCRO_H_ */ - diff --git a/app/src/libraries/RandomInitter.cpp b/app/src/libraries/RandomInitter.cpp deleted file mode 100644 index 60e06397d..000000000 --- a/app/src/libraries/RandomInitter.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include - -#include -#include - -#include "RandomInitter.h" - - -RandomInitter::RandomInitter() -{ - -} - - -void RandomInitter::init(long humanGenerateSeedShift) -{ - long seed1=getMilliCount(); - srand( static_cast( seed1+humanGenerateSeedShift+rand() ) ); - - long delay=rand()%1000; - long r=0; - for(long i=0; i divMod ? QDateTime::currentMSecsSinceEpoch()/divMod : divMod/QDateTime::currentMSecsSinceEpoch(); - - long seed3=seed1+seed2; - long seed=seed3; - - // qDebug() << "Random generator seed: " << seed; - - srand( static_cast( seed ) ); - - // qDebug() << "Random number: " << rand(); -} - - -long RandomInitter::getMilliCount() -{ - #if TARGET_OS!=ANDROID_OS - return static_cast(QDateTime::currentMSecsSinceEpoch()); - #else - long ms; // Milliseconds - struct timespec spec; - - clock_gettime(CLOCK_REALTIME, &spec); - - ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds - - return static_cast(ms); - #endif -} - diff --git a/app/src/libraries/RandomInitter.h b/app/src/libraries/RandomInitter.h deleted file mode 100644 index a7d701dc2..000000000 --- a/app/src/libraries/RandomInitter.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef RANDOMINITTER_H -#define RANDOMINITTER_H - - -class RandomInitter -{ -public: - RandomInitter(); - - static void init(long humanGenerateSeedShift); - -private: - static long getMilliCount(); - -}; - -#endif // RANDOMINITTER_H diff --git a/app/src/libraries/ShortcutManager.cpp b/app/src/libraries/ShortcutManager.cpp index 7351df10c..831c45b4c 100644 --- a/app/src/libraries/ShortcutManager.cpp +++ b/app/src/libraries/ShortcutManager.cpp @@ -171,8 +171,8 @@ void ShortcutManager::initDefaultKeyTable() defaultKeyTable.insert("misc-focusNoteTable", Data{ QKeySequence("F6"), tr("Set focus to notes table"), tr("") }); defaultKeyTable.insert("misc-focusEditor", Data{ QKeySequence("F4"), tr("Set focus to editor"), tr("") }); defaultKeyTable.insert("misc-findInBase", Data{ QKeySequence("Ctrl+Shift+F"), tr("Find in base"), tr("") }); - defaultKeyTable.insert("misc-syncro", Data{ QKeySequence("F9"), tr("Synchronization"), tr("Run synchronization") }); - defaultKeyTable.insert("misc-editConfirm", Data{ QKeySequence(Qt::CTRL + Qt::Key_Return), tr("Ok"), tr("") }); + defaultKeyTable.insert("misc-synchro", Data{ QKeySequence("F9"), tr("Synchronization"), tr("Run synchronization") }); + defaultKeyTable.insert("misc-editConfirm", Data{ QKeySequence(Qt::CTRL | Qt::Key_Return), tr("Ok"), tr("") }); defaultKeyTable.insert("misc-print", Data{ QKeySequence("Ctrl+P"), tr("Print"), tr("") }); defaultKeyTable.insert("misc-exportPdf", Data{ QKeySequence("Ctrl+Shift+D"), tr("Export PDF"), tr("") }); defaultKeyTable.insert("misc-quit", Data{ QKeySequence("Ctrl+Q"), tr("Quit"), tr("") }); @@ -470,7 +470,7 @@ bool ShortcutManager::isOverloadEnable(QString sectionNameA, QString sectionName bool ShortcutManager::isDirectOverloadEnable(QString sectionNameA, QString sectionNameB) { // Перебор списка с настройками допустимости перекрытый - for(auto sectionData : overloadSection) + for(const auto & sectionData : overloadSection) { QStringList pair=sectionData.split(":"); diff --git a/app/src/libraries/TrashMonitoring.cpp b/app/src/libraries/TrashMonitoring.cpp index 6f9de63af..a3662a9c4 100644 --- a/app/src/libraries/TrashMonitoring.cpp +++ b/app/src/libraries/TrashMonitoring.cpp @@ -41,27 +41,17 @@ void TrashMonitoring::init(QString trashPath) for(int i=0;i= QT_VERSION_CHECK(5, 10, 0)) - unsigned int fileTime=fileInfoList.at(i).birthTime().toTime_t(); - #else - unsigned int fileTime=fileInfoList.at(i).created().toTime_t(); - #endif - - unsigned int fileSize=static_cast( fileInfoList.at(i).size() ); - // Директории с именами "." и ".." обрабатывать не нужно if(fileName=="." || fileName=="..") continue; + unsigned int fileSize=fileInfoList.at(i).size(); + // Увеличивается подсчитываемый размер директории dirSize=dirSize+fileSize; // Информация о файле добавляется в таблицу - FileData currentFileData; - currentFileData.fileName=fileName; - currentFileData.fileTime=fileTime; - currentFileData.fileSize=fileSize; + FileData currentFileData = {fileName, fileSize}; filesTable << currentFileData; } @@ -73,9 +63,6 @@ void TrashMonitoring::init(QString trashPath) // принимает имя файла без пути к директории void TrashMonitoring::addFile(QString filename) { - // Выясняется время создания файла берется текущее, особой точности не нужно - unsigned int fileTime=(QDateTime::currentDateTime()).toTime_t(); - // Выясняется размер файла QFile currentFile(path+"/"+filename); unsigned int fileSize=currentFile.size(); @@ -86,7 +73,6 @@ void TrashMonitoring::addFile(QString filename) // Информация о файле добавляется в таблицу FileData currentfiledata; currentfiledata.fileName=filename; - currentfiledata.fileTime=fileTime; currentfiledata.fileSize=fileSize; filesTable.insert(0,currentfiledata); diff --git a/app/src/libraries/TrashMonitoring.h b/app/src/libraries/TrashMonitoring.h index 8868bd27b..db6efd80d 100644 --- a/app/src/libraries/TrashMonitoring.h +++ b/app/src/libraries/TrashMonitoring.h @@ -31,7 +31,6 @@ class TrashMonitoring struct FileData { QString fileName; - unsigned int fileTime; unsigned int fileSize; }; diff --git a/app/src/libraries/crypt/CryptService.cpp b/app/src/libraries/crypt/CryptService.cpp index c8247fb67..d12f14234 100644 --- a/app/src/libraries/crypt/CryptService.cpp +++ b/app/src/libraries/crypt/CryptService.cpp @@ -1,8 +1,8 @@ -#include "main.h" #include "CryptService.h" #include "RC5Simple.h" #include "Password.h" +#include #include #include "libraries/helpers/DebugHelper.h" @@ -20,7 +20,7 @@ CryptService::~CryptService() } -void CryptService::convertByteArrayToVector(const QByteArray &qba, vector &vec) +void CryptService::convertByteArrayToVector(const QByteArray &qba, std::vector &vec) { unsigned int size=qba.size(); vec.resize(size, 0); @@ -28,9 +28,9 @@ void CryptService::convertByteArrayToVector(const QByteArray &qba, vector &vec, QByteArray &qba) +void CryptService::convertVectorToByteArray(const std::vector &vec, QByteArray &qba) { - unsigned int size=vec.size(); + unsigned int size=static_cast(vec.size()); qba.clear(); qba.append( (const char *)&vec[0], size*sizeof(unsigned char) ); @@ -59,13 +59,13 @@ QString CryptService::encryptString(QByteArray key, QString line) // qDebug() << "Encrypt source" << line; - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); - vector vectorLineIn; + std::vector vectorLineIn; convertByteArrayToVector(line.toUtf8(), vectorLineIn); - vector vectorLineOut; + std::vector vectorLineOut; // Шифрация RC5Simple rc5; @@ -97,7 +97,7 @@ QString CryptService::decryptString(QByteArray key, QString line) qDebug() << "Decrypt key" << key.toHex(); */ - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); /* @@ -107,7 +107,7 @@ QString CryptService::decryptString(QByteArray key, QString line) printf("\n"); */ - vector vectorLineIn; + std::vector vectorLineIn; // Заменен вызов line.toAscii на line.toLatin1 чтобы шла компиляция в Qt 5.2. // Эта замена допустима, так как в Base64 используются только символы латиницы и ограниченный набор прочих символов @@ -120,7 +120,7 @@ QString CryptService::decryptString(QByteArray key, QString line) printf("\n"); */ - vector vectorLineOut; + std::vector vectorLineOut; // Дешифрация RC5Simple rc5; @@ -144,13 +144,13 @@ QByteArray CryptService::encryptByteArray(QByteArray key, QByteArray data) if(data.size()==0) return QByteArray(); - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); - vector vectorDataIn; + std::vector vectorDataIn; convertByteArrayToVector(data, vectorDataIn); - vector vectorDataOut; + std::vector vectorDataOut; // Шифрация RC5Simple rc5; @@ -169,13 +169,13 @@ QByteArray CryptService::decryptByteArray(QByteArray key, QByteArray data) if(data.size()==0) return QByteArray(); - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); - vector vectorDataIn; + std::vector vectorDataIn; convertByteArrayToVector(data, vectorDataIn); - vector vectorDataOut; + std::vector vectorDataOut; // Дешифрация RC5Simple rc5; @@ -194,13 +194,13 @@ QByteArray CryptService::encryptStringToByteArray(QByteArray key, QString line) if(line=="") return QByteArray(); - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); - vector vectorLineIn; + std::vector vectorLineIn; convertByteArrayToVector(line.toUtf8(), vectorLineIn); - vector vectorLineOut; + std::vector vectorLineOut; // Шифрация RC5Simple rc5; @@ -219,13 +219,13 @@ QString CryptService::decryptStringFromByteArray(QByteArray key, QByteArray data if(data.length()==0) return QString(); - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); - vector vectorDataIn; + std::vector vectorDataIn; convertByteArrayToVector(data, vectorDataIn); - vector vectorDataOut; + std::vector vectorDataOut; // Дешифрация RC5Simple rc5; @@ -263,15 +263,15 @@ void CryptService::encDecFileSmart(QByteArray key, QString fileName, int mode) QFile file(fileName); if(!file.open(QIODevice::ReadOnly)) - criticalError("encDecFileSmart() : Cant open binary file "+fileName+" for reading."); + criticalError("encDecFileSmart() : Can't open binary file "+fileName+" for reading."); - vector vectorKey; + std::vector vectorKey; convertByteArrayToVector(key, vectorKey); - vector vectorDataIn; + std::vector vectorDataIn; convertByteArrayToVector(file.readAll(), vectorDataIn); - vector vectorDataOut; + std::vector vectorDataOut; file.close(); @@ -289,7 +289,7 @@ void CryptService::encDecFileSmart(QByteArray key, QString fileName, int mode) convertVectorToByteArray(vectorDataOut, result); if(!file.open(QIODevice::WriteOnly)) - criticalError("encryptFile() : Cant open binary file "+fileName+" for write."); + criticalError("encryptFile() : Can't open binary file "+fileName+" for write."); file.write(result); QApplication::restoreOverrideCursor(); diff --git a/app/src/libraries/crypt/CryptService.h b/app/src/libraries/crypt/CryptService.h index 4249479c8..16395c1f4 100644 --- a/app/src/libraries/crypt/CryptService.h +++ b/app/src/libraries/crypt/CryptService.h @@ -1,8 +1,8 @@ #ifndef __CRYPTSERVICE_H__ #define __CRYPTSERVICE_H__ -#include +#include #include #include @@ -17,8 +17,8 @@ class CryptService CryptService(); virtual ~CryptService(); - static void convertByteArrayToVector(const QByteArray &qba, vector &vec); - static void convertVectorToByteArray(const vector &vec, QByteArray &qba); + static void convertByteArrayToVector(const QByteArray &qba, std::vector &vec); + static void convertVectorToByteArray(const std::vector &vec, QByteArray &qba); static QString encryptString(QByteArray key, QString line); static QString decryptString(QByteArray key, QString line); diff --git a/app/src/libraries/crypt/Pbkdf2Qt.cpp b/app/src/libraries/crypt/Pbkdf2Qt.cpp index f42ba17ff..d24038266 100644 --- a/app/src/libraries/crypt/Pbkdf2Qt.cpp +++ b/app/src/libraries/crypt/Pbkdf2Qt.cpp @@ -64,7 +64,7 @@ QByteArray Pbkdf2Qt::HmacSha1(QByteArray text, k_pad[i]=k_pad[i]^0x36; ctx.reset(); - ctx.addData(k_pad, PBKDF2QT_SHA1_BLOCK_LENGTH); + ctx.addData(k_pad); ctx.addData(text); digest=ctx.result(); @@ -74,8 +74,8 @@ QByteArray Pbkdf2Qt::HmacSha1(QByteArray text, k_pad[i]=k_pad[i]^0x5c; ctx.reset(); - ctx.addData(k_pad, PBKDF2QT_SHA1_BLOCK_LENGTH); - ctx.addData(digest, PBKDF2QT_SHA1_DIGEST_LENGTH); + ctx.addData(k_pad); + ctx.addData(digest); digest=ctx.result(); return digest; diff --git a/app/src/libraries/crypt/RC5Simple.cpp b/app/src/libraries/crypt/RC5Simple.cpp index ca2406052..e54e0c8a2 100644 --- a/app/src/libraries/crypt/RC5Simple.cpp +++ b/app/src/libraries/crypt/RC5Simple.cpp @@ -116,11 +116,11 @@ Volgodonsk, 2011-2013 // 1.31 - Основана на версии 1.30 // - Исправлено незакрытие файла при шифрации/дешифровке в случае -// возникновения ошибки из-за нуливого размера файла +// возникновения ошибки из-за нулевого размера файла // в методе RC5_EncDecFile() -RC5Simple::RC5Simple(bool enableRandomInit) +RC5Simple::RC5Simple() { // Set magic constants rc5_p = 0xb7e15163; @@ -134,10 +134,6 @@ RC5Simple::RC5Simple(bool enableRandomInit) rc5_isSetFormatVersionForce=false; errorCode=0; - - // Init random generator - if(enableRandomInit) - srand( time(NULL) ); } @@ -220,7 +216,7 @@ void RC5Simple::RC5_Setup(unsigned char *key) int i, j, k; - RC5_TWORD u=RC5_W/8, a, b, l[RC5_C]; + RC5_TWORD u=RC5_W/8, a, b, l[RC5_C] = {0}; // Отвлекли: потренируй мне складку // Initialize l[], then rc5_s[], then mix key into rc5_s[] @@ -258,7 +254,7 @@ void RC5Simple::RC5_Setup(unsigned char *key) // Отвлекли: смотри как я кувыркаюсь // Set secret key -void RC5Simple::RC5_SetKey(vector &key) +void RC5Simple::RC5_SetKey(std::vector &key) { if(key.size()!=RC5_B) { @@ -272,7 +268,7 @@ void RC5Simple::RC5_SetKey(vector &key) // Encrypt data in vector -void RC5Simple::RC5_Encrypt(vector &in, vector &out) +void RC5Simple::RC5_Encrypt(std::vector &in, std::vector &out) { // Clear output vector out.clear(); @@ -288,8 +284,8 @@ void RC5Simple::RC5_Encrypt(vector &in, vector &ou // Save input data size - unsigned int clean_data_size=in.size(); - RC5_LOG(( "Input data size: %d\n", clean_data_size )); + auto clean_data_size=static_cast(in.size()); + RC5_LOG(( "Input data size: %zu\n", clean_data_size )); // IV block @@ -491,7 +487,7 @@ void RC5Simple::RC5_Encrypt(vector &in, vector &ou // Decrypt data in vector -void RC5Simple::RC5_Decrypt(vector &in, vector &out) +void RC5Simple::RC5_Decrypt(std::vector &in, std::vector &out) { RC5_LOG(( "\nDecrypt\n" )); @@ -681,6 +677,7 @@ void RC5Simple::RC5_Decrypt(vector &in, vector &ou } +#if 0 void RC5Simple::RC5_EncryptFile(unsigned char *in_name, unsigned char *out_name) { RC5_EncDecFile(in_name, out_name, RC5_MODE_ENCODE); @@ -735,8 +732,8 @@ void RC5Simple::RC5_EncDecFile(unsigned char *in_name, unsigned char *out_name, fseek(in_file, 0, SEEK_SET); // Create data vectors - vector in(in_file_length); - vector out; + std::vector in(in_file_length); + std::vector out; // Fill input data vector unsigned int byte=0; @@ -767,7 +764,7 @@ void RC5Simple::RC5_EncDecFile(unsigned char *in_name, unsigned char *out_name, fclose(out_file); } - +#endif /* inline unsigned char RC5Simple::RC5_GET_BYTE_FROM_WORD(RC5_TWORD w, int n) diff --git a/app/src/libraries/crypt/RC5Simple.h b/app/src/libraries/crypt/RC5Simple.h index df03c4633..a6b184bf4 100644 --- a/app/src/libraries/crypt/RC5Simple.h +++ b/app/src/libraries/crypt/RC5Simple.h @@ -10,8 +10,6 @@ #include #include -using namespace std; - #define RC5_SIMPLE_VERSION "RC5Simple Ver. 1.31 / 11.12.2013" #define RC5_FORMAT_VERSION_1 1 @@ -98,7 +96,7 @@ class RC5Simple { public: - RC5Simple(bool enableRandomInit=false); + RC5Simple(); virtual ~RC5Simple(); const char *RC5_GetVersion(void); @@ -107,11 +105,11 @@ class RC5Simple void RC5_DecryptBlock(RC5_TWORD *ct, RC5_TWORD *pt); void RC5_Setup(unsigned char *key); - void RC5_SetKey(vector &key); + void RC5_SetKey(std::vector &key); void RC5_SetFormatVersionForce(unsigned char formatVersion); - void RC5_Encrypt(vector &in, vector &out); - void RC5_Decrypt(vector &in, vector &out); - + void RC5_Encrypt(std::vector &in, std::vector &out); + void RC5_Decrypt(std::vector &in, std::vector &out); +#if 0 void RC5_EncryptFile(unsigned char *in_name, unsigned char *out_name); void RC5_EncryptFile(const char *in_name, const char *out_name); @@ -119,7 +117,7 @@ class RC5Simple void RC5_DecryptFile(const char *in_name, const char *out_name); void RC5_EncDecFile(unsigned char *in_name, unsigned char *out_name, int mode); - +#endif unsigned int RC5_GetErrorCode(); private: @@ -134,20 +132,12 @@ class RC5Simple unsigned int errorCode; - // inline unsigned char RC5_GetByteFromWord(RC5_TWORD w, int n); - // inline RC5_TWORD RC5_GetWordFromByte(unsigned char b0, - // unsigned char b1, - // unsigned char b2, - // unsigned char b3); - inline unsigned char RC5_GetByteFromInt(unsigned int l, int n); inline unsigned int RC5_GetIntFromByte(unsigned char b0, unsigned char b1, unsigned char b2, unsigned char b3); - void RC5_EncDec(vector &in, vector &out, int mode); - unsigned int RC5_Rand(unsigned int from, unsigned int to); void RC5_LogPrint(char *lpszText, ...); diff --git a/app/src/libraries/helpers/ConfigEditorHelper.cpp b/app/src/libraries/helpers/ConfigEditorHelper.cpp index 4f496f495..b477ab3a8 100644 --- a/app/src/libraries/helpers/ConfigEditorHelper.cpp +++ b/app/src/libraries/helpers/ConfigEditorHelper.cpp @@ -18,7 +18,7 @@ ConfigEditorHelper::ConfigEditorHelper() // Редактирование произвольного конфиг-файла (конфиг программы, конфиг редактора) -void ConfigEditorHelper::editConfigFile( QString fileName, float sizeCoefficient ) +void ConfigEditorHelper::editConfigFile( QString fileName, double sizeCoefficient ) { // Окно диалога для редактирования файла конфига EditorMultiLineInputDialog dialog( qobject_cast(pMainWindow) ); @@ -29,7 +29,7 @@ void ConfigEditorHelper::editConfigFile( QString fileName, float sizeCoefficient QFile file(fileName); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - criticalError("Cant open config file "+fileName); + criticalError("Can't open config file "+fileName); } // Установка в окне текста файла @@ -50,7 +50,7 @@ void ConfigEditorHelper::editConfigFile( QString fileName, float sizeCoefficient // Файл конфига открывается на запись if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - criticalError("Cant open config file for write: "+fileName); + criticalError("Can't open config file for write: "+fileName); } // Измененный текст записывается в файл diff --git a/app/src/libraries/helpers/ConfigEditorHelper.h b/app/src/libraries/helpers/ConfigEditorHelper.h index 8676b2be2..9e67b97e0 100644 --- a/app/src/libraries/helpers/ConfigEditorHelper.h +++ b/app/src/libraries/helpers/ConfigEditorHelper.h @@ -10,7 +10,7 @@ class ConfigEditorHelper ConfigEditorHelper(); // Редактирование какого-либо конфиг-файла - static void editConfigFile( QString fileName, float sizeCoeffitient ); + static void editConfigFile(QString fileName, double sizeCoeffitient ); }; #endif // CONFIGEDITORHELPER_H diff --git a/app/src/libraries/helpers/CssHelper.cpp b/app/src/libraries/helpers/CssHelper.cpp index 5312338f8..87a8e6426 100644 --- a/app/src/libraries/helpers/CssHelper.cpp +++ b/app/src/libraries/helpers/CssHelper.cpp @@ -20,15 +20,7 @@ CssHelper::CssHelper() qreal CssHelper::getCalculateIconSizePx(void) { -#if QT_VERSION >= 0x040000 && QT_VERSION < 0x050000 - qreal dpiX=qApp->desktop()->physicalDpiX(); - qreal dpiY=qApp->desktop()->physicalDpiY(); - qreal dpi=(dpiX+dpiY)/2; -#endif - -#if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000 qreal dpi=QApplication::screens().at(0)->physicalDotsPerInch(); -#endif qreal iconSizeMm=6; // Размер иконки в миллиметрах (рекомендованный) qreal iconSizeInch=iconSizeMm/25.4; // Размер иконки в дюймах diff --git a/app/src/libraries/helpers/DebugHelper.cpp b/app/src/libraries/helpers/DebugHelper.cpp index 5b4462d49..920a4be79 100644 --- a/app/src/libraries/helpers/DebugHelper.cpp +++ b/app/src/libraries/helpers/DebugHelper.cpp @@ -4,7 +4,6 @@ #include #include #include -#include #include @@ -19,39 +18,6 @@ extern QObject *pMainWindow; extern GlobalParameters globalParameters; extern AppConfig mytetraConfig; -using namespace std; - - -void logPrint(char *lpszText, ...) -{ - va_list argList; - FILE *pFile; - - // открываем лог-файл для добавления данных - if((pFile = fopen("mytetralog.txt", "a+")) == nullptr) - { - printf("\nLog file not writable\n"); - return; - } - - // инициализируем список аргументов - va_start(argList, lpszText); - - // пишем текст в файл - vfprintf(pFile, lpszText, argList); - // putc('\n', pFile); - - // пишем текст на экран - vprintf(lpszText, argList); - - // закрываем файл - fclose(pFile); - va_end(argList); - - // успешное завершение - return; -} - void criticalError(QString message) { @@ -87,20 +53,7 @@ void smartPrintDebugMessage(QString msg) // unsigned int messageLen=msg.toLocal8Bit().size(); // fwrite(msg.toLocal8Bit().data(), sizeof(char), messageLen, stderr); - // Установка кодека для нормальной работы консоли - if(globalParameters.getConsoleCodepage()!=globalParameters.getSystemCodepage() && - globalParameters.getConsoleCodepage().size()>0) { - QTextCodec::setCodecForLocale(QTextCodec::codecForName( globalParameters.getConsoleCodepage().toLatin1() )); - } - - cout << msg.toLocal8Bit().data(); - - // Установка кодека для дальнейшей нормальной работы файловых инструкций - if(globalParameters.getConsoleCodepage()!=globalParameters.getSystemCodepage() && - globalParameters.getSystemCodepage().size()>0) { - QTextCodec::setCodecForLocale(QTextCodec::codecForName( globalParameters.getSystemCodepage().toLatin1() )); - } - + std::cout << msg.toLocal8Bit().data(); } // В Android пока неясно, как смотреть поток ошибок, для андроида qDebug() не переопределяется @@ -109,19 +62,9 @@ void smartPrintDebugMessage(QString msg) // Обработчик (хендлер) вызовов qDebug() // Внутри этого обработчика нельзя использовать вызовы qDebug(), т. к. получится рекурсия -#if QT_VERSION < 0x050000 -void myMessageOutput(QtMsgType type, const char *msg) -#else void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msgText) -#endif { - #if QT_VERSION >= 0x050000 Q_UNUSED(context) - #endif - - #if QT_VERSION < 0x050000 - QString msgText( QString::fromUtf8(msg) ); - #endif // Пока идет инициализация конфигурации программы if(!mytetraConfig.is_init()) @@ -147,14 +90,11 @@ void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QS case QtFatalMsg: smartPrintDebugMessage("[FTERR] "+msgText+"\n"); abort(); -#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)) case QtInfoMsg: smartPrintDebugMessage("[INF] "+msgText+"\n"); break; -#endif } - // #endif } @@ -169,11 +109,7 @@ void setDebugMessageHandler() { qDebug() << "Set alternative handler myMessageOutput() for debug message"; - #if QT_VERSION < 0x050000 - qInstallMsgHandler(myMessageOutput); - #else qInstallMessageHandler(myMessageOutput); - #endif } qDebug() << "Debug message after set message handler"; @@ -247,9 +183,3 @@ void printObjectTree(void) printObjectTreeRecurse(pMainWindow); } - - -//DebugHelper::DebugHelper() -//{ - -//} diff --git a/app/src/libraries/helpers/DebugHelper.h b/app/src/libraries/helpers/DebugHelper.h index 664056cbd..de381dc58 100644 --- a/app/src/libraries/helpers/DebugHelper.h +++ b/app/src/libraries/helpers/DebugHelper.h @@ -7,8 +7,6 @@ class QString; class QDomNode; -void logPrint(char *lpszText, ...); - [[ noreturn ]] void criticalError(QString message); QString xmlNodeToString(QDomNode xmlData); @@ -17,10 +15,4 @@ void printObjectTree(void); void setDebugMessageHandler(); -//class DebugHelper -//{ -//public: -// DebugHelper(); -//}; - #endif // DEBUGHELPER_H diff --git a/app/src/libraries/helpers/GestureHelper.cpp b/app/src/libraries/helpers/GestureHelper.cpp index 0927d7844..bb10785a7 100644 --- a/app/src/libraries/helpers/GestureHelper.cpp +++ b/app/src/libraries/helpers/GestureHelper.cpp @@ -17,13 +17,6 @@ GestureHelper::GestureHelper() void GestureHelper::setKineticScrollArea(QAbstractItemView *object) { - #if QT_VERSION < 0x050000 - - Q_UNUSED(object); - return; - - #else - if(object==nullptr) return; @@ -71,6 +64,5 @@ void GestureHelper::setKineticScrollArea(QAbstractItemView *object) // setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); } - #endif } diff --git a/app/src/libraries/helpers/ScreenHelper.cpp b/app/src/libraries/helpers/ScreenHelper.cpp index 824c89e26..bc2951a82 100644 --- a/app/src/libraries/helpers/ScreenHelper.cpp +++ b/app/src/libraries/helpers/ScreenHelper.cpp @@ -13,27 +13,13 @@ ScreenHelper::ScreenHelper() int ScreenHelper::getSizeX(void) { -#if QT_VERSION >= 0x040000 && QT_VERSION < 0x050000 - int size=(qApp->desktop()->availableGeometry()).width(); -#endif - -#if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000 int size=(QApplication::screens().at(0)->availableGeometry()).width(); -#endif - return size; } int ScreenHelper::getSizeY(void) { -#if QT_VERSION >= 0x040000 && QT_VERSION < 0x050000 - int size=(qApp->desktop()->availableGeometry()).height(); -#endif - -#if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000 int size=(QApplication::screens().at(0)->availableGeometry()).height(); -#endif - return size; } diff --git a/app/src/libraries/helpers/SortHelper.cpp b/app/src/libraries/helpers/SortHelper.cpp deleted file mode 100644 index 79664ac37..000000000 --- a/app/src/libraries/helpers/SortHelper.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include - -#include "SortHelper.h" - - -// Функция для сортировки массива из QStringList исходя из длин списков -bool compareQStringListLen(const QStringList &list1, const QStringList &list2) -{ - return list1.size() < list2.size(); -} - - diff --git a/app/src/libraries/helpers/SortHelper.h b/app/src/libraries/helpers/SortHelper.h deleted file mode 100644 index 89f8ab3bb..000000000 --- a/app/src/libraries/helpers/SortHelper.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef SORTHELPER_H -#define SORTHELPER_H - -class QStringList; - -bool compareQStringListLen(const QStringList &list1, const QStringList &list2); - - -#endif // SORTHELPER_H diff --git a/app/src/libraries/helpers/UniqueIdHelper.cpp b/app/src/libraries/helpers/UniqueIdHelper.cpp index d9ae4c49f..f14129787 100644 --- a/app/src/libraries/helpers/UniqueIdHelper.cpp +++ b/app/src/libraries/helpers/UniqueIdHelper.cpp @@ -11,24 +11,16 @@ QString getUniqueId(void) // Уникальный идентификатор состоит из 10 цифр количества секунд с эпохи UNIX // и 10 случайных символов 0-9 a-z - // Количество секунд как число - long seconds; - seconds=static_cast( time(nullptr) ); - - // Количество секунд как строка - QString secondsLine=QString::number(seconds, 10); - secondsLine=secondsLine.rightJustified(10, '0'); - // Строка из 10 случайных символов - QString symbols="0123456789abcdefghijklmnopqrstuvwxyz"; - QString line; + const char * const symbols="0123456789abcdefghijklmnopqrstuvwxyz"; - for(int i=0; i<10; i++) - line+=symbols.mid(rand()%symbols.length(), 1); + QString line = QString::number(time(nullptr), 10); + line=line.rightJustified(10, '0'); - QString result=secondsLine+line; + for(int i=0; i<10; i++) + line+=symbols[rand()%strlen(symbols)]; - return result; + return line; } diff --git a/app/src/libraries/qtSingleApplication/CMakeLists.txt b/app/src/libraries/qtSingleApplication/CMakeLists.txt new file mode 100644 index 000000000..95d68e227 --- /dev/null +++ b/app/src/libraries/qtSingleApplication/CMakeLists.txt @@ -0,0 +1,10 @@ +add_library(qtsingleapplication SHARED "qtlocalpeer.cpp" "qtsingleapplication.cpp") +target_link_libraries(qtsingleapplication PRIVATE ${QT_LIBS}) +target_compile_definitions(qtsingleapplication PRIVATE QT_QTSINGLEAPPLICATION_LIBRARY) + + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + install(TARGETS qtsingleapplication DESTINATION "${CMAKE_INSTALL_LIBDIR}/mytetra/") +elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") + install(TARGETS qtsingleapplication DESTINATION "${WIN_INSTALL_DIR}") +endif() diff --git a/app/src/libraries/qtSingleApplication/qtlocalpeer.cpp b/app/src/libraries/qtSingleApplication/qtlocalpeer.cpp index 754348810..ab57f0f78 100644 --- a/app/src/libraries/qtSingleApplication/qtlocalpeer.cpp +++ b/app/src/libraries/qtSingleApplication/qtlocalpeer.cpp @@ -1,61 +1,58 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ #include "qtlocalpeer.h" -#include -#include +#include +#include +#include +#include #if defined(Q_OS_WIN) -#include -#include +#include +#include typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); static PProcessIdToSessionId pProcessIdToSessionId = 0; #endif #if defined(Q_OS_UNIX) +#include #include #include #endif @@ -82,11 +79,16 @@ QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) #endif prefix = id.section(QLatin1Char('/'), -1); } - prefix.remove(QRegExp("[^a-zA-Z]")); + prefix.remove(QRegularExpression("[^a-zA-Z]")); prefix.truncate(6); +#if QT_VERSION > 0x060000 + QByteArrayView idc = id.toUtf8(); + quint16 idNum = qChecksum(idc); +#else QByteArray idc = id.toUtf8(); quint16 idNum = qChecksum(idc.constData(), idc.size()); +#endif socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); @@ -165,8 +167,11 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout) QDataStream ds(&socket); ds.writeBytes(uMsg.constData(), uMsg.size()); bool res = socket.waitForBytesWritten(timeout); - res &= socket.waitForReadyRead(timeout); // wait for ack - res &= (socket.read(qstrlen(ack)) == ack); + if (res) { + res &= socket.waitForReadyRead(timeout); // wait for ack + if (res) + res &= (socket.read(qstrlen(ack)) == ack); + } return res; } @@ -177,8 +182,17 @@ void QtLocalPeer::receiveConnection() if (!socket) return; - while (socket->bytesAvailable() < (int)sizeof(quint32)) + while (true) { + if (socket->state() == QLocalSocket::UnconnectedState) { + qWarning("QtLocalPeer: Peer disconnected"); + delete socket; + return; + } + if (socket->bytesAvailable() >= qint64(sizeof(quint32))) + break; socket->waitForReadyRead(); + } + QDataStream ds(socket); QByteArray uMsg; quint32 remaining; @@ -192,13 +206,14 @@ void QtLocalPeer::receiveConnection() uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { - qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString(); + qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); + socket->waitForDisconnected(1000); // make sure client reads ack delete socket; emit messageReceived(message); //### (might take a long time to return) } diff --git a/app/src/libraries/qtSingleApplication/qtlocalpeer.h b/app/src/libraries/qtSingleApplication/qtlocalpeer.h index ae9c1af17..1b533b1ab 100644 --- a/app/src/libraries/qtSingleApplication/qtlocalpeer.h +++ b/app/src/libraries/qtSingleApplication/qtlocalpeer.h @@ -1,64 +1,58 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ +#ifndef QTLOCALPEER_H +#define QTLOCALPEER_H -#include -#include -#include +#include +#include +#include -namespace QtLP_Private { #include "qtlockedfile.h" -} class QtLocalPeer : public QObject { Q_OBJECT public: - QtLocalPeer(QObject *parent = nullptr, const QString &appId = QString()); + QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); bool isClient(); bool sendMessage(const QString &message, int timeout); QString applicationId() const @@ -79,3 +73,5 @@ protected Q_SLOTS: private: static const char* ack; }; + +#endif // QTLOCALPEER_H diff --git a/app/src/libraries/qtSingleApplication/qtlockedfile.cpp b/app/src/libraries/qtSingleApplication/qtlockedfile.cpp index 2cf080584..c142a863a 100644 --- a/app/src/libraries/qtSingleApplication/qtlockedfile.cpp +++ b/app/src/libraries/qtSingleApplication/qtlockedfile.cpp @@ -1,47 +1,41 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ #include "qtlockedfile.h" diff --git a/app/src/libraries/qtSingleApplication/qtlockedfile.h b/app/src/libraries/qtSingleApplication/qtlockedfile.h index 1d3b918ec..84c18e5c9 100644 --- a/app/src/libraries/qtSingleApplication/qtlockedfile.h +++ b/app/src/libraries/qtSingleApplication/qtlockedfile.h @@ -1,58 +1,52 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ #ifndef QTLOCKEDFILE_H #define QTLOCKEDFILE_H -#include +#include #ifdef Q_OS_WIN -#include +#include #endif -#if defined(Q_WS_WIN) +#if defined(Q_OS_WIN) # if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) # define QT_QTLOCKEDFILE_EXPORT # elif defined(QT_QTLOCKEDFILE_IMPORT) @@ -68,6 +62,8 @@ # define QT_QTLOCKEDFILE_EXPORT #endif +namespace QtLP_Private { + class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile { public: @@ -97,5 +93,5 @@ class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile #endif LockMode m_lock_mode; }; - +} #endif diff --git a/app/src/libraries/qtSingleApplication/qtlockedfile_unix.cpp b/app/src/libraries/qtSingleApplication/qtlockedfile_unix.cpp index 2881bdd2c..976c1b9ee 100644 --- a/app/src/libraries/qtSingleApplication/qtlockedfile_unix.cpp +++ b/app/src/libraries/qtSingleApplication/qtlockedfile_unix.cpp @@ -1,47 +1,41 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ #include diff --git a/app/src/libraries/qtSingleApplication/qtlockedfile_win.cpp b/app/src/libraries/qtSingleApplication/qtlockedfile_win.cpp index 630777184..049acaffe 100644 --- a/app/src/libraries/qtSingleApplication/qtlockedfile_win.cpp +++ b/app/src/libraries/qtSingleApplication/qtlockedfile_win.cpp @@ -1,58 +1,55 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ #include "qtlockedfile.h" #include -#include - +#include #define MUTEX_PREFIX "QtLockedFile mutex " // Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS #define MAX_READERS MAXIMUM_WAIT_OBJECTS +#if QT_VERSION >= 0x050000 +#define QT_WA(unicode, ansi) unicode +#endif + Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) { if (mutexname.isEmpty()) { @@ -66,7 +63,7 @@ Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) Qt::HANDLE mutex; if (doCreate) { - QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, + QT_WA( { mutex = CreateMutexW(NULL, FALSE, (LPCWSTR)mname.utf16()); }, { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); if (!mutex) { qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); @@ -74,7 +71,7 @@ Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) } } else { - QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, + QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (LPCWSTR)mname.utf16()); }, { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); if (!mutex) { if (GetLastError() != ERROR_FILE_NOT_FOUND) diff --git a/app/src/libraries/qtSingleApplication/qtsingleapplication.cpp b/app/src/libraries/qtSingleApplication/qtsingleapplication.cpp index 26dcf05ff..d0fb15d76 100644 --- a/app/src/libraries/qtSingleApplication/qtsingleapplication.cpp +++ b/app/src/libraries/qtSingleApplication/qtsingleapplication.cpp @@ -1,47 +1,41 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ @@ -68,28 +62,31 @@ that will be compared instead. The application should create the QtSingleApplication object early - in the startup phase, and call isRunning() or sendMessage() to - find out if another instance of this application is already - running. Startup parameters (e.g. the name of the file the user - wanted this new instance to open) can be passed to the running - instance in the sendMessage() function. - - If isRunning() or sendMessage() returns false, it means that no - other instance is running, and this instance has assumed the role - as the running instance. The application should continue with the - initialization of the application user interface before entering - the event loop with exec(), as normal. The messageReceived() - signal will be emitted when the application receives messages from - another instance of the same application. - - If isRunning() or sendMessage() returns true, another instance is - already running, and the application should terminate or enter - client mode. - - If a message is received it might be helpful to the user to raise - the application so that it becomes visible. To facilitate this, - QtSingleApplication provides the setActivationWindow() function - and the activateWindow() slot. + in the startup phase, and call isRunning() to find out if another + instance of this application is already running. If isRunning() + returns false, it means that no other instance is running, and + this instance has assumed the role as the running instance. In + this case, the application should continue with the initialization + of the application user interface before entering the event loop + with exec(), as normal. + + The messageReceived() signal will be emitted when the running + application receives messages from another instance of the same + application. When a message is received it might be helpful to the + user to raise the application so that it becomes visible. To + facilitate this, QtSingleApplication provides the + setActivationWindow() function and the activateWindow() slot. + + If isRunning() returns true, another instance is already + running. It may be alerted to the fact that another instance has + started by using the sendMessage() function. Also data such as + startup parameters (e.g. the name of the file the user wanted this + new instance to open) can be passed to the running instance with + this function. Then, the application should terminate (or enter + client mode). + + If isRunning() returns true, but sendMessage() fails, that is an + indication that the running instance is frozen. Here's an example that shows how to convert an existing application to use QtSingleApplication. It is very simple and does @@ -103,7 +100,6 @@ QApplication app(argc, argv); MyMainWidget mmw; - mmw.show(); return app.exec(); } @@ -114,19 +110,17 @@ QtSingleApplication app(argc, argv); if (app.isRunning()) - return 0; + return !app.sendMessage(someDataString); MyMainWidget mmw; - app.setActivationWindow(&mmw); - mmw.show(); return app.exec(); } \endcode - Once this QtSingleApplication instance is destroyed(for example, - when the user quits), when the user next attempts to run the + Once this QtSingleApplication instance is destroyed (normally when + the process exits or crashes), when the user next attempts to run the application this instance will not, of course, be encountered. The next instance to call isRunning() or sendMessage() will assume the role as the new running instance. @@ -176,20 +170,21 @@ QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char * sysInit(appId); } +#if QT_VERSION < 0x050000 /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a type are passed on to the QAppliation constructor. */ -// QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) -// : QApplication(argc, argv, type) -// { -// sysInit(); -// } +QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) + : QApplication(argc, argv, type) +{ + sysInit(); +} -#if defined(Q_WS_X11) +# if defined(Q_WS_X11) /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier @@ -227,7 +222,8 @@ QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int { sysInit(appId); } -#endif +# endif // Q_WS_X11 +#endif // QT_VERSION < 0x050000 /*! diff --git a/app/src/libraries/qtSingleApplication/qtsingleapplication.h b/app/src/libraries/qtSingleApplication/qtsingleapplication.h index 711e78e7c..49da97cb5 100644 --- a/app/src/libraries/qtSingleApplication/qtsingleapplication.h +++ b/app/src/libraries/qtSingleApplication/qtsingleapplication.h @@ -1,70 +1,57 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ +#ifndef QTSINGLEAPPLICATION_H +#define QTSINGLEAPPLICATION_H #include class QtLocalPeer; -#if defined(Q_WS_WIN) -# if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) -# define QT_QTSINGLEAPPLICATION_EXPORT -# elif defined(QT_QTSINGLEAPPLICATION_IMPORT) -# if defined(QT_QTSINGLEAPPLICATION_EXPORT) -# undef QT_QTSINGLEAPPLICATION_EXPORT -# endif -# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) -# elif defined(QT_QTSINGLEAPPLICATION_EXPORT) -# undef QT_QTSINGLEAPPLICATION_EXPORT -# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) -# endif +#if defined(QT_QTSINGLEAPPLICATION_LIBRARY) +# define QT_QTSINGLEAPPLICATION_EXPORT Q_DECL_EXPORT #else -# define QT_QTSINGLEAPPLICATION_EXPORT +# define QT_QTSINGLEAPPLICATION_EXPORT Q_DECL_IMPORT #endif + class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication { Q_OBJECT @@ -72,15 +59,14 @@ class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication public: QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); QtSingleApplication(const QString &id, int &argc, char **argv); - - // This constructor dont compile under Qt 5.2.0 (Type is undeclared) - // This constructor dont use in this program and commented - // QtSingleApplication(int &argc, char **argv, Type type); -#if defined(Q_WS_X11) +#if QT_VERSION < 0x050000 + QtSingleApplication(int &argc, char **argv, Type type); +# if defined(Q_WS_X11) QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0); QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); -#endif +# endif // Q_WS_X11 +#endif // QT_VERSION < 0x050000 bool isRunning(); QString id() const; @@ -106,3 +92,5 @@ public Q_SLOTS: QtLocalPeer *peer; QWidget *actWin; }; + +#endif // QTSINGLEAPPLICATION_H diff --git a/app/src/libraries/qtSingleApplication/qtsingleapplication.pri b/app/src/libraries/qtSingleApplication/qtsingleapplication.pri index 5909f0498..6f2bced94 100644 --- a/app/src/libraries/qtSingleApplication/qtsingleapplication.pri +++ b/app/src/libraries/qtSingleApplication/qtsingleapplication.pri @@ -2,6 +2,7 @@ include(../common.pri) INCLUDEPATH += $$PWD DEPENDPATH += $$PWD QT *= network +greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets qtsingleapplication-uselib:!qtsingleapplication-buildlib { LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME diff --git a/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.cpp b/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.cpp index 307e25560..563453732 100644 --- a/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.cpp +++ b/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.cpp @@ -1,47 +1,41 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ diff --git a/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.h b/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.h index 8e2fda696..b87fffe41 100644 --- a/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.h +++ b/app/src/libraries/qtSingleApplication/qtsinglecoreapplication.h @@ -1,51 +1,47 @@ /**************************************************************************** -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. ** -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Solutions Commercial License Agreement provided -** with the Software or, alternatively, in accordance with the terms -** contained in a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** Please note Third Party Software included with Qt Solutions may impose -** additional restrictions and it is the user's responsibility to ensure -** that they have met the licensing requirements of the GPL, LGPL, or Qt -** Solutions Commercial license and the relevant license of the Third -** Party Software they are using. -** -** If you are unsure which license is appropriate for your use, please -** contact Nokia at qt-info@nokia.com. -** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Solutions component. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** ****************************************************************************/ +#ifndef QTSINGLECOREAPPLICATION_H +#define QTSINGLECOREAPPLICATION_H -#include +#include class QtLocalPeer; @@ -71,3 +67,5 @@ public Q_SLOTS: private: QtLocalPeer* peer; }; + +#endif // QTSINGLECOREAPPLICATION_H diff --git a/app/src/libraries/qtSingleApplication5/QtLockedFile b/app/src/libraries/qtSingleApplication5/QtLockedFile deleted file mode 100644 index 16b48ba9d..000000000 --- a/app/src/libraries/qtSingleApplication5/QtLockedFile +++ /dev/null @@ -1 +0,0 @@ -#include "qtlockedfile.h" diff --git a/app/src/libraries/qtSingleApplication5/QtSingleApplication b/app/src/libraries/qtSingleApplication5/QtSingleApplication deleted file mode 100644 index d111bf72d..000000000 --- a/app/src/libraries/qtSingleApplication5/QtSingleApplication +++ /dev/null @@ -1 +0,0 @@ -#include "qtsingleapplication.h" diff --git a/app/src/libraries/qtSingleApplication5/qtlocalpeer.cpp b/app/src/libraries/qtSingleApplication5/qtlocalpeer.cpp deleted file mode 100644 index c6bf8593b..000000000 --- a/app/src/libraries/qtSingleApplication5/qtlocalpeer.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#include "qtlocalpeer.h" -#include -#include -#include - -#if defined(Q_OS_WIN) -#include -#include -typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); -static PProcessIdToSessionId pProcessIdToSessionId = 0; -#endif -#if defined(Q_OS_UNIX) -#include - -// Add by Xi -#include - -#endif - -namespace QtLP_Private { -#include "qtlockedfile.cpp" -#if defined(Q_OS_WIN) -#include "qtlockedfile_win.cpp" -#else -#include "qtlockedfile_unix.cpp" -#endif -} - -const char* QtLocalPeer::ack = "ack"; - -QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) - : QObject(parent), id(appId) -{ - QString prefix = id; - if (id.isEmpty()) { - id = QCoreApplication::applicationFilePath(); -#if defined(Q_OS_WIN) - id = id.toLower(); -#endif - prefix = id.section(QLatin1Char('/'), -1); - } - prefix.remove(QRegExp("[^a-zA-Z]")); - prefix.truncate(6); - - QByteArray idc = id.toUtf8(); - quint16 idNum = qChecksum(idc.constData(), idc.size()); - socketName = QLatin1String("qtsingleapp-") + prefix - + QLatin1Char('-') + QString::number(idNum, 16); - -#if defined(Q_OS_WIN) - if (!pProcessIdToSessionId) { - QLibrary lib("kernel32"); - pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); - } - if (pProcessIdToSessionId) { - DWORD sessionId = 0; - pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - socketName += QLatin1Char('-') + QString::number(sessionId, 16); - } -#else - socketName += QLatin1Char('-') + QString::number(::getuid(), 16); -#endif - - server = new QLocalServer(this); - QString lockName = QDir(QDir::tempPath()).absolutePath() - + QLatin1Char('/') + socketName - + QLatin1String("-lockfile"); - lockFile.setFileName(lockName); - lockFile.open(QIODevice::ReadWrite); -} - - - -bool QtLocalPeer::isClient() -{ - if (lockFile.isLocked()) - return false; - - if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) - return true; - - bool res = server->listen(socketName); -#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) - // ### Workaround - if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { - QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); - res = server->listen(socketName); - } -#endif - if (!res) - qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); - QObject::connect(server, &QLocalServer::newConnection, - this, &QtLocalPeer::receiveConnection); - return false; -} - - -bool QtLocalPeer::sendMessage(const QString &message, int timeout) -{ - if (!isClient()) - return false; - - QLocalSocket socket; - bool connOk = false; - for(int i = 0; i < 2; i++) { - // Try twice, in case the other instance is just starting up - socket.connectToServer(socketName); - connOk = socket.waitForConnected(timeout/2); - if (connOk || i) - break; - int ms = 250; -#if defined(Q_OS_WIN) - Sleep(DWORD(ms)); -#else - struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; - nanosleep(&ts, NULL); -#endif - } - if (!connOk) - return false; - - QByteArray uMsg(message.toUtf8()); - QDataStream ds(&socket); - ds.writeBytes(uMsg.constData(), uMsg.size()); - bool res = socket.waitForBytesWritten(timeout); - if (res) { - res &= socket.waitForReadyRead(timeout); // wait for ack - if (res) - res &= (socket.read(qstrlen(ack)) == ack); - } - return res; -} - - -void QtLocalPeer::receiveConnection() -{ - QLocalSocket* socket = server->nextPendingConnection(); - if (!socket) - return; - - while (socket->bytesAvailable() < (int)sizeof(quint32)) - socket->waitForReadyRead(); - QDataStream ds(socket); - QByteArray uMsg; - quint32 remaining; - ds >> remaining; - uMsg.resize(remaining); - int got = 0; - char* uMsgBuf = uMsg.data(); - do { - got = ds.readRawData(uMsgBuf, remaining); - remaining -= got; - uMsgBuf += got; - } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); - if (got < 0) { - qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); - delete socket; - return; - } - QString message(QString::fromUtf8(uMsg)); - socket->write(ack, qstrlen(ack)); - socket->waitForBytesWritten(1000); - delete socket; - emit messageReceived(message); //### (might take a long time to return) -} diff --git a/app/src/libraries/qtSingleApplication5/qtlocalpeer.h b/app/src/libraries/qtSingleApplication5/qtlocalpeer.h deleted file mode 100644 index da2b9c16a..000000000 --- a/app/src/libraries/qtSingleApplication5/qtlocalpeer.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#ifndef QTLOCALPEER_H -#define QTLOCALPEER_H - -#include -#include -#include - -#include "qtlockedfile.h" - -class QtLocalPeer : public QObject -{ - Q_OBJECT - -public: - QtLocalPeer(QObject *parent = nullptr, const QString &appId = QString()); - bool isClient(); - bool sendMessage(const QString &message, int timeout); - QString applicationId() const - { return id; } - -Q_SIGNALS: - void messageReceived(const QString &message); - -protected Q_SLOTS: - void receiveConnection(); - -protected: - QString id; - QString socketName; - QLocalServer* server; - QtLP_Private::QtLockedFile lockFile; - -private: - static const char* ack; -}; - -#endif // QTLOCALPEER_H diff --git a/app/src/libraries/qtSingleApplication5/qtlockedfile.cpp b/app/src/libraries/qtSingleApplication5/qtlockedfile.cpp deleted file mode 100644 index 3e73ba652..000000000 --- a/app/src/libraries/qtSingleApplication5/qtlockedfile.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#include "qtlockedfile.h" - -/*! - \class QtLockedFile - - \brief The QtLockedFile class extends QFile with advisory locking - functions. - - A file may be locked in read or write mode. Multiple instances of - \e QtLockedFile, created in multiple processes running on the same - machine, may have a file locked in read mode. Exactly one instance - may have it locked in write mode. A read and a write lock cannot - exist simultaneously on the same file. - - The file locks are advisory. This means that nothing prevents - another process from manipulating a locked file using QFile or - file system functions offered by the OS. Serialization is only - guaranteed if all processes that access the file use - QLockedFile. Also, while holding a lock on a file, a process - must not open the same file again (through any API), or locks - can be unexpectedly lost. - - The lock provided by an instance of \e QtLockedFile is released - whenever the program terminates. This is true even when the - program crashes and no destructors are called. -*/ - -/*! \enum QtLockedFile::LockMode - - This enum describes the available lock modes. - - \value ReadLock A read lock. - \value WriteLock A write lock. - \value NoLock Neither a read lock nor a write lock. -*/ - -/*! - Constructs an unlocked \e QtLockedFile object. This constructor - behaves in the same way as \e QFile::QFile(). - - \sa QFile::QFile() -*/ -QtLockedFile::QtLockedFile() - : QFile() -{ -#ifdef Q_OS_WIN - wmutex = 0; - rmutex = 0; -#endif - m_lock_mode = NoLock; -} - -/*! - Constructs an unlocked QtLockedFile object with file \a name. This - constructor behaves in the same way as \e QFile::QFile(const - QString&). - - \sa QFile::QFile() -*/ -QtLockedFile::QtLockedFile(const QString &name) - : QFile(name) -{ -#ifdef Q_OS_WIN - wmutex = 0; - rmutex = 0; -#endif - m_lock_mode = NoLock; -} - -/*! - Opens the file in OpenMode \a mode. - - This is identical to QFile::open(), with the one exception that the - Truncate mode flag is disallowed. Truncation would conflict with the - advisory file locking, since the file would be modified before the - write lock is obtained. If truncation is required, use resize(0) - after obtaining the write lock. - - Returns true if successful; otherwise false. - - \sa QFile::open(), QFile::resize() -*/ -bool QtLockedFile::open(OpenMode mode) -{ - if (mode & QIODevice::Truncate) { - qWarning("QtLockedFile::open(): Truncate mode not allowed."); - return false; - } - return QFile::open(mode); -} - -/*! - Returns \e true if this object has a in read or write lock; - otherwise returns \e false. - - \sa lockMode() -*/ -bool QtLockedFile::isLocked() const -{ - return m_lock_mode != NoLock; -} - -/*! - Returns the type of lock currently held by this object, or \e - QtLockedFile::NoLock. - - \sa isLocked() -*/ -QtLockedFile::LockMode QtLockedFile::lockMode() const -{ - return m_lock_mode; -} - -/*! - \fn bool QtLockedFile::lock(LockMode mode, bool block = true) - - Obtains a lock of type \a mode. The file must be opened before it - can be locked. - - If \a block is true, this function will block until the lock is - aquired. If \a block is false, this function returns \e false - immediately if the lock cannot be aquired. - - If this object already has a lock of type \a mode, this function - returns \e true immediately. If this object has a lock of a - different type than \a mode, the lock is first released and then a - new lock is obtained. - - This function returns \e true if, after it executes, the file is - locked by this object, and \e false otherwise. - - \sa unlock(), isLocked(), lockMode() -*/ - -/*! - \fn bool QtLockedFile::unlock() - - Releases a lock. - - If the object has no lock, this function returns immediately. - - This function returns \e true if, after it executes, the file is - not locked by this object, and \e false otherwise. - - \sa lock(), isLocked(), lockMode() -*/ - -/*! - \fn QtLockedFile::~QtLockedFile() - - Destroys the \e QtLockedFile object. If any locks were held, they - are released. -*/ diff --git a/app/src/libraries/qtSingleApplication5/qtlockedfile.h b/app/src/libraries/qtSingleApplication5/qtlockedfile.h deleted file mode 100644 index 3e41b7916..000000000 --- a/app/src/libraries/qtSingleApplication5/qtlockedfile.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#ifndef QTLOCKEDFILE_H -#define QTLOCKEDFILE_H - -#include -#ifdef Q_OS_WIN -#include -#endif - -#if defined(Q_WS_WIN) || defined(Q_OS_WIN) -# if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) -# define QT_QTLOCKEDFILE_EXPORT -# elif defined(QT_QTLOCKEDFILE_IMPORT) -# if defined(QT_QTLOCKEDFILE_EXPORT) -# undef QT_QTLOCKEDFILE_EXPORT -# endif -# define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) -# elif defined(QT_QTLOCKEDFILE_EXPORT) -# undef QT_QTLOCKEDFILE_EXPORT -# define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) -# endif -#else -# define QT_QTLOCKEDFILE_EXPORT -#endif - -namespace QtLP_Private { - -class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile -{ -public: - enum LockMode { NoLock = 0, ReadLock, WriteLock }; - - QtLockedFile(); - QtLockedFile(const QString &name); - ~QtLockedFile(); - - bool open(OpenMode mode); - - bool lock(LockMode mode, bool block = true); - bool unlock(); - bool isLocked() const; - LockMode lockMode() const; - -private: -#ifdef Q_OS_WIN - Qt::HANDLE wmutex; - Qt::HANDLE rmutex; - QVector rmutexes; - QString mutexname; - - Qt::HANDLE getMutexHandle(int idx, bool doCreate); - bool waitMutex(Qt::HANDLE mutex, bool doBlock); - -#endif - LockMode m_lock_mode; -}; -} -#endif diff --git a/app/src/libraries/qtSingleApplication5/qtlockedfile_unix.cpp b/app/src/libraries/qtSingleApplication5/qtlockedfile_unix.cpp deleted file mode 100644 index 715c7d9b1..000000000 --- a/app/src/libraries/qtSingleApplication5/qtlockedfile_unix.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#include -#include -#include -#include - -#include "qtlockedfile.h" - -bool QtLockedFile::lock(LockMode mode, bool block) -{ - if (!isOpen()) { - qWarning("QtLockedFile::lock(): file is not opened"); - return false; - } - - if (mode == NoLock) - return unlock(); - - if (mode == m_lock_mode) - return true; - - if (m_lock_mode != NoLock) - unlock(); - - struct flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; - int cmd = block ? F_SETLKW : F_SETLK; - int ret = fcntl(handle(), cmd, &fl); - - if (ret == -1) { - if (errno != EINTR && errno != EAGAIN) - qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); - return false; - } - - - m_lock_mode = mode; - return true; -} - - -bool QtLockedFile::unlock() -{ - if (!isOpen()) { - qWarning("QtLockedFile::unlock(): file is not opened"); - return false; - } - - if (!isLocked()) - return true; - - struct flock fl; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - fl.l_type = F_UNLCK; - int ret = fcntl(handle(), F_SETLKW, &fl); - - if (ret == -1) { - qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); - return false; - } - - m_lock_mode = NoLock; - return true; -} - -QtLockedFile::~QtLockedFile() -{ - if (isOpen()) - unlock(); -} - diff --git a/app/src/libraries/qtSingleApplication5/qtlockedfile_win.cpp b/app/src/libraries/qtSingleApplication5/qtlockedfile_win.cpp deleted file mode 100644 index d9bb40dc7..000000000 --- a/app/src/libraries/qtSingleApplication5/qtlockedfile_win.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - - -#include "qtlockedfile.h" -#include -#include - -#define MUTEX_PREFIX "QtLockedFile mutex " -// Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS -#define MAX_READERS MAXIMUM_WAIT_OBJECTS - -Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) -{ - if (mutexname.isEmpty()) { - QFileInfo fi(*this); - mutexname = QString::fromLatin1(MUTEX_PREFIX) - + fi.absoluteFilePath().toLower(); - } - QString mname(mutexname); - if (idx >= 0) - mname += QString::number(idx); - - Qt::HANDLE mutex; - if (doCreate) { -#if (QT_VERSION < 0x050000) - QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, - { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); -#else - mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); -#endif - if (!mutex) { - qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); - return 0; - } - } - else { -#if (QT_VERSION < 0x050000) - QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, - { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); -#else - mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); -#endif - if (!mutex) { - if (GetLastError() != ERROR_FILE_NOT_FOUND) - qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); - return 0; - } - } - return mutex; -} - -bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock) -{ - Q_ASSERT(mutex); - DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); - switch (res) { - case WAIT_OBJECT_0: - case WAIT_ABANDONED: - return true; - break; - case WAIT_TIMEOUT: - break; - default: - qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); - } - return false; -} - - - -bool QtLockedFile::lock(LockMode mode, bool block) -{ - if (!isOpen()) { - qWarning("QtLockedFile::lock(): file is not opened"); - return false; - } - - if (mode == NoLock) - return unlock(); - - if (mode == m_lock_mode) - return true; - - if (m_lock_mode != NoLock) - unlock(); - - if (!wmutex && !(wmutex = getMutexHandle(-1, true))) - return false; - - if (!waitMutex(wmutex, block)) - return false; - - if (mode == ReadLock) { - int idx = 0; - for (; idx < MAX_READERS; idx++) { - rmutex = getMutexHandle(idx, false); - if (!rmutex || waitMutex(rmutex, false)) - break; - CloseHandle(rmutex); - } - bool ok = true; - if (idx >= MAX_READERS) { - qWarning("QtLockedFile::lock(): too many readers"); - rmutex = 0; - ok = false; - } - else if (!rmutex) { - rmutex = getMutexHandle(idx, true); - if (!rmutex || !waitMutex(rmutex, false)) - ok = false; - } - if (!ok && rmutex) { - CloseHandle(rmutex); - rmutex = 0; - } - ReleaseMutex(wmutex); - if (!ok) - return false; - } - else { - Q_ASSERT(rmutexes.isEmpty()); - for (int i = 0; i < MAX_READERS; i++) { - Qt::HANDLE mutex = getMutexHandle(i, false); - if (mutex) - rmutexes.append(mutex); - } - if (rmutexes.size()) { - DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), - TRUE, block ? INFINITE : 0); - if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { - if (res != WAIT_TIMEOUT) - qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); - m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky - unlock(); - return false; - } - } - } - - m_lock_mode = mode; - return true; -} - -bool QtLockedFile::unlock() -{ - if (!isOpen()) { - qWarning("QtLockedFile::unlock(): file is not opened"); - return false; - } - - if (!isLocked()) - return true; - - if (m_lock_mode == ReadLock) { - ReleaseMutex(rmutex); - CloseHandle(rmutex); - rmutex = 0; - } - else { - foreach(Qt::HANDLE mutex, rmutexes) { - ReleaseMutex(mutex); - CloseHandle(mutex); - } - rmutexes.clear(); - ReleaseMutex(wmutex); - } - - m_lock_mode = QtLockedFile::NoLock; - return true; -} - -QtLockedFile::~QtLockedFile() -{ - if (isOpen()) - unlock(); - if (wmutex) - CloseHandle(wmutex); -} diff --git a/app/src/libraries/qtSingleApplication5/qtsingleapplication.cpp b/app/src/libraries/qtSingleApplication5/qtsingleapplication.cpp deleted file mode 100644 index 8f837ff82..000000000 --- a/app/src/libraries/qtSingleApplication5/qtsingleapplication.cpp +++ /dev/null @@ -1,350 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - - -#include "qtsingleapplication.h" -#include "qtlocalpeer.h" -#include - -/*! - \class QtSingleApplication qtsingleapplication.h - \brief The QtSingleApplication class provides an API to detect and - communicate with running instances of an application. - - This class allows you to create applications where only one - instance should be running at a time. I.e., if the user tries to - launch another instance, the already running instance will be - activated instead. Another usecase is a client-server system, - where the first started instance will assume the role of server, - and the later instances will act as clients of that server. - - By default, the full path of the executable file is used to - determine whether two processes are instances of the same - application. You can also provide an explicit identifier string - that will be compared instead. - - The application should create the QtSingleApplication object early - in the startup phase, and call isRunning() to find out if another - instance of this application is already running. If isRunning() - returns false, it means that no other instance is running, and - this instance has assumed the role as the running instance. In - this case, the application should continue with the initialization - of the application user interface before entering the event loop - with exec(), as normal. - - The messageReceived() signal will be emitted when the running - application receives messages from another instance of the same - application. When a message is received it might be helpful to the - user to raise the application so that it becomes visible. To - facilitate this, QtSingleApplication provides the - setActivationWindow() function and the activateWindow() slot. - - If isRunning() returns true, another instance is already - running. It may be alerted to the fact that another instance has - started by using the sendMessage() function. Also data such as - startup parameters (e.g. the name of the file the user wanted this - new instance to open) can be passed to the running instance with - this function. Then, the application should terminate (or enter - client mode). - - If isRunning() returns true, but sendMessage() fails, that is an - indication that the running instance is frozen. - - Here's an example that shows how to convert an existing - application to use QtSingleApplication. It is very simple and does - not make use of all QtSingleApplication's functionality (see the - examples for that). - - \code - // Original - int main(int argc, char **argv) - { - QApplication app(argc, argv); - - MyMainWidget mmw; - mmw.show(); - return app.exec(); - } - - // Single instance - int main(int argc, char **argv) - { - QtSingleApplication app(argc, argv); - - if (app.isRunning()) - return !app.sendMessage(someDataString); - - MyMainWidget mmw; - app.setActivationWindow(&mmw); - mmw.show(); - return app.exec(); - } - \endcode - - Once this QtSingleApplication instance is destroyed (normally when - the process exits or crashes), when the user next attempts to run the - application this instance will not, of course, be encountered. The - next instance to call isRunning() or sendMessage() will assume the - role as the new running instance. - - For console (non-GUI) applications, QtSingleCoreApplication may be - used instead of this class, to avoid the dependency on the QtGui - library. - - \sa QtSingleCoreApplication -*/ - - -void QtSingleApplication::sysInit(const QString &appId) -{ - actWin = 0; - peer = new QtLocalPeer(this, appId); - connect(peer, &QtLocalPeer::messageReceived, - this, &QtSingleApplication::messageReceived); -} - - -/*! - Creates a QtSingleApplication object. The application identifier - will be QCoreApplication::applicationFilePath(). \a argc, \a - argv, and \a GUIenabled are passed on to the QAppliation constructor. - - If you are creating a console application (i.e. setting \a - GUIenabled to false), you may consider using - QtSingleCoreApplication instead. -*/ - -QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) - : QApplication(argc, argv, GUIenabled) -{ - sysInit(); -} - - -/*! - Creates a QtSingleApplication object with the application - identifier \a appId. \a argc and \a argv are passed on to the - QAppliation constructor. -*/ - -QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) - : QApplication(argc, argv) -{ - sysInit(appId); -} - - -/*! - Creates a QtSingleApplication object. The application identifier - will be QCoreApplication::applicationFilePath(). \a argc, \a - argv, and \a type are passed on to the QAppliation constructor. -*/ - -// Comment by Xi -/* -QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) - : QApplication(argc, argv, type) -{ - sysInit(); -} -*/ - - -#if defined(Q_WS_X11) -/*! - Special constructor for X11, ref. the documentation of - QApplication's corresponding constructor. The application identifier - will be QCoreApplication::applicationFilePath(). \a dpy, \a visual, - and \a cmap are passed on to the QApplication constructor. -*/ -QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap) - : QApplication(dpy, visual, cmap) -{ - sysInit(); -} - -/*! - Special constructor for X11, ref. the documentation of - QApplication's corresponding constructor. The application identifier - will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a - argv, \a visual, and \a cmap are passed on to the QApplication - constructor. -*/ -QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) - : QApplication(dpy, argc, argv, visual, cmap) -{ - sysInit(); -} - -/*! - Special constructor for X11, ref. the documentation of - QApplication's corresponding constructor. The application identifier - will be \a appId. \a dpy, \a argc, \a - argv, \a visual, and \a cmap are passed on to the QApplication - constructor. -*/ -QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) - : QApplication(dpy, argc, argv, visual, cmap) -{ - sysInit(appId); -} -#endif - - -/*! - Returns true if another instance of this application is running; - otherwise false. - - This function does not find instances of this application that are - being run by a different user (on Windows: that are running in - another session). - - \sa sendMessage() -*/ - -bool QtSingleApplication::isRunning() -{ - return peer->isClient(); -} - - -/*! - Tries to send the text \a message to the currently running - instance. The QtSingleApplication object in the running instance - will emit the messageReceived() signal when it receives the - message. - - This function returns true if the message has been sent to, and - processed by, the current instance. If there is no instance - currently running, or if the running instance fails to process the - message within \a timeout milliseconds, this function return false. - - \sa isRunning(), messageReceived() -*/ -bool QtSingleApplication::sendMessage(const QString &message, int timeout) -{ - return peer->sendMessage(message, timeout); -} - - -/*! - Returns the application identifier. Two processes with the same - identifier will be regarded as instances of the same application. -*/ -QString QtSingleApplication::id() const -{ - return peer->applicationId(); -} - - -/*! - Sets the activation window of this application to \a aw. The - activation window is the widget that will be activated by - activateWindow(). This is typically the application's main window. - - If \a activateOnMessage is true (the default), the window will be - activated automatically every time a message is received, just prior - to the messageReceived() signal being emitted. - - \sa activateWindow(), messageReceived() -*/ - -void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) -{ - actWin = aw; - if (activateOnMessage) - connect(peer, &QtLocalPeer::messageReceived, - this, &QtSingleApplication::activateWindow); - else - disconnect(peer, &QtLocalPeer::messageReceived, - this, &QtSingleApplication::activateWindow); -} - - -/*! - Returns the applications activation window if one has been set by - calling setActivationWindow(), otherwise returns 0. - - \sa setActivationWindow() -*/ -QWidget* QtSingleApplication::activationWindow() const -{ - return actWin; -} - - -/*! - De-minimizes, raises, and activates this application's activation window. - This function does nothing if no activation window has been set. - - This is a convenience function to show the user that this - application instance has been activated when he has tried to start - another instance. - - This function should typically be called in response to the - messageReceived() signal. By default, that will happen - automatically, if an activation window has been set. - - \sa setActivationWindow(), messageReceived(), initialize() -*/ -void QtSingleApplication::activateWindow() -{ - if (actWin) { - actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); - actWin->raise(); - actWin->activateWindow(); - } -} - - -/*! - \fn void QtSingleApplication::messageReceived(const QString& message) - - This signal is emitted when the current instance receives a \a - message from another instance of this application. - - \sa sendMessage(), setActivationWindow(), activateWindow() -*/ - - -/*! - \fn void QtSingleApplication::initialize(bool dummy = true) - - \obsolete -*/ diff --git a/app/src/libraries/qtSingleApplication5/qtsingleapplication.h b/app/src/libraries/qtSingleApplication5/qtsingleapplication.h deleted file mode 100644 index dcdeb5e59..000000000 --- a/app/src/libraries/qtSingleApplication5/qtsingleapplication.h +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#ifndef QTSINGLEAPPLICATION_H -#define QTSINGLEAPPLICATION_H - -#include - -class QtLocalPeer; - -#if defined(Q_WS_WIN) || defined(Q_OS_WIN32) -# if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) -# define QT_QTSINGLEAPPLICATION_EXPORT -# elif defined(QT_QTSINGLEAPPLICATION_IMPORT) -# if defined(QT_QTSINGLEAPPLICATION_EXPORT) -# undef QT_QTSINGLEAPPLICATION_EXPORT -# endif -# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) -# elif defined(QT_QTSINGLEAPPLICATION_EXPORT) -# undef QT_QTSINGLEAPPLICATION_EXPORT -# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) -# endif -#else -# define QT_QTSINGLEAPPLICATION_EXPORT -#endif - - -class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication -{ - Q_OBJECT - -public: - QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); - QtSingleApplication(const QString &id, int &argc, char **argv); - - // Comment by Xi - // QtSingleApplication(int &argc, char **argv, Type type); - -#if defined(Q_WS_X11) - QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); - QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0); - QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); -#endif - - bool isRunning(); - QString id() const; - - void setActivationWindow(QWidget* aw, bool activateOnMessage = true); - QWidget* activationWindow() const; - - // Obsolete: - void initialize(bool dummy = true) - { isRunning(); Q_UNUSED(dummy) } - -public Q_SLOTS: - bool sendMessage(const QString &message, int timeout = 5000); - void activateWindow(); - - -Q_SIGNALS: - void messageReceived(const QString &message); - - -private: - void sysInit(const QString &appId = QString()); - QtLocalPeer *peer; - QWidget *actWin; -}; - -#endif // QTSINGLEAPPLICATION_H diff --git a/app/src/libraries/qtSingleApplication5/qtsingleapplication.pri b/app/src/libraries/qtSingleApplication5/qtsingleapplication.pri deleted file mode 100644 index d4ce54f1f..000000000 --- a/app/src/libraries/qtSingleApplication5/qtsingleapplication.pri +++ /dev/null @@ -1,20 +0,0 @@ -include(../common.pri) -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -QT *= network - -contains(QT_VERSION, ^5.*) { - QT *= widgets -} - -qtsingleapplication-uselib:!qtsingleapplication-buildlib { - LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME -} else { - SOURCES += $$PWD/qtsingleapplication.cpp $$PWD/qtlocalpeer.cpp - HEADERS += $$PWD/qtsingleapplication.h $$PWD/qtlocalpeer.h -} - -win32 { - contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT - else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT -} diff --git a/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.cpp b/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.cpp deleted file mode 100644 index 0c65bc0fb..000000000 --- a/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - - -#include "qtsinglecoreapplication.h" -#include "qtlocalpeer.h" - -/*! - \class QtSingleCoreApplication qtsinglecoreapplication.h - \brief A variant of the QtSingleApplication class for non-GUI applications. - - This class is a variant of QtSingleApplication suited for use in - console (non-GUI) applications. It is an extension of - QCoreApplication (instead of QApplication). It does not require - the QtGui library. - - The API and usage is identical to QtSingleApplication, except that - functions relating to the "activation window" are not present, for - obvious reasons. Please refer to the QtSingleApplication - documentation for explanation of the usage. - - A QtSingleCoreApplication instance can communicate to a - QtSingleApplication instance if they share the same application - id. Hence, this class can be used to create a light-weight - command-line tool that sends commands to a GUI application. - - \sa QtSingleApplication -*/ - -/*! - Creates a QtSingleCoreApplication object. The application identifier - will be QCoreApplication::applicationFilePath(). \a argc and \a - argv are passed on to the QCoreAppliation constructor. -*/ - -QtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv) - : QCoreApplication(argc, argv) -{ - peer = new QtLocalPeer(this); - connect(peer, &QtLocalPeer::messageReceived, - this, &QtSingleCoreApplication::messageReceived); -} - - -/*! - Creates a QtSingleCoreApplication object with the application - identifier \a appId. \a argc and \a argv are passed on to the - QCoreAppliation constructor. -*/ -QtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv) - : QCoreApplication(argc, argv) -{ - peer = new QtLocalPeer(this, appId); - connect(peer, &QtLocalPeer::messageReceived, - this, &QtSingleCoreApplication::messageReceived); -} - - -/*! - Returns true if another instance of this application is running; - otherwise false. - - This function does not find instances of this application that are - being run by a different user (on Windows: that are running in - another session). - - \sa sendMessage() -*/ - -bool QtSingleCoreApplication::isRunning() -{ - return peer->isClient(); -} - - -/*! - Tries to send the text \a message to the currently running - instance. The QtSingleCoreApplication object in the running instance - will emit the messageReceived() signal when it receives the - message. - - This function returns true if the message has been sent to, and - processed by, the current instance. If there is no instance - currently running, or if the running instance fails to process the - message within \a timeout milliseconds, this function return false. - - \sa isRunning(), messageReceived() -*/ - -bool QtSingleCoreApplication::sendMessage(const QString &message, int timeout) -{ - return peer->sendMessage(message, timeout); -} - - -/*! - Returns the application identifier. Two processes with the same - identifier will be regarded as instances of the same application. -*/ - -QString QtSingleCoreApplication::id() const -{ - return peer->applicationId(); -} - - -/*! - \fn void QtSingleCoreApplication::messageReceived(const QString& message) - - This signal is emitted when the current instance receives a \a - message from another instance of this application. - - \sa sendMessage() -*/ diff --git a/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.h b/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.h deleted file mode 100644 index 43de8cb70..000000000 --- a/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). -** All rights reserved. -** -** Contact: Nokia Corporation (qt-info@nokia.com) -** -** This file is part of a Qt Solutions component. -** -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor -** the names of its contributors may be used to endorse or promote -** products derived from this software without specific prior written -** permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -****************************************************************************/ - -#ifndef QTSINGLECOREAPPLICATION_H -#define QTSINGLECOREAPPLICATION_H - - -#include - -class QtLocalPeer; - -class QtSingleCoreApplication : public QCoreApplication -{ - Q_OBJECT - -public: - QtSingleCoreApplication(int &argc, char **argv); - QtSingleCoreApplication(const QString &id, int &argc, char **argv); - - bool isRunning(); - QString id() const; - -public Q_SLOTS: - bool sendMessage(const QString &message, int timeout = 5000); - - -Q_SIGNALS: - void messageReceived(const QString &message); - - -private: - QtLocalPeer* peer; -}; - -#endif // QTSINGLECOREAPPLICATION_H diff --git a/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.pri b/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.pri deleted file mode 100644 index d2d6cc3e1..000000000 --- a/app/src/libraries/qtSingleApplication5/qtsinglecoreapplication.pri +++ /dev/null @@ -1,10 +0,0 @@ -INCLUDEPATH += $$PWD -DEPENDPATH += $$PWD -HEADERS += $$PWD/qtsinglecoreapplication.h $$PWD/qtlocalpeer.h -SOURCES += $$PWD/qtsinglecoreapplication.cpp $$PWD/qtlocalpeer.cpp - -QT *= network - -win32:contains(TEMPLATE, lib):contains(CONFIG, shared) { - DEFINES += QT_QTSINGLECOREAPPLICATION_EXPORT=__declspec(dllexport) -} diff --git a/app/src/libraries/wyedit/Editor.cpp b/app/src/libraries/wyedit/Editor.cpp index b7a3977c5..485c4d8be 100644 --- a/app/src/libraries/wyedit/Editor.cpp +++ b/app/src/libraries/wyedit/Editor.cpp @@ -51,7 +51,6 @@ Editor::Editor(QWidget *parent) : QWidget(parent) initDataEnableAssembly=true; initDataConfigFileName=""; - initDataEnableRandomSeed=false; initDataDisableToolList.clear(); dirFileEmptyReaction=DIRFILEEMPTY_REACTION_SHOW_ERROR; @@ -104,15 +103,6 @@ void Editor::initConfigFileName(QString name) } -void Editor::initEnableRandomSeed(bool flag) -{ - if(isInit) - criticalError("Method "+QString(__FUNCTION__)+" running before init() only."); - - initDataEnableRandomSeed=flag; -} - - void Editor::initDisableToolList(QStringList toolNames) { if(isInit) @@ -162,14 +152,6 @@ void Editor::init(int mode) expandEditAreaFlag=false; emit updateIndentSliderGeometry(); - - if(initDataEnableRandomSeed) - { - QDateTime datetime=QDateTime::currentDateTime (); - unsigned int seed=rand()+datetime.toTime_t(); - // qDebug() << "Random generator init " << seed; - srand(seed); - } } @@ -685,7 +667,7 @@ void Editor::setTextareaEditable(bool editable) // Получение текста области редактирования в формате HTML QString Editor::getTextarea(void) { - return textArea->document()->toHtml("UTF-8"); + return textArea->document()->toHtml(); } @@ -747,16 +729,14 @@ bool Editor::saveTextareaText() if (!wfile.open(QIODevice::WriteOnly | QIODevice::Text)) { - criticalError("WyEdit: Cant open file "+fullFileName+" for write."); + criticalError("WyEdit: Can't open file "+fullFileName+" for write."); return false; } qDebug() << "Write to file " << workFileName; QTextStream out(&wfile); - QString content=textArea->document()->toHtml("UTF-8"); - out.setCodec("UTF-8"); - out << content; + out << textArea->document()->toHtml(); return true; } @@ -828,8 +808,9 @@ bool Editor::saveTextareaImages(int mode=SAVE_IMAGES_SIMPLE) QStringList imageInDirectory=directory.entryList(QDir::Files); // Перебираются файлы в директории + static const QRegularExpression re("\\.png$"); foreach(QString fileName, imageInDirectory) - if( fileName.contains(QRegExp("\\.png$")) ) // Обрабатыватся только *.png файлы + if( fileName.contains(re) ) // Обрабатываются только *.png файлы if( !imagesNames.contains(fileName) ) // Только картинки, не встречающиеся в тексте записи if( !miscFields["attachFileNameList"].contains(fileName) ) // Только имена файлов, не содержащиеся в прикрепленных файлах { @@ -855,13 +836,13 @@ void Editor::saveTextarea(void) { // Перенос текущего файла записи в корзину qDebug() << "Try remove file " << getFileName() << " from directory " << getWorkDirectory(); - if( QFileInfo( getWorkDirectory()+"/"+getFileName() ).exists() ) + if( QFileInfo::exists( getWorkDirectory()+"/"+getFileName() ) ) { qDebug() << "File exists. Remove it."; DiskHelper::removeFileToTrash(getWorkDirectory()+"/"+getFileName()); } else - qDebug() << "Cant remove file. File not exists."; + qDebug() << "Can't remove file. File not exists."; // Если происходит прямая работа с файлом текста if(loadCallbackFunc==nullptr) @@ -876,7 +857,7 @@ void Editor::saveTextarea(void) { // Иначе задана функция обратного вызова для записи текста и картинок - QString content=textArea->document()->toHtml("UTF-8"); + QString content=textArea->document()->toHtml(); saveCallbackFunc(qobject_cast(this), content); } @@ -1048,10 +1029,10 @@ void Editor::onSelectionChanged(void) // Для анализа форматирования символов надо начинать // с позиции, следующей справа от начала выделения - QString startFontFamily=smartFontFamily( cursor.charFormat().fontFamily() ); // Шрифт + QString startFontFamily=smartFontFamily( cursor.charFormat().font().family() ); // Шрифт qreal startSize=smartFontSize( cursor.charFormat().fontPointSize() ); // Размер шрифта bool startBold=false; - if(cursor.charFormat().fontWeight()==QFont::Bold) startBold=true; // Тощина + if(cursor.charFormat().fontWeight()==QFont::Bold) startBold=true; // Толщина bool startItalic=cursor.charFormat().fontItalic(); // Наклон bool startUnderline=cursor.charFormat().fontUnderline(); // Подчеркивание bool startStrikeOut=cursor.charFormat().fontStrikeOut(); // Зачеркивание @@ -1082,7 +1063,7 @@ void Editor::onSelectionChanged(void) // разные начертания символов, разное выравнивание в выделенном тексте while(cursor.position()<=stop) { - if( differentFontFlag==false && startFontFamily!=smartFontFamily(cursor.charFormat().fontFamily()) ) + if( differentFontFlag==false && startFontFamily!=smartFontFamily(cursor.charFormat().font().family()) ) differentFontFlag=true; if( differentSizeFlag==false && startSize!=smartFontSize(cursor.charFormat().fontPointSize()) ) @@ -1457,17 +1438,10 @@ void Editor::setTabSize() { // Устанавка размера табуляции для клавиши Tab // Учитываем среднюю ширину глифов в шрифте - #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) textArea->setTabStopDistance( QFontMetrics(textArea->currentCharFormat().font()).averageCharWidth() * editorConfig->get_tab_size() ); - #else - textArea->setTabStopWidth( - QFontMetrics(textArea->currentCharFormat().font()).averageCharWidth() * - editorConfig->get_tab_size() - ); - #endif // Альтернатива, не учитывающая среднюю ширину глифов в шрифте // textArea->setTabStopDistance( diff --git a/app/src/libraries/wyedit/Editor.h b/app/src/libraries/wyedit/Editor.h index 02043f1e8..6111ebdc0 100644 --- a/app/src/libraries/wyedit/Editor.h +++ b/app/src/libraries/wyedit/Editor.h @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include @@ -92,7 +91,6 @@ class Editor : public QWidget void initEnableAssembly(bool flag); void initConfigFileName(QString name); - void initEnableRandomSeed(bool flag); void initDisableToolList(QStringList toolNames); void init(int mode); @@ -248,7 +246,6 @@ private slots: bool initDataEnableAssembly; QString initDataConfigFileName; - bool initDataEnableRandomSeed; QStringList initDataDisableToolList; // Рабочая директория редактора и файл текста diff --git a/app/src/libraries/wyedit/EditorAbsTable.cpp b/app/src/libraries/wyedit/EditorAbsTable.cpp index 09faf06e0..833ce7138 100644 --- a/app/src/libraries/wyedit/EditorAbsTable.cpp +++ b/app/src/libraries/wyedit/EditorAbsTable.cpp @@ -425,6 +425,8 @@ void EditorAbsTable::split_single_cell_by_horisontal(int x, int y, int div) switch( cells[x][i].get_cell_type() ) { + case EditorAbsTableCell::IS_NULL_CELL: __builtin_unreachable(); + // Если это обычная ячейка case EditorAbsTableCell::IS_NORMAL_CELL: { @@ -663,6 +665,8 @@ void EditorAbsTable::split_single_cell_by_vertical(int x1, int x2, int y, int di switch( cells[i][y].get_cell_type() ) { + case EditorAbsTableCell::IS_NULL_CELL: __builtin_unreachable(); + // Если это обычная ячейка case EditorAbsTableCell::IS_NORMAL_CELL: { diff --git a/app/src/libraries/wyedit/EditorAbsTableCell.cpp b/app/src/libraries/wyedit/EditorAbsTableCell.cpp index b971a718e..c89a73727 100644 --- a/app/src/libraries/wyedit/EditorAbsTableCell.cpp +++ b/app/src/libraries/wyedit/EditorAbsTableCell.cpp @@ -77,13 +77,13 @@ void EditorAbsTableCell::clear(void) } -int EditorAbsTableCell::get_cell_type(void) +EditorAbsTableCell::CELL_TYPE EditorAbsTableCell::get_cell_type(void) { return cellType; } -void EditorAbsTableCell::set_cell_type(int i) +void EditorAbsTableCell::set_cell_type(EditorAbsTableCell::CELL_TYPE i) { cellType=i; } @@ -124,10 +124,13 @@ int EditorAbsTableCell::get_ref_super_cell_y(void) void EditorAbsTableCell::print_cell(void) { char type; - if(cellType==IS_NULL_CELL) type='O'; - if(cellType==IS_NORMAL_CELL) type='N'; - if(cellType==IS_SUPER_CELL) type='S'; - if(cellType==IS_SUB_CELL) type='U'; + switch(cellType) { + case IS_NULL_CELL: type='O'; break; + case IS_NORMAL_CELL: type='N'; break; + case IS_SUPER_CELL: type='S'; break; + case IS_SUB_CELL: type='U'; break; + default: __builtin_unreachable(); + } QString val=value.simplified().trimmed(); val=val.leftJustified(5,'.',true); diff --git a/app/src/libraries/wyedit/EditorAbsTableCell.h b/app/src/libraries/wyedit/EditorAbsTableCell.h index a091f2f9d..67dde1885 100644 --- a/app/src/libraries/wyedit/EditorAbsTableCell.h +++ b/app/src/libraries/wyedit/EditorAbsTableCell.h @@ -25,8 +25,16 @@ class EditorAbsTableCell void clear(void); - void set_cell_type(int i); - int get_cell_type(void); + enum CELL_TYPE + { + IS_NULL_CELL, + IS_NORMAL_CELL, + IS_SUPER_CELL, + IS_SUB_CELL + }; + + void set_cell_type(EditorAbsTableCell::CELL_TYPE i); + EditorAbsTableCell::CELL_TYPE get_cell_type(void); void set_ref_super_cell_xy(int x, int y); void set_ref_super_cell_x(int x); @@ -39,14 +47,6 @@ class EditorAbsTableCell void print_cell(void); - enum CELL_TYPE - { - IS_NULL_CELL, - IS_NORMAL_CELL, - IS_SUPER_CELL, - IS_SUB_CELL - }; - private: // Свойства ячейки, заполняются из свойств тега @@ -56,7 +56,7 @@ class EditorAbsTableCell QString value; // Тип ячейки - int cellType; + CELL_TYPE cellType; // Координаты ведущей ячейки, если ячейка является подчиненной (isSubCell) int refSuperCellX; diff --git a/app/src/libraries/wyedit/EditorConfig.cpp b/app/src/libraries/wyedit/EditorConfig.cpp index 086447423..b20cf512a 100644 --- a/app/src/libraries/wyedit/EditorConfig.cpp +++ b/app/src/libraries/wyedit/EditorConfig.cpp @@ -23,14 +23,8 @@ EditorConfig::EditorConfig(QString config_file_name, QWidget *parent) : QWidget( if(fileinfo.isWritable()==false || fileinfo.isReadable()==false) criticalError("Editor config file "+config_file_name+" not writable or readable. Please check file permission."); - // Полное имя файла конфигурации разбивается на путь и имя файла - QString file_name=fileinfo.fileName(); - QString file_dir =fileinfo.path(); - // Создается объект работы с конфигурацией редактора conf=new QSettings(config_file_name, QSettings::IniFormat, this); - // conf->setPath(QSettings::IniFormat,QSettings::UserScope,file_dir); - // conf->setPath(QSettings::IniFormat,QSettings::SystemScope,file_dir); // Вызываются действия для обновления конфига update_version_process(); @@ -395,7 +389,7 @@ void EditorConfig::update_version_process(void) QList parameterFunctions; - parameterFunctions << nullptr; // Исторически счет версий идет с 1, поэтому, чтобы не запутаться, создается пустой нуливой элемент + parameterFunctions << nullptr; // Исторически счет версий идет с 1, поэтому, чтобы не запутаться, создается пустой нулевой элемент parameterFunctions << get_parameter_table_1; parameterFunctions << get_parameter_table_2; parameterFunctions << get_parameter_table_3; @@ -1088,12 +1082,8 @@ QString EditorConfig::update_version_change_value(int versionFrom, names["table_remove_row"]="tableRemoveRow"; names["table_split_cell"]="tableSplitCell"; - for (auto key: names.keys()) - { - auto value=names.value(key); - - result.replace(key, value); - } + for(auto kv = names.constKeyValueBegin(); kv != names.constKeyValueEnd(); ++kv) + result.replace(kv->first, kv->second); } diff --git a/app/src/libraries/wyedit/EditorContextMenu.cpp b/app/src/libraries/wyedit/EditorContextMenu.cpp index 1bf22e4b5..a82aba7eb 100644 --- a/app/src/libraries/wyedit/EditorContextMenu.cpp +++ b/app/src/libraries/wyedit/EditorContextMenu.cpp @@ -52,7 +52,7 @@ void EditorContextMenu::setupActions(void) void EditorContextMenu::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); shortcutManager.initAction("editor-undo", actionUndo ); shortcutManager.initAction("editor-redo", actionRedo ); diff --git a/app/src/libraries/wyedit/EditorFindDialog.cpp b/app/src/libraries/wyedit/EditorFindDialog.cpp index 3f346456f..8e48b2d9a 100644 --- a/app/src/libraries/wyedit/EditorFindDialog.cpp +++ b/app/src/libraries/wyedit/EditorFindDialog.cpp @@ -19,7 +19,7 @@ EditorFindDialog::EditorFindDialog(QWidget *parent) : QDialog(parent) assembly(); QShowEvent event; - showEvent(&event); + EditorFindDialog::showEvent(&event); } @@ -73,7 +73,7 @@ void EditorFindDialog::find_clicked(void) { QString text=lineEdit->text(); - QTextDocument::FindFlags flags=0; + QTextDocument::FindFlags flags; if(mathCase->isChecked()) flags|=QTextDocument::FindCaseSensitively; if(wholeWords->isChecked()) flags|=QTextDocument::FindWholeWords; if(searchBackward->isChecked())flags|=QTextDocument::FindBackward; diff --git a/app/src/libraries/wyedit/EditorMathExpressionDialog.cpp b/app/src/libraries/wyedit/EditorMathExpressionDialog.cpp index fa356eeb0..91325ed5f 100644 --- a/app/src/libraries/wyedit/EditorMathExpressionDialog.cpp +++ b/app/src/libraries/wyedit/EditorMathExpressionDialog.cpp @@ -82,7 +82,7 @@ void EditorMathExpressionDialog::showEvent(QShowEvent *event) // Масштабирование картинки формулы в зависимости от изменения размеров диалога void EditorMathExpressionDialog::resizeEvent(QResizeEvent *event) { - if (imageLabel!=nullptr && imageLabel->pixmap()!=nullptr) { + if (imageLabel && !imageLabel->pixmap().isNull()) { if (fitToScrollAreaCheckBox->isChecked()) { // Масштабирование картинки формулы pictureZoom(); @@ -208,7 +208,7 @@ void EditorMathExpressionDialog::assembly() // Область работы с картинкой формулы pictureFormulaLayout = new QVBoxLayout(); - pictureFormulaLayout->setMargin(5); + pictureFormulaLayout->setContentsMargins(5, 5, 5, 5); pictureFormulaLayout->addLayout(pictureFormulaControlLayout); pictureFormulaLayout->addWidget(imageScrollArea); @@ -226,7 +226,7 @@ void EditorMathExpressionDialog::assembly() // Область работы с текстом формулы textFormulaLayout = new QVBoxLayout(); - textFormulaLayout->setMargin(5); + textFormulaLayout->setContentsMargins(5, 5, 5, 5); textFormulaLayout->addLayout(textFormulaZoomLayout); textFormulaLayout->addWidget(textArea); @@ -242,7 +242,7 @@ void EditorMathExpressionDialog::assembly() /* Сборка всех контролов */ QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setMargin(5); + mainLayout->setContentsMargins(5, 5, 5, 5); // Добавление разделителя основных виджетов mainLayout->addWidget(mathSplitter); @@ -342,7 +342,7 @@ void EditorMathExpressionDialog::onRedo() void EditorMathExpressionDialog::updateFormulaPicture() { QString tempGifFileName = QDir::tempPath()+"/"+getUniqueId()+".gif"; - mathExpressionFormatter->createGifFromMathExpression( textArea->toPlainText(), tempGifFileName, false ); + mathExpressionFormatter->createGifFromMathExpression( textArea->toPlainText(), tempGifFileName ); QPixmap currentPixmap(tempGifFileName); @@ -360,7 +360,7 @@ void EditorMathExpressionDialog::updateFormulaPicture() imageLabel = new QLabel(this); imageLabel->setBackgroundRole(QPalette::Base); //imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); - imageLabel->setMargin(10); + imageLabel->setContentsMargins(10, 10, 10, 10); imageLabel->setScaledContents(true); imageLabel->setPixmap(currentPixmap); @@ -380,8 +380,8 @@ void EditorMathExpressionDialog::updateFormulaPicture() // Масштабирование картинки формулы void EditorMathExpressionDialog::pictureZoom() { - double pixHeight = imageLabel->pixmap()->height(); - double pixWidth = imageLabel->pixmap()->width(); + double pixHeight = imageLabel->pixmap().height(); + double pixWidth = imageLabel->pixmap().width(); double imageScrollAreaHeight = imageScrollArea->geometry().height()-10; double imageScrollAreaWidth = imageScrollArea->geometry().width()-10; if (pixHeight > imageScrollAreaHeight || pixWidth > imageScrollAreaWidth) { diff --git a/app/src/libraries/wyedit/EditorMultiLineInputDialog.cpp b/app/src/libraries/wyedit/EditorMultiLineInputDialog.cpp index 44e3ebf4d..db72db355 100644 --- a/app/src/libraries/wyedit/EditorMultiLineInputDialog.cpp +++ b/app/src/libraries/wyedit/EditorMultiLineInputDialog.cpp @@ -69,7 +69,7 @@ void EditorMultiLineInputDialog::setupUi() void EditorMultiLineInputDialog::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); QPushButton *okButton=buttonBox->button(QDialogButtonBox::Ok); // Выясняется указатель на кнопку OK okButton->setShortcut( shortcutManager.getKeySequence("misc-editConfirm") ); // Устанавливается шорткат @@ -124,7 +124,7 @@ void EditorMultiLineInputDialog::setWordWrapMode(QTextOption::WrapMode mode) } -void EditorMultiLineInputDialog::setSizeCoefficient(float f) +void EditorMultiLineInputDialog::setSizeCoefficient(double f) { sizeCoefficient=f; @@ -137,8 +137,8 @@ void EditorMultiLineInputDialog::updateSize() QWidget *parentWidget=qobject_cast(this->parent()); QRect geom(parentWidget->pos(), parentWidget->size()); - geom.setHeight( (int)((float)geom.height()*sizeCoefficient) ); - geom.setWidth ( (int)((float)geom.width()*sizeCoefficient) ); + geom.setHeight( (int)(geom.height()*sizeCoefficient) ); + geom.setWidth ( (int)(geom.width()*sizeCoefficient) ); qDebug() << "Parent window geometry " << geom.x() << geom.y() << geom.width() << geom.height(); diff --git a/app/src/libraries/wyedit/EditorMultiLineInputDialog.h b/app/src/libraries/wyedit/EditorMultiLineInputDialog.h index 8991368e3..4476aaee8 100644 --- a/app/src/libraries/wyedit/EditorMultiLineInputDialog.h +++ b/app/src/libraries/wyedit/EditorMultiLineInputDialog.h @@ -21,7 +21,7 @@ class EditorMultiLineInputDialog : public QDialog bool isModified(); // Выяснение, был ли изменен текст, показанный в диалоге void setWordWrapMode(QTextOption::WrapMode mode); - void setSizeCoefficient(float f); + void setSizeCoefficient(double f); public slots: @@ -29,7 +29,7 @@ public slots: private: - float sizeCoefficient; + double sizeCoefficient; QTextEdit *textArea; QDialogButtonBox *buttonBox; diff --git a/app/src/libraries/wyedit/EditorShowText.cpp b/app/src/libraries/wyedit/EditorShowText.cpp index 8e38afa4a..fb8979c65 100644 --- a/app/src/libraries/wyedit/EditorShowText.cpp +++ b/app/src/libraries/wyedit/EditorShowText.cpp @@ -173,7 +173,7 @@ void EditorShowText::showEvent(QShowEvent *event) // Если была запомнена геометрия окна, устанавливается прежняя геометрия if(!(mGeomX==0 && mGeomY==0 && mGeomW==0 && mGeomH==0)) { - // Установка геометрии происходит только если текущяя геометрия не совпадает с запомненной + // Установка геометрии происходит только если текущая геометрия не совпадает с запомненной if(x!=mGeomX || y!=mGeomY || w!=mGeomW || diff --git a/app/src/libraries/wyedit/EditorShowTextDispatcher.cpp b/app/src/libraries/wyedit/EditorShowTextDispatcher.cpp index a76264d00..556770bf8 100644 --- a/app/src/libraries/wyedit/EditorShowTextDispatcher.cpp +++ b/app/src/libraries/wyedit/EditorShowTextDispatcher.cpp @@ -167,10 +167,7 @@ void EditorShowTextDispatcher::updateWindow(const QString ¬eId) // Обновление содержимого всех открепляемых окон void EditorShowTextDispatcher::updateAllWindows() { - for( auto noteId : mWindowsList.keys() ) - { - this->updateWindow( noteId ); - } + std::for_each(mWindowsList.keyBegin(), mWindowsList.keyEnd(), [this](auto noteId){ this->updateWindow( noteId); }); } @@ -190,19 +187,7 @@ void EditorShowTextDispatcher::closeWindow(const QString ¬eId) // Так как списки могут быть длинными void EditorShowTextDispatcher::closeWindowByIdVector(const QVector &ids) { - for( auto id : ids ) - { - this->closeWindow(id); - } -} - - -// Закрытие окон по списку -// Метод сделан в виде слота, чтобы он мог выполняться в отдельном потоке -// Так как списки могут быть длинными -void EditorShowTextDispatcher::closeWindowByIdList(const QStringList &ids) -{ - for( auto id : ids ) + for( const auto & id : ids ) { this->closeWindow(id); } @@ -214,7 +199,7 @@ void EditorShowTextDispatcher::closeWindowByIdList(const QStringList &ids) // Так как списки могут быть длинными void EditorShowTextDispatcher::closeWindowByIdSet(const QSet &ids) { - for( auto id : ids ) + for( const auto & id : ids ) { this->closeWindow(id); } @@ -231,32 +216,23 @@ void EditorShowTextDispatcher::closeWindowForNonExistentRecords() KnowTreeModel *knowTreeModel=static_cast(find_object("knowTreeView")->model()); QSharedPointer< QSet > availableIds=knowTreeModel->getAllRecordsIdList(); - - for( auto noteId : mWindowsList.keys() ) - { - if( !availableIds.data()->contains(noteId) ) - { - this->closeWindow(noteId); - } - } + std::for_each(mWindowsList.keyBegin(), mWindowsList.keyEnd(), + [this, availableIds](auto noteId){ if(!availableIds.data()->contains(noteId)) this->closeWindow(noteId); }); } // Закрытие всех открепляемых окон void EditorShowTextDispatcher::closeAllWindows() { - for( auto noteId : mWindowsList.keys() ) - { - // Если существует connect() между - // EditorShowText::editorShowTextClose и EditorShowTextDispatcher::onCloseWindow - // то при выполнении метода close() открепляемого окна, должен будет вызваться слот - // EditorShowTextDispatcher::onCloseWindow() - // и в нем произойдет удаление окна из списка окон, - // и новое состояние списка открепляемых окон будет сохранено в конфиг. - // Объект окна должен будет сам удалиться, так как стоит флаг WA_DeleteOnClose - mWindowsList[ noteId ]->close(); - } - + // Если существует connect() между + // EditorShowText::editorShowTextClose и EditorShowTextDispatcher::onCloseWindow + // то при выполнении метода close() открепляемого окна, должен будет вызваться слот + // EditorShowTextDispatcher::onCloseWindow() + // и в нем произойдет удаление окна из списка окон, + // и новое состояние списка открепляемых окон будет сохранено в конфиг. + // Объект окна должен будет сам удалиться, так как стоит флаг WA_DeleteOnClose + std::for_each(mWindowsList.keyBegin(), mWindowsList.keyEnd(), + [this](auto noteId){ mWindowsList[ noteId ]->close(); }); mWindowsList.clear(); } @@ -267,12 +243,8 @@ void EditorShowTextDispatcher::closeAllWindows() // действий с открепляемыми окнами void EditorShowTextDispatcher::closeAllWindowsForExit() { - for( auto noteId : mWindowsList.keys() ) - { - mWindowsList[ noteId ]->disconnect(); // Все соединения закрываемого окна отключаются - mWindowsList[ noteId ]->close(); - } - + std::for_each(mWindowsList.keyBegin(), mWindowsList.keyEnd(), + [this](auto noteId){ mWindowsList[ noteId ]->disconnect(); mWindowsList[ noteId ]->close(); }); mWindowsList.clear(); } @@ -289,17 +261,17 @@ void EditorShowTextDispatcher::saveOpenWindows() { QStringList windowsState; - for( auto noteId : mWindowsList.keys() ) + for( auto noteId = mWindowsList.keyBegin(); noteId != mWindowsList.keyEnd(); ++noteId ) { QString state; - state=noteId+","; + state=*noteId+","; - QRect geom=mWindowsList[noteId]->geometry(); + QRect geom=mWindowsList[*noteId]->geometry(); state+=QString::number( geom.x() )+","; state+=QString::number( geom.y() )+","; state+=QString::number( geom.width() )+","; state+=QString::number( geom.height() )+","; - state+=QString::number( mWindowsList[noteId]->getTextVerticalScroll() ); + state+=QString::number( mWindowsList[*noteId]->getTextVerticalScroll() ); windowsState << state; } @@ -320,7 +292,7 @@ void EditorShowTextDispatcher::restoreOpenWindows() QStringList windowsState=state.split(";"); // Перебираются описания окон в виде ID и координат - for( auto window : windowsState ) + for( const auto & window : windowsState ) { if(window.trimmed().size()>0) // Если описание существует, а не пустая строка { @@ -342,7 +314,7 @@ void EditorShowTextDispatcher::switchBehavior(const QString &mode) { MainWindow *mainWindow=find_object("mainwindow"); - for( auto widgetWindow : mWindowsList ) + for( auto & widgetWindow : std::as_const(mWindowsList) ) { int x=widgetWindow->geometry().x(); int y=widgetWindow->geometry().y(); diff --git a/app/src/libraries/wyedit/EditorShowTextDispatcher.h b/app/src/libraries/wyedit/EditorShowTextDispatcher.h index ed0897ebd..4446f29ef 100644 --- a/app/src/libraries/wyedit/EditorShowTextDispatcher.h +++ b/app/src/libraries/wyedit/EditorShowTextDispatcher.h @@ -42,7 +42,6 @@ class EditorShowTextDispatcher : public QObject public slots: void closeWindowByIdVector(const QVector &ids); - void closeWindowByIdList(const QStringList &ids); void closeWindowByIdSet(const QSet< QString > &ids); void closeWindowForNonExistentRecords(); diff --git a/app/src/libraries/wyedit/EditorTextArea.cpp b/app/src/libraries/wyedit/EditorTextArea.cpp index 85c7e675e..1453eb530 100644 --- a/app/src/libraries/wyedit/EditorTextArea.cpp +++ b/app/src/libraries/wyedit/EditorTextArea.cpp @@ -257,7 +257,6 @@ void EditorTextArea::paintEvent(QPaintEvent *event) { QPainter p(viewport()); p.setRenderHint(QPainter::Antialiasing,false); - p.setRenderHint(QPainter::HighQualityAntialiasing,false); QPen pen(Qt::darkGray); pen.setStyle(Qt::SolidLine); @@ -335,7 +334,6 @@ void EditorTextArea::paintEvent(QPaintEvent *event) // Поверх рисуются элементы разметки QPainter p(viewport()); p.setRenderHint(QPainter::Antialiasing,false); - p.setRenderHint(QPainter::HighQualityAntialiasing,false); QPen pen(Qt::darkGray); pen.setStyle(Qt::SolidLine); @@ -430,7 +428,7 @@ void EditorTextArea::resizeEvent(QResizeEvent *event) } -// Метод возвращает X-координату курсора в "нуливой" позиции слева +// Метод возвращает X-координату курсора в "нулевой" позиции слева // Это значение используется для работы линейки отступов int EditorTextArea::getIndentStartedLeft(void) { @@ -653,7 +651,7 @@ void EditorTextArea::onChangeFontFamily(QString fontFamily) // Теперь так не работает, новый код сделан на основе Qt примера Text Edit QTextCharFormat format; - format.setFontFamily(fontFamily); + format.setFontFamilies({fontFamily}); qDebug() << "Font from font name: " << format.font().toString(); diff --git a/app/src/libraries/wyedit/EditorToolBar.cpp b/app/src/libraries/wyedit/EditorToolBar.cpp index 9247f9e77..0178b6b96 100644 --- a/app/src/libraries/wyedit/EditorToolBar.cpp +++ b/app/src/libraries/wyedit/EditorToolBar.cpp @@ -456,7 +456,7 @@ void EditorToolBar::hideAllToolsElements(void) { QStringList commandNameList=this->getCommandNameList(); - for(auto commandName : commandNameList) + for(const auto & commandName : commandNameList) { QWidget *widget=this->findChild(QString("editor_tb_")+commandName); if(widget) @@ -491,7 +491,7 @@ void EditorToolBar::setEnableModifyTextButton(bool state) // Перечень имен всех элементов управления на панели QStringList commandNameList=this->getCommandNameList(); - for(auto commandName : commandNameList) + for(const auto & commandName : commandNameList) { // Если элемент влияет на форматирование if( !noModifyButton.contains( commandName ) ) @@ -548,12 +548,12 @@ void EditorToolBar::clearToolsLines(void) // Владение QWidget-ми, которые вставлены в тулбары через addWidget(), // забирается от тулбаров и возвращается текущему объекту // Однако, данное действие не нужно делать для QAction, - // которые вствленны через addAction(), так как для QAction, + // которые вставлены через addAction(), так как для QAction, // в момент вставки в тулбар, владение не передается // Тулбар 1 QList objectList=toolsLine1.children(); - for(auto object : objectList) + for(auto & object : objectList) { QWidget *widget=dynamic_cast(object); if(widget) @@ -564,7 +564,7 @@ void EditorToolBar::clearToolsLines(void) // Тулбар 2 objectList=toolsLine2.children(); - for(auto object : objectList) + for(auto & object : objectList) { QWidget *widget=dynamic_cast(object); if(widget) @@ -679,7 +679,8 @@ void EditorToolBar::insertButtonToToolsLine(QString toolName, QToolBar &line) void EditorToolBar::registryActionsToToolBarWidget() { // Перебираются все инструменты редактора с шорткатами - for(auto toolName : shortcutManager.getActionsNameList("editor") ) + const auto tools = shortcutManager.getActionsNameList("editor"); + for(const auto & toolName : tools ) { // Запрещенные действия добавляться не должны if( disableToolList.contains(toolName) ) diff --git a/app/src/libraries/wyedit/EditorToolBarAssistant.cpp b/app/src/libraries/wyedit/EditorToolBarAssistant.cpp index 9f5e28bad..55c79eff4 100644 --- a/app/src/libraries/wyedit/EditorToolBarAssistant.cpp +++ b/app/src/libraries/wyedit/EditorToolBarAssistant.cpp @@ -151,9 +151,9 @@ void EditorToolBarAssistant::onChangeFontselectOnDisplay(QString fontName) { // Иначе шрифт с указанным названием не найден в списке шрифтов, // и надо попробовать выставить комбобоксе стандартный похожий шрифт - +#if QT_VERSION < 0x060000 QFontDatabase database; // База всех установленных шрифтов - +#endif // Вывод в консоль полного списка шифтов /* foreach (const QString &family, database.families()) { @@ -171,13 +171,18 @@ void EditorToolBarAssistant::onChangeFontselectOnDisplay(QString fontName) sameFonts << QPair("Microsoft Sans Serif", "Sans Serif"); // Перебираются пары похожих шрифтов - for(auto currentFontPair : sameFonts) + for(auto currentFontPair = sameFonts.cbegin(); currentFontPair != sameFonts.cend(); ++currentFontPair) { // Если входящий шрифт имеет похожий шрифт в базе установленных шрифтов - if(fontName==currentFontPair.first and - database.families().contains(currentFontPair.second)) + if(fontName==currentFontPair->first and +#if QT_VERSION > 0x060000 + QFontDatabase::families().contains(currentFontPair->second) +#else + database.families().contains(currentFontPair->second) +#endif + ) { - updateFontFamily=currentFontPair.second; + updateFontFamily=currentFontPair->second; fontSelect->setCurrentIndex( fontSelect->findText(updateFontFamily) ); break; } @@ -285,7 +290,6 @@ void EditorToolBarAssistant::onChangeBackgroundColor(const QColor &color) // Есть ли BackgroundBrush в тексте под курсором bool hasTextBackgroundBrush = textAreaFormat.hasProperty(QTextFormat::BackgroundBrush); - QPixmap pixMap( getIconSize() ); QColor fillColor; // Есть ли BackgroundBrush в тексте под курсором @@ -368,7 +372,6 @@ QPixmap EditorToolBarAssistant::drawIconOverColor(const QColor &fillColor, const painter.begin(&pixMap); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.setRenderHint(QPainter::Antialiasing); - painter.setRenderHint(QPainter::HighQualityAntialiasing); painter.drawPixmap(0, 0, icon.pixmap( pixMap.size() )); painter.end(); diff --git a/app/src/libraries/wyedit/formatters/ImageFormatter.cpp b/app/src/libraries/wyedit/formatters/ImageFormatter.cpp index 3c268a40f..bf70a4bdf 100644 --- a/app/src/libraries/wyedit/formatters/ImageFormatter.cpp +++ b/app/src/libraries/wyedit/formatters/ImageFormatter.cpp @@ -324,7 +324,8 @@ void ImageFormatter::onDownloadImages(const QString html) qDebug() << "Find " << imageName << "\n"; // имя файла // Если имя файла не является "внутренним", значит картинка еще не добавлена - if(!imageName.contains(QRegExp("^image\\d{10}[a-z0-9]+.png$"))) + static const QRegularExpression re("^image\\d{10}[a-z0-9]+.png$"); + if(!imageName.contains(re)) { if(msgBox.text().length()==0) { diff --git a/app/src/libraries/wyedit/formatters/MathExpressionFormatter.cpp b/app/src/libraries/wyedit/formatters/MathExpressionFormatter.cpp index 26d6fbaed..88c0c4381 100644 --- a/app/src/libraries/wyedit/formatters/MathExpressionFormatter.cpp +++ b/app/src/libraries/wyedit/formatters/MathExpressionFormatter.cpp @@ -27,7 +27,26 @@ MathExpressionFormatter::MathExpressionFormatter() { - +#if defined(Q_WS_WIN) || defined(Q_OS_WIN32) || defined(Q_OS_WINCE) || defined(Q_OS_MSDOS) || defined(Q_OS_CYGWIN) + // mimetex должен лежать там же где и mytetra + m_mimetex_bin = QCoreApplication::applicationDirPath() + "/mimetex.exe"; +#else + // try to find mimetex executable in PATH + // deb-based distros have mimetex. + // rpm-based distros have mimetex, but not in PATH and somewhy mimetex package depend on HTTP server 'caddy'. + // ArchLinux have mimetex.cgi binary in PATH + + for (const auto & d : QProcessEnvironment::systemEnvironment().value("PATH").split(':')) { + if (QFileInfo::exists(d + "/mimetex")) { + m_mimetex_bin = d + "/mimetex"; + return; + } else if (QFileInfo::exists(d + "/mimetex.cgi")) { + m_mimetex_bin = d + "/mimetex.cgi"; + return; + } + } + m_mimetex_bin = QCoreApplication::applicationDirPath() + "/mimetex"; +#endif } @@ -206,56 +225,12 @@ QString MathExpressionFormatter::getMathExpressionFromUser(QString iMathExpressi return dialog.getMathExpressionText().trimmed(); } - -void MathExpressionFormatter::createGifFromMathExpression(QString iMathExpression, QString iFileName, bool removeTeXFileToTrash) +void MathExpressionFormatter::createGifFromMathExpression(QString iMathExpression, QString iFileName) { - // Исходник в формате TeX записывается во временный файл - // Работа через файл с исходником TeX сделана для того, чтобы кроссплатформенно - // работала передача текста, без побочных шелл-эффектов, которые могут возникнуть - // при передаче математического варажения в командной строке - // Если removeTeXFileToTrash = true, то временный Tex файл удаляеься в корзину myTetra - // Если removeTeXFileToTrash = false, то временный Tex файл кничтожается - QString mathExpressionFileName=QDir::tempPath()+"/"+getUniqueId()+".txt"; - QFile mathExpressionFile(mathExpressionFileName); - if(!mathExpressionFile.open(QIODevice::WriteOnly | QIODevice::Text)) { - criticalError("Can not create temporary file for TeX source: "+mathExpressionFileName); - return; - } - mathExpressionFile.write(iMathExpression.toUtf8()); - mathExpressionFile.close(); - - // Запуск консольной команды для генерации картинки с формулой - QString mimetexBinaryName="mimetex"; - QString chDirCommand; - QString mimetexPath=QCoreApplication::applicationDirPath(); // mimetex должен лежать там же где и mytetra CommandRun exCommand; - - if(exCommand.getOsFamily()=="unix") { - mimetexBinaryName="./"+mimetexBinaryName; - chDirCommand="cd "+mimetexPath+" ; "; - } - - if(exCommand.getOsFamily()=="windows") { - mimetexBinaryName+=".exe"; - chDirCommand="chdir /D "+mimetexPath+" & "; - } - - QString command=chDirCommand+mimetexBinaryName+" -e "+iFileName+" -f "+mathExpressionFileName; - - qDebug() << "Command for create math expression picture: " << command; - - exCommand.setCommand(command); + exCommand.setCommand(m_mimetex_bin); + exCommand.setArgs({iMathExpression, "-e", iFileName}); exCommand.runSimple(); - - if (removeTeXFileToTrash) { - // Файл с TeX исходником удаляется в корзину - DiskHelper::removeFileToTrash( mathExpressionFileName ); - } else { - // Файл с TeX исходником полностью уничтожается - if (QFile::exists(mathExpressionFileName)) { - QFile::remove(mathExpressionFileName); - } - } } diff --git a/app/src/libraries/wyedit/formatters/MathExpressionFormatter.h b/app/src/libraries/wyedit/formatters/MathExpressionFormatter.h index 6523b4cd9..50dd7e6c8 100644 --- a/app/src/libraries/wyedit/formatters/MathExpressionFormatter.h +++ b/app/src/libraries/wyedit/formatters/MathExpressionFormatter.h @@ -18,7 +18,7 @@ class MathExpressionFormatter : public Formatter QString mathExpressionOnSelect(void); QString mathExpressionOnCursor(void); - void createGifFromMathExpression(QString iMathExpression, QString iFileName, bool removeTeXFileToTrash=true); + void createGifFromMathExpression(QString iMathExpression, QString iFileName); signals: @@ -38,6 +38,8 @@ public slots: QString getMathExpressionByImageName(QString resourceImageName); +private: + QString m_mimetex_bin; }; #endif // MATHEXPRESSIONFORMATTER_H diff --git a/app/src/libraries/wyedit/formatters/ReferenceFormatter.cpp b/app/src/libraries/wyedit/formatters/ReferenceFormatter.cpp index a660062d8..4717695d8 100644 --- a/app/src/libraries/wyedit/formatters/ReferenceFormatter.cpp +++ b/app/src/libraries/wyedit/formatters/ReferenceFormatter.cpp @@ -166,10 +166,7 @@ void ReferenceFormatter::onClickedGotoReference(QString href) bool ReferenceFormatter::isHrefInternal(QString href) { - if(href.contains(QRegExp("^"+FixedParameters::appTextId+":\\/\\/note\\/\\w+$"))) - return true; - else - return false; + return href.contains(QRegularExpression("^"+FixedParameters::appTextId+":\\/\\/note\\/\\w+$")); } @@ -178,7 +175,7 @@ QString ReferenceFormatter::getIdFromInternalHref(QString href) if(!isHrefInternal(href)) return ""; - href.replace(QRegExp("^"+FixedParameters::appTextId+":\\/\\/note\\/"), ""); + href.replace(QRegularExpression("^"+FixedParameters::appTextId+":\\/\\/note\\/"), ""); return href; } diff --git a/app/src/libraries/wyedit/formatters/TypefaceFormatter.cpp b/app/src/libraries/wyedit/formatters/TypefaceFormatter.cpp index 17dc1083b..0a65ef6fc 100644 --- a/app/src/libraries/wyedit/formatters/TypefaceFormatter.cpp +++ b/app/src/libraries/wyedit/formatters/TypefaceFormatter.cpp @@ -270,6 +270,7 @@ void TypefaceFormatter::onCodeClicked(void) return; textArea->textCursor().beginEditBlock(); + // Далее при любом выходе из метода нужно вызывать textArea->textCursor().endEditBlock() // Обработка мягкого переноса в выделенном тексте // Учитываются мягкие переносы до выделенного текста (1-й символ до выделения) и в выделенных абзацах @@ -300,8 +301,12 @@ void TypefaceFormatter::onCodeClicked(void) if(blockStart<=selectStart && blockStop>=selectStop) enableIndent=false; // Выбран кусок текста в пределах блока - else + else{ + qDebug() << "The selection is outside one block"; + //Хорошо бы писать в статусную строку сообщение, почему форматирование не выполнено + textArea->textCursor().endEditBlock(); return; + } } else enableIndent=true; // Выбран четко блок (блоки) текста, нужно делать отступ @@ -345,7 +350,7 @@ void TypefaceFormatter::onCodeClicked(void) // Форматирование для добавления отступа textArea->textCursor().mergeBlockFormat(indentFormatting); - editor->updateIndentsliderToActualFormat(); + emit editor->updateIndentsliderToActualFormat(); } textArea->textCursor().endEditBlock(); @@ -367,10 +372,7 @@ void TypefaceFormatter::onClearClicked(void) bool isSelectionReverse=false; if(startCursorPos>stopCursorPos) { - int tempCursorPos=startCursorPos; - startCursorPos=stopCursorPos; - stopCursorPos=tempCursorPos; - + std::swap(startCursorPos, stopCursorPos); isSelectionReverse=true; } // qDebug() << "Cursor start position: " << startCursorPos << "Cursor stop position: " << stopCursorPos; @@ -506,7 +508,7 @@ void TypefaceFormatter::onClearClicked(void) // обновились состояния подсветок кнопок форматирования editor->onSelectionChanged(); - editor->updateIndentsliderToActualFormat(); + emit editor->updateIndentsliderToActualFormat(); emit updateOutlineButtonHiglight(); } @@ -588,20 +590,13 @@ QString TypefaceFormatter::replaceSpacesOnlyTags(QString htmlCode) { qDebug() << "In TypefaceFormatter::replaceSpacesOnlyTags(): " << htmlSimplyfier( htmlCode ); - QRegExp replaceSpaceTagsEx("]*>\\s*"); - replaceSpaceTagsEx.setMinimal(true); + static const QRegularExpression replaceSpaceTagsEx("]*>\\s*", QRegularExpression::InvertedGreedinessOption); // Поиск тегов с одними пробелами внутри, с запоминанием их QStringList list; - int lastPos = 0; - while( ( lastPos = replaceSpaceTagsEx.indexIn( htmlCode, lastPos ) ) != -1 ) - { - lastPos += replaceSpaceTagsEx.matchedLength(); - - list << replaceSpaceTagsEx.cap(0); - // qDebug() << "Find space only sttring: " << list.last(); - } - + auto m = replaceSpaceTagsEx.globalMatch(htmlCode); + while (m.hasNext()) + list << m.next().captured(); // Замена найденных тегов на теги с RC-символом вместо пробелов for( int n = 0; n < list.size(); n++) @@ -639,8 +634,7 @@ QString TypefaceFormatter::clearTypeFace(QString htmlCode) // В регулярных выражениях Qt кванторы по-умолчанию жадные (greedy) // Поэтому напрямую регвыру указывается что кванторы должны быть ленивые - QRegExp removeStyleEx("style=\".*\""); - removeStyleEx.setMinimal(true); + static const QRegularExpression removeStyleEx("style=\".*\"", QRegularExpression::InvertedGreedinessOption); htmlCode.replace(removeStyleEx, "style=\"margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;\""); // qDebug() << "After remove style: " << htmlCode; @@ -674,14 +668,14 @@ QString TypefaceFormatter::clearTypeFace(QString htmlCode) // и тем самым создает лишнюю пустую строку // Жадная регулярка не всегда корректно захватывает строку (почему-то работает как ленивая), приходится разбивать на подстроки // Кроме того, в Qt нет возможности переключать режим multiline/не-multiline в регулярных выражениях - QStringList list=htmlCode.split(QRegularExpression("\\n")); + static const QRegularExpression regex("\\n"); + QStringList list=htmlCode.split(regex); QString tempHtmlCode; for(int lineNum=0; lineNum<\\/p.*>", QRegularExpression::InvertedGreedinessOption); - QRegExp replacePBrP("<\\/p.*>"); - replacePBrP.setMinimal(true); list[lineNum].replace(replacePBrP, "

"); // qDebug() << "L" << lineNum << " " << list[lineNum]; @@ -690,12 +684,10 @@ QString TypefaceFormatter::clearTypeFace(QString htmlCode) htmlCode=tempHtmlCode; // qDebug() << "After replace p br p: " << htmlCode; - QRegExp replaceOpenHeaderEx("<[hH]\\d.*>"); - replaceOpenHeaderEx.setMinimal(true); + static const QRegularExpression replaceOpenHeaderEx("<[hH]\\d.*>", QRegularExpression::InvertedGreedinessOption); htmlCode.replace(replaceOpenHeaderEx, "

"); - QRegExp replaceCloseHeaderEx(""); - replaceCloseHeaderEx.setMinimal(true); + static const QRegularExpression replaceCloseHeaderEx("", QRegularExpression::InvertedGreedinessOption); htmlCode.replace(replaceCloseHeaderEx, "

"); QStringList chunks=htmlCode.split(""); // Вместо удаления ".*" через медленную регулярку @@ -713,8 +705,7 @@ QString TypefaceFormatter::clearTypeFace(QString htmlCode) // Метод, применяемый при выводе отладочной информации, чтобы проще было смотреть на код QString TypefaceFormatter::htmlSimplyfier(QString htmlCode) { - QRegExp rx("style=\"([^\"]*)\""); - rx.setMinimal(true); + static const QRegularExpression rx("style=\"([^\"]*)\"", QRegularExpression::InvertedGreedinessOption); htmlCode.replace(rx, ""); // qDebug() << "After replace htmlSimplyfier: " << htmlCode; @@ -970,10 +961,7 @@ void TypefaceFormatter::onTextOnlyClicked() bool isSelectionReverse=false; if(startCursorPos>stopCursorPos) { - int tempCursorPos=startCursorPos; - startCursorPos=stopCursorPos; - stopCursorPos=tempCursorPos; - + std::swap(startCursorPos, stopCursorPos); isSelectionReverse=true; } // qDebug() << "Cursor start position: " << startCursorPos << "Cursor stop position: " << stopCursorPos; @@ -1072,7 +1060,7 @@ void TypefaceFormatter::onTextOnlyClicked() // Вызывается метод, как будто переместился курсор с выделением, чтобы // обновились состояния подсветок кнопок форматирования editor->onSelectionChanged(); - editor->updateIndentsliderToActualFormat(); + emit editor->updateIndentsliderToActualFormat(); emit updateOutlineButtonHiglight(); } @@ -1171,9 +1159,7 @@ void TypefaceFormatter::onFixBreakSymbolClicked() // В регулярных выражениях Qt кванторы по-умолчанию жадные (greedy) // Поэтому напрямую регвыру указывается что кванторы должны быть ленивые - QRegExp replace_expression(""); - replace_expression.setMinimal(true); - + static const QRegularExpression replace_expression("", QRegularExpression::InvertedGreedinessOption); htmlCode.replace(replace_expression, "

"); // qDebug() << "After remove style: " << htmlCode; @@ -1301,8 +1287,9 @@ void TypefaceFormatter::onInsertHorizontalLineClicked() // Определяем, не является ли этот символ слева от курсора мягким переносом QString html = textCursor.selection().toHtml(); - QRegExp regExp("\\s*\\s*"); - regExp.setMinimal(true); + static const QRegularExpression regExp("\\s*\\s*", + QRegularExpression::InvertedGreedinessOption); + if(html.indexOf(regExp) != -1) { // Если это мягкий перенос - заменяем его на абзац @@ -1347,8 +1334,8 @@ void TypefaceFormatter::workingSoftCarryInSelection() if(textCursor.anchor() != 0 && textCursor.position() != 0) // Пропускаем начало документо { QString html = textCursor.selection().toHtml(); - QRegExp regExp("\\s*(?:\\s*){1,}\\s*"); - regExp.setMinimal(true); + static const QRegularExpression regExp("\\s*(?:\\s*){1,}\\s*", + QRegularExpression::InvertedGreedinessOption); if(html.indexOf(regExp) != -1) { // Если это мягкий перенос - заменяем его на абзац @@ -1364,23 +1351,23 @@ void TypefaceFormatter::workingSoftCarryInSelection() // Ищем мягкий перенос в качестве пустого абзаца в расширенном вправо выделении QString htmlCode = textArea->textCursor().selection().toHtml(); - QRegExp regExp("\\s*(?:\\s*){1,}\\s*"); - regExp.setMinimal(true); - if(htmlCode.indexOf(regExp) != -1) + static const QRegularExpression regExp_1("\\s*(?:\\s*){1,}\\s*", + QRegularExpression::InvertedGreedinessOption); + if(htmlCode.indexOf(regExp_1) != -1) { // Заменяем проблемный код в html - htmlCode.replace(regExp, "


"); + htmlCode.replace(regExp_1, "


"); textArea->textCursor().insertHtml(htmlCode); } // Теперь обрабатываем смитуацию, когда на конце строки - мягкий перенос htmlCode = textArea->textCursor().selection().toHtml(); - regExp.setPattern("()(?:.+)\\s*)(?:(?:\\s*){1,}\\s*)()"); - regExp.setMinimal(true); - if(htmlCode.indexOf(regExp) != -1) + static const QRegularExpression regExp_2("()(?:.+)\\s*)(?:(?:\\s*){1,}\\s*)()", + QRegularExpression::InvertedGreedinessOption); + if(htmlCode.indexOf(regExp_2) != -1) { // Удаляем в html код
- htmlCode.replace(regExp, "\\1"); + htmlCode.replace(regExp_2, "\\1"); textArea->textCursor().insertHtml(htmlCode); } diff --git a/app/src/libraries/wyedit/indentslider/IndentSlider.cpp b/app/src/libraries/wyedit/indentslider/IndentSlider.cpp index aae314b8e..6ee9b393e 100644 --- a/app/src/libraries/wyedit/indentslider/IndentSlider.cpp +++ b/app/src/libraries/wyedit/indentslider/IndentSlider.cpp @@ -107,7 +107,6 @@ void IndentSlider::paintEvent(QPaintEvent *event) QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,false); - painter.setRenderHint(QPainter::HighQualityAntialiasing,false); // Настраивается перо QPen pen(Qt::black); //Qt::darkGray @@ -173,7 +172,7 @@ void IndentSlider::draw_rightindent(QPainter *painter) // Получение позиции отступа для отрисовки вертикальной линии отступа // Вертикальная линия может рисоваться для любого движка // Данный метод выясняет, какой движок в данный момент выбран -// и возвращяет его X-координату в данном виджете IndentSlider +// и возвращает его X-координату в данном виджете IndentSlider int IndentSlider::get_current_indentedge_pos(void) { if(current_sel_indent==SEL_NONE) @@ -285,7 +284,7 @@ void IndentSlider::mouseMoveEvent(QMouseEvent *event) } // Графика виджета обновляется для отрисовки нового положения движков - emit update(); + update(); } @@ -302,17 +301,17 @@ void IndentSlider::mouseReleaseEvent(QMouseEvent *event) void IndentSlider::set_textindent_pos(int i) { textindent_pos=i; - emit update(); + update(); } void IndentSlider::set_leftindent_pos(int i) { leftindent_pos=i; - emit update(); + update(); } void IndentSlider::set_rightindent_pos(int i) { rightindent_pos=i; - emit update(); + update(); } diff --git a/app/src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarSettingsScreen.cpp b/app/src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarSettingsScreen.cpp index db9e23610..3b3894bff 100644 --- a/app/src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarSettingsScreen.cpp +++ b/app/src/libraries/wyedit/mvc/views/editorToolbarSettings/EditorToolbarSettingsScreen.cpp @@ -185,9 +185,7 @@ void EditorToolbarSettingsScreen::onCheckViewToolbarWidget() { usedCommandsToolbarStackedWidget->setCurrentIndex(selectToolbarsListWidget->currentRow()); - QString text = QString("%1 %2") - .arg(tr("Tools at")) - .arg(selectToolbarsListWidget->item(selectToolbarsListWidget->currentRow())->text()); + QString text = QString("%1 %2").arg(tr("Tools at"), selectToolbarsListWidget->item(selectToolbarsListWidget->currentRow())->text()); usedCommandsToolbarLabel->setText(text); } @@ -225,7 +223,7 @@ void EditorToolbarSettingsScreen::onMoveAvailableCommandToUsedCommands() // Нашли такую же команду в ToolBar 1 QMessageBox *msbox = new QMessageBox( QMessageBox::Icon::Warning, "mytetra", - tr("%1: This command is already in %2.").arg(command).arg(tr("ToolBar 1")), + tr("%1: This command is already in %2.").arg(command, tr("ToolBar 1")), QMessageBox::Ok, this ); msbox->exec(); @@ -236,7 +234,7 @@ void EditorToolbarSettingsScreen::onMoveAvailableCommandToUsedCommands() if (commandIndex2!=QModelIndex()) { // Нашли такую же команду в ToolBar 2 QMessageBox msbox; - msbox.setText(tr("%1: This command is already in %2.").arg(command).arg(tr("ToolBar 2"))); + msbox.setText(tr("%1: This command is already in %2.").arg(command, tr("ToolBar 2"))); msbox.setIcon(QMessageBox::Icon::Warning); msbox.setStandardButtons(QMessageBox::Ok); msbox.exec(); @@ -275,7 +273,7 @@ void EditorToolbarSettingsScreen::onMoveAvailableCommandToUsedCommands() } // Удаление команды из модели списка всех доступных команд - // Элемент (имеющий всегда нуливой индекс) из модели всех доступных команд не удаляется + // Элемент (имеющий всегда нулевой индекс) из модели всех доступных команд не удаляется if (selectedAvailableIndex.row() != 0) { availableCommandsToolbarController->getModel()->removeRow(selectedAvailableIndex.row()); } diff --git a/app/src/main.cpp b/app/src/main.cpp index 3303b9af3..958e41043 100644 --- a/app/src/main.cpp +++ b/app/src/main.cpp @@ -24,7 +24,7 @@ #include "libraries/GlobalParameters.h" #include "libraries/ActionLogger.h" -#include "libraries/qtSingleApplication5/qtsingleapplication.h" +#include "libraries/qtSingleApplication/qtsingleapplication.h" #include "models/dataBaseConfig/DataBaseConfig.h" #include "libraries/WalkHistory.h" @@ -34,15 +34,13 @@ #include "libraries/TraceLogger.h" #include "libraries/ShortcutManager.h" #include "libraries/PeriodicCheckBase.h" -#include "libraries/PeriodicSyncro.h" +#include "libraries/PeriodicSynchro.h" #include "libraries/IconSelectDialog.h" #include "libraries/helpers/DebugHelper.h" #include "libraries/helpers/MessageHelper.h" #include "libraries/helpers/CssHelper.h" -using namespace std; - // todo: Разгрести объекты глобальной области, переделать все // на синглтоны, сделать объект ядра, поместить объекты глабальной // области в ядро как в единую центральную точку доступа @@ -74,7 +72,7 @@ ShortcutManager shortcutManager; // Различные периодические проверки PeriodicCheckBase periodicCheckBase; -PeriodicSyncro periodicSyncro; +PeriodicSynchro periodicSynchro; // Указатель на основное окно программы QObject *pMainWindow; @@ -83,7 +81,7 @@ QObject *pMainWindow; void printHelp() { printf("\n"); - printf("MyTetra v.%d.%d.%d\n", APPLICATION_RELEASE_VERSION, APPLICATION_RELEASE_SUBVERSION, APPLICATION_RELEASE_MICROVERSION); + printf("MyTetra %s\n", APPLICATION_VERSION); printf("For use control mode, run by standard way MyTetra for show GUI interface, and next use command:\n"); printf("./mytetra --control --show - Show and activate MyTetra window\n"); printf("./mytetra --control --hide - Hide MyTetra window\n"); @@ -195,7 +193,7 @@ void parseConsoleOption(QtSingleApplication &app) int main(int argc, char ** argv) { - printf("\n\rStart MyTetra v.%d.%d.%d\n\r", APPLICATION_RELEASE_VERSION, APPLICATION_RELEASE_SUBVERSION, APPLICATION_RELEASE_MICROVERSION); + printf("\nStart MyTetra %s\n", APPLICATION_VERSION); Q_INIT_RESOURCE(mytetra); @@ -218,11 +216,11 @@ int main(int argc, char ** argv) // Обработка консольных опций parseConsoleOption(app); - +#if QT_VERSION < 0x060000 // Установка увеличенного разрешения для дисплеев с большим DPI (Retina) if( qApp->devicePixelRatio() > 1.0 ) - qApp->setAttribute(Qt::AA_UseHighDpiPixmaps); - + qApp->setAttribute(Qt::AA_UseHighDpiPixmaps); +#endif // Инициализация глобальных параметров, // внутри происходит установка рабочей директории, настройка кодеков для локали и консоли @@ -261,13 +259,20 @@ int main(int argc, char ** argv) QString langFileName=":/resource/translations/mytetra_"+mytetraConfig.get_interfacelanguage()+".qm"; qDebug() << "Use language file " << langFileName; QTranslator langTranslator; - langTranslator.load(langFileName); - app.installTranslator(&langTranslator); + if(langTranslator.load(langFileName)) + app.installTranslator(&langTranslator); + else + qDebug() << "Can't install translations"; //Загрузка переводов стандартных диалогов и кнопок QTranslator qtTranslator; - if(qtTranslator.load("qt_" + QLocale().name().split('_').first(), - QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + if(qtTranslator.load("qt_" + mytetraConfig.get_interfacelanguage(), +#if QT_VERSION > 0x060000 + QLibraryInfo::path(QLibraryInfo::TranslationsPath) +#else + QLibraryInfo::location(QLibraryInfo::TranslationsPath) +#endif + )) { if(!app.installTranslator(&qtTranslator)) qDebug() << "Can't install QT translations"; @@ -370,9 +375,9 @@ int main(int argc, char ** argv) periodicCheckBase.start(); // Инициалиация периодической синхронизации - periodicSyncro.init(); - periodicSyncro.setDelay( mytetraConfig.getPeriodicSyncroPeriod() ); - periodicSyncro.start(); + periodicSynchro.init(); + periodicSynchro.setDelay( mytetraConfig.getPeriodicSynchroPeriod() ); + periodicSynchro.start(); // При закрытии окна не выходить из программы. // Окно программы может быть снова открыто из трея diff --git a/app/src/main.h b/app/src/main.h index b52f0b3c5..593ad1a51 100644 --- a/app/src/main.h +++ b/app/src/main.h @@ -17,9 +17,7 @@ #include #include #include -#include -using namespace std; // ---------------------------------------------------------- // MyTetra - программа для накопления осмысленной информации @@ -32,9 +30,9 @@ using namespace std; // ---------------------------------------------------------- // Версия программы -#define APPLICATION_RELEASE_VERSION 1 -#define APPLICATION_RELEASE_SUBVERSION 44 -#define APPLICATION_RELEASE_MICROVERSION 165 +#ifndef APPLICATION_VERSION +#define APPLICATION_VERSION "unknown" +#endif // Поддерживаемая версия формата базы (хранилища) #define CURRENT_FORMAT_VERSION 1 @@ -47,5 +45,8 @@ using namespace std; #define TRACELOG #endif +#ifdef Q_CC_MSVC +[[noreturn]] __forceinline void __builtin_unreachable() {__assume(false);} +#endif #endif // MYTETRA_MAIN_H diff --git a/app/src/models/actionLog/ActionLogModel.cpp b/app/src/models/actionLog/ActionLogModel.cpp index d71554620..c6342da33 100644 --- a/app/src/models/actionLog/ActionLogModel.cpp +++ b/app/src/models/actionLog/ActionLogModel.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include "main.h" #include "ActionLogModel.h" @@ -68,11 +69,8 @@ QVariant ActionLogModel::getCell(int row, int column, int role) const // Если вывод на экран, то происходит преобразование TIMESTAMP в человекочитаемый формат даты и времени if(role==Qt::DisplayRole) { - QDateTime fieldDateTime=QDateTime::fromTime_t( element.attribute("t").toUInt() ); - if(mytetraConfig.getEnableCustomDateTimeFormat()==false) - return fieldDateTime.toString(Qt::SystemLocaleDate); - else - return fieldDateTime.toString( mytetraConfig.getCustomDateTimeFormat() ); + auto fmt = mytetraConfig.getEnableCustomDateTimeFormat() ? mytetraConfig.getCustomDateTimeFormat() : QLocale::system().dateTimeFormat(QLocale::ShortFormat); + return QLocale::system().toString(QDateTime::fromSecsSinceEpoch(element.attribute("t").toUInt()), fmt); } else return QVariant( element.attribute("t") ); // Время передается в сыром виде (формат TIMESTAMP), чтобы была возможность сортировки @@ -86,7 +84,7 @@ QVariant ActionLogModel::getCell(int row, int column, int role) const // Вывод иконок if(role==Qt::DecorationRole) { - if(element.attribute("a")=="syncroProcessError" || element.attribute("a")=="syncroError") + if(element.attribute("a")=="synchroProcessError" || element.attribute("a")=="synchroError") return QCommonStyle().standardIcon(QStyle::SP_MessageBoxWarning); if(element.attribute("a")=="criticalError") diff --git a/app/src/models/appConfig/AppConfig.cpp b/app/src/models/appConfig/AppConfig.cpp index 8fc33b128..100dd57f5 100644 --- a/app/src/models/appConfig/AppConfig.cpp +++ b/app/src/models/appConfig/AppConfig.cpp @@ -3,7 +3,6 @@ #include "main.h" #include "AppConfig.h" -#include "AppConfigUpdater.h" #include "libraries/GlobalParameters.h" #include "libraries/helpers/DebugHelper.h" @@ -498,15 +497,15 @@ void AppConfig::set_synchroonexit(bool flag) } -bool AppConfig::getSyncroConsoleDetails(void) +bool AppConfig::getSynchroConsoleDetails(void) { - return conf->value("syncroConsoleDetails").toBool(); + return conf->value("synchroConsoleDetails").toBool(); } -void AppConfig::setSyncroConsoleDetails(bool flag) +void AppConfig::setSynchroConsoleDetails(bool flag) { - conf->setValue("syncroConsoleDetails", flag); + conf->setValue("synchroConsoleDetails", flag); } @@ -905,27 +904,27 @@ void AppConfig::setIconCurrentSectionName(QString name) // Разрешена ли периодическая синхронизация -bool AppConfig::getEnablePeriodicSyncro(void) +bool AppConfig::getEnablePeriodicSynchro(void) { - return conf->value("enablePeriodicSyncro").toBool(); + return conf->value("enablePeriodicSynchro").toBool(); } -void AppConfig::setEnablePeriodicSyncro(bool state) +void AppConfig::setEnablePeriodicSynchro(bool state) { - conf->setValue("enablePeriodicSyncro", state); + conf->setValue("enablePeriodicSynchro", state); } // Период автоматической периодической синхронизации -int AppConfig::getPeriodicSyncroPeriod(void) +int AppConfig::getPeriodicSynchroPeriod(void) { - return get_parameter("periodicSyncroPeriod").toInt(); + return get_parameter("periodicSynchroPeriod").toInt(); } -void AppConfig::setPeriodicSyncroPeriod(int period) +void AppConfig::setPeriodicSynchroPeriod(int period) { - conf->setValue("periodicSyncroPeriod", period); + conf->setValue("periodicSynchroPeriod", period); } @@ -970,934 +969,143 @@ void AppConfig::setDockableWindowsBehavior(QString mode) } -// -------------------- -// Номер версии конфига -// -------------------- - -int AppConfig::get_config_version(void) -{ - int v=conf->contains("version") ? conf->value("version").toInt() : 0; - - return v; -} - - -void AppConfig::set_config_version(int i) -{ - conf->setValue("version", i); -} - - -QStringList AppConfig::removeParameterFromTable(QString removeName, QStringList table) -{ - // Перебираются параметры в таблице - for(int i=0; i pFunction=&AppConfig::get_parameter_table_1; - - // Перечень функций, выдающих список параметров для конкретной версии конфига - QList< std::function< QStringList(AppConfig&, bool) > > parameterFunctions; - - parameterFunctions << nullptr; // Исторически счет версий идет с 1, поэтому, чтобы не запутаться, создается пустой нуливой элемент - parameterFunctions << &AppConfig::get_parameter_table_1; - parameterFunctions << &AppConfig::get_parameter_table_2; - parameterFunctions << &AppConfig::get_parameter_table_3; - parameterFunctions << &AppConfig::get_parameter_table_4; - parameterFunctions << &AppConfig::get_parameter_table_5; - parameterFunctions << &AppConfig::get_parameter_table_6; - parameterFunctions << &AppConfig::get_parameter_table_7; - parameterFunctions << &AppConfig::get_parameter_table_8; - parameterFunctions << &AppConfig::get_parameter_table_9; - parameterFunctions << &AppConfig::get_parameter_table_10; - parameterFunctions << &AppConfig::get_parameter_table_11; - parameterFunctions << &AppConfig::get_parameter_table_12; - parameterFunctions << &AppConfig::get_parameter_table_13; - parameterFunctions << &AppConfig::get_parameter_table_14; - parameterFunctions << &AppConfig::get_parameter_table_15; - parameterFunctions << &AppConfig::get_parameter_table_16; - parameterFunctions << &AppConfig::get_parameter_table_17; - parameterFunctions << &AppConfig::get_parameter_table_18; - parameterFunctions << &AppConfig::get_parameter_table_19; - parameterFunctions << &AppConfig::get_parameter_table_20; - parameterFunctions << &AppConfig::get_parameter_table_21; - parameterFunctions << &AppConfig::get_parameter_table_22; - parameterFunctions << &AppConfig::get_parameter_table_23; - parameterFunctions << &AppConfig::get_parameter_table_24; - parameterFunctions << &AppConfig::get_parameter_table_25; - parameterFunctions << &AppConfig::get_parameter_table_26; - parameterFunctions << &AppConfig::get_parameter_table_27; - parameterFunctions << &AppConfig::get_parameter_table_28; - parameterFunctions << &AppConfig::get_parameter_table_29; - parameterFunctions << &AppConfig::get_parameter_table_30; - parameterFunctions << &AppConfig::get_parameter_table_31; - parameterFunctions << &AppConfig::get_parameter_table_32; - parameterFunctions << &AppConfig::get_parameter_table_33; - parameterFunctions << &AppConfig::get_parameter_table_34; - parameterFunctions << &AppConfig::get_parameter_table_35; - parameterFunctions << &AppConfig::get_parameter_table_36; - parameterFunctions << &AppConfig::get_parameter_table_37; - parameterFunctions << &AppConfig::get_parameter_table_38; - - for(int i=1; icontains(name)) + conf->setValue(name, value); +} + +void AppConfig::set_version_1_default_params() +{ + add_default_param("addnewrecord_expand_info" , 1); + add_default_param("findscreen_find_inname" , true); + add_default_param("findscreen_find_intags" , true); + add_default_param("findscreen_find_intext" , true); + add_default_param("findscreen_howextract" , 1); + add_default_param("findscreen_show" , false); + add_default_param("findscreen_wordregard" , 1); + add_default_param("findsplitter_size_list" , "517,141"); + add_default_param("hspl_size_list" , "237,621"); + add_default_param("lastidnum" , 3537); + add_default_param("lastnotenum" , 3119); + add_default_param("lastprefixnum" , 7540); + add_default_param("mainwingeometry" , "155,24,864,711)"); + add_default_param("recordtable_position" , 0); + add_default_param("tetradir" , "/opt/mytetra/data"); + add_default_param("trashdir" , "/opt/mytetra/trash"); + add_default_param("trashmaxfilecount" , 200); + add_default_param("trashsize" , 5); + add_default_param("tree_position" , "0,1818,1819"); + add_default_param("vspl_size_list" , "171,487"); + add_default_param("findscreen_find_inauthor" , true); + add_default_param("findscreen_find_inurl" , false); } -QStringList AppConfig::get_parameter_table_17(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 16 - table << get_parameter_table_16(false); - - // Новые параметры - if(globalParameters.getTargetOs()=="android") - table << "showSplashScreen" << "bool" << "true"; // В Андроид долгий запуск, нужно показывать сплешскрин - else - table << "showSplashScreen" << "bool" << "false"; // На десктопе быстрый запуск, сплешскрин только мешает - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_18(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 17 - table << get_parameter_table_17(false); - - // Новые параметры - if(globalParameters.getTargetOs()=="android") - table << "interfaceMode" << "QString" << "mobile"; // В Андроид должен быть мобильный интерфейс - else - table << "interfaceMode" << "QString" << "desktop"; // На десктопе должен быть интерфейс адоптированный для работы на рабочем столе - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_19(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 18 - table << get_parameter_table_18(false); - - // Новые параметры - table << "focusWidget" << "QString" << ""; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_20(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 19 - table << get_parameter_table_19(false); - - // Новые параметры - if(globalParameters.getTargetOs()=="android") - table << "hideEditorTools" << "QString" << "italic,underline,monospace,alignleft,aligncenter,alignright,alignwidth,numericlist,dotlist,indentplus,indentminus,showformatting,showhtml,fontcolor,backgroundcolor,expand_edit_area,save,createtable,table_add_row,table_remove_row,table_add_col,table_remove_col,table_merge_cells,table_split_cell"; // В Андроид прячутся инструменты сложного форматирования текста - else - table << "hideEditorTools" << "QString" << ""; // На десктопе скрываемых кнопок редактора нет - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_21(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 20 - table << get_parameter_table_20(false); - - table << "findInBaseExpand" << "bool" << "true"; - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_22(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 21 - table << get_parameter_table_21(false); - - table << "recordtableSelectedRecordId" << "QString" << ""; - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_23(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 22 - table << get_parameter_table_22(false); - - // Исключаются ненужные в новой версии параметры - table=removeParameterFromTable("recordtable_position", table); - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_24(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 23 - table << get_parameter_table_23(false); - - table << "enableCustomDateTimeFormat" << "bool" << "false"; - table << "customDateTimeFormat" << "QString" << ""; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_25(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 24 - table << get_parameter_table_24(false); - - table << "attachAppendDir" << "QString" << ""; - table << "attachSaveAsDir" << "QString" << ""; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_26(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 25 - table << get_parameter_table_25(false); - - table << "enableDecryptFileToTrashDirectory" << "bool" << "false"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_27(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 26 - table << get_parameter_table_26(false); - - table << "actionLogMaximumSize" << "int" << "1"; // 1 Мб - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_28(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 27 - table << get_parameter_table_27(false); - - table << "enableLogging" << "bool" << "false"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_29(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 28 - table << get_parameter_table_28(false); - - table << "enableRecordWithAttachHighlight" << "bool" << "true"; - table << "recordWithAttachHighlightColor" << "QString" << "#d1e3c5"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_30(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 29 - table << get_parameter_table_29(false); - - table << "enablePeriodicCheckBase" << "bool" << "false"; - table << "checkBasePeriod" << "int" << "20"; - table << "enablePeriodicCheckMessage" << "bool" << "false"; - - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_31(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 30 - table << get_parameter_table_30(false); - - table << "previewIconSize" << "int" << "24"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_32(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 31 - table << get_parameter_table_31(false); - - table << "iconCurrentSectionName" << "QString" << "Essential"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_33(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 32 - table << get_parameter_table_32(false); - - table << "enablePeriodicSyncro" << "bool" << "false"; - table << "periodicSyncroPeriod" << "int" << "300"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_34(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 33 - table << get_parameter_table_33(false); - - table << "enableCreateEmptyRecord" << "bool" << "false"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_35(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 34 - table << get_parameter_table_34(false); - - // Новый флаг, поиск по названию ветки - table << "findscreen_find_innameItem" << "bool" << "false"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_36(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 35 - table << get_parameter_table_35(false); - - // Состояние окрепляемых окон - // Предполагаемый формат - "IDзаписи1,x1,y1,w1,h1;IDзаписи2,x2,y2,w2,h2..." - table << "dockableWindowsState" << "QString" << ""; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_37(bool withEndSignature) -{ - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 36 - table << get_parameter_table_36(false); - - // Поведение окрепляемых окон - table << "dockableWindowsBehavior" << "QString" << "single"; - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; -} - - -QStringList AppConfig::get_parameter_table_38(bool withEndSignature) +void AppConfig::update_version_process(void) { - // Таблица параметров - // Имя, Тип, Значение на случай когда в конфиге параметра прочему-то нет - QStringList table; - - // Старые параметры, аналогичные версии 37 - table << get_parameter_table_37(false); - - // Обновление формата конфига не происходит, обновляется только - // представление параметра dockableWindowsState - // см. AppConfigUpdater::updateValueRepresentation - - if(withEndSignature) - table << "0" << "0" << "0"; - - return table; + switch(conf->value("version").toInt()) { + case 1: set_version_1_default_params(); [[fallthrough]]; + case 2: add_default_param("cutbranchconfirm", true); [[fallthrough]]; + case 3: add_default_param("printdebugmessages", false); [[fallthrough]]; + case 4: add_default_param("interfacelanguage", "en"); + add_default_param("programm", "mytetra"); [[fallthrough]]; + case 5: conf->remove("lastidnum"); + conf->remove("lastnotenum"); + conf->remove("lastprefixnum"); [[fallthrough]]; + case 6: add_default_param("howpassrequest", "atClickOnCryptBranch"); [[fallthrough]]; + case 7: add_default_param("runinminimizedwindow", false); [[fallthrough]]; + case 8: add_default_param("synchrocommand", ""); + add_default_param("synchroonstartup", false); + add_default_param("synchroonexit", false); [[fallthrough]]; + case 9: add_default_param("syncroConsoleDetails", false); [[fallthrough]]; + case 10: add_default_param("autoClosePasswordEnable", false); + add_default_param("autoClosePasswordDelay", 10); [[fallthrough]]; + case 11: add_default_param("editorCursorPosition", 0); + add_default_param("editorScrollBarPosition", 0); [[fallthrough]]; + case 12: add_default_param("passwordMiddleHash", ""); + add_default_param("passwordSaveFlag", false); [[fallthrough]]; + case 13: add_default_param("rememberCursorAtHistoryNavigation", true); + add_default_param("rememberCursorAtOrdinarySelection", true); [[fallthrough]]; + case 14: add_default_param("findScreenTreeSearchArea", 0); [[fallthrough]]; + case 15: // Так как не все параметры можно стилизовать через QSS, здесь задается высота ячейки таблицы + add_default_param("uglyQssReplaceHeightForTableView", globalParameters.getTargetOs()=="android" ? 35 : 0); [[fallthrough]]; + case 16: add_default_param("recordTableShowFields", "name,tags"); + add_default_param("recordTableFieldsWidth", "256,128"); + add_default_param("recordTableShowHorizontalHeaders", true); + add_default_param("recordTableShowVerticalHeaders", false); [[fallthrough]]; + case 17: // В Android долгий запуск, нужно показывать сплешскрин, а на десктопе быстрый запуск, сплешскрин только мешает + add_default_param("showSplashScreen", globalParameters.getTargetOs()=="android" ? true : false); [[fallthrough]]; + case 18: add_default_param("interfaceMode", globalParameters.getTargetOs()=="android" ? "mobile" : "desktop"); [[fallthrough]]; + case 19: add_default_param("focusWidget", ""); [[fallthrough]]; + case 20: { + // В Android прячутся инструменты сложного форматирования текста + QString a = "italic,underline,monospace,alignleft,aligncenter,alignright,alignwidth," + "numericlist,dotlist,indentplus,indentminus,showformatting,showhtml,fontcolor," + "backgroundcolor,expand_edit_area,save,createtable,table_add_row,table_remove_row," + "table_add_col,table_remove_col,table_merge_cells,table_split_cell"; + add_default_param("hideEditorTools", globalParameters.getTargetOs()=="android" ? a : ""); + [[fallthrough]]; + } + case 21: add_default_param("findInBaseExpand", true); [[fallthrough]]; + case 22: add_default_param("recordtableSelectedRecordId", ""); [[fallthrough]]; + case 23: conf->remove("recordtable_position"); [[fallthrough]]; + case 24: add_default_param("enableCustomDateTimeFormat", false); + add_default_param("customDateTimeFormat", ""); [[fallthrough]]; + case 25: add_default_param("attachAppendDir", ""); + add_default_param("attachSaveAsDir", ""); [[fallthrough]]; + case 26: add_default_param("enableDecryptFileToTrashDirectory", false); [[fallthrough]]; + case 27: add_default_param("actionLogMaximumSize", 1/*Мб*/); [[fallthrough]]; + case 28: add_default_param("enableLogging", false); [[fallthrough]]; + case 29: add_default_param("enableRecordWithAttachHighlight", true); + add_default_param("recordWithAttachHighlightColor", "#d1e3c5"); [[fallthrough]]; + case 30: add_default_param("enablePeriodicCheckBase", false); + add_default_param("checkBasePeriod", 20); + add_default_param("enablePeriodicCheckMessage", false); [[fallthrough]]; + case 31: add_default_param("previewIconSize", 24); [[fallthrough]]; + case 32: add_default_param("iconCurrentSectionName", "Essential"); [[fallthrough]]; + case 33: add_default_param("enablePeriodicSyncro", false); + add_default_param("periodicSyncroPeriod", 300); [[fallthrough]]; + case 34: add_default_param("enableCreateEmptyRecord", false); [[fallthrough]]; + case 35: add_default_param("findscreen_find_innameItem", false); [[fallthrough]]; + case 36: // Предполагаемый формат - "IDзаписи1,x1,y1,w1,h1;IDзаписи2,x2,y2,w2,h2..." + add_default_param("dockableWindowsState", ""); [[fallthrough]]; + case 37: add_default_param("dockableWindowsBehavior", "single"); [[fallthrough]]; + case 38: { + auto val = conf->value("dockableWindowsState").toString(); + if(val.trimmed().size() > 1) + { + auto chunks = val.split(';'); + for(auto & c : chunks) + c += ",0"; + + val = chunks.join(';'); + conf->setValue("dockableWindowsState", val); + } + [[fallthrough]]; + } + case 39: { + // rename '*syncro*' to '*synchro*' + auto pv = conf->value("enablePeriodicSyncro"); + conf->remove("enablePeriodicSyncro"); + add_default_param("enablePeriodicSynchro", pv); + + pv = conf->value("periodicSyncroPeriod"); + conf->remove("periodicSyncroPeriod"); + add_default_param("periodicSynchroPeriod", pv); + + pv = conf->value("syncroConsoleDetails"); + conf->remove("syncroConsoleDetails"); + add_default_param("synchroConsoleDetails", pv); + } + } // end big switch + + // Устанавливается новый номер версии + conf->setValue("version", 39); + + // Конфигурация записывается на диск + conf->sync(); } diff --git a/app/src/models/appConfig/AppConfig.h b/app/src/models/appConfig/AppConfig.h index 7946c06c1..3fed75c3b 100644 --- a/app/src/models/appConfig/AppConfig.h +++ b/app/src/models/appConfig/AppConfig.h @@ -6,9 +6,6 @@ #include #include -class QRect; -class QStringList; - class AppConfig : public QObject { Q_OBJECT @@ -24,11 +21,6 @@ class AppConfig : public QObject QString getConfigFileName(); - // Версия формата конфигфайла - int get_config_version(void); - void set_config_version(int i); - - // Директория с базой знаний QString get_tetradir(void); bool set_tetradir(QString dirName); @@ -124,8 +116,8 @@ class AppConfig : public QObject bool get_synchroonexit(void); void set_synchroonexit(bool flag); - bool getSyncroConsoleDetails(void); - void setSyncroConsoleDetails(bool flag); + bool getSynchroConsoleDetails(void); + void setSynchroConsoleDetails(bool flag); int getEditorCursorPosition(void); void setEditorCursorPosition(int n); @@ -241,12 +233,12 @@ class AppConfig : public QObject void setIconCurrentSectionName(QString name); // Разрешена ли периодическая синхронизация - bool getEnablePeriodicSyncro(void); - void setEnablePeriodicSyncro(bool state); + bool getEnablePeriodicSynchro(void); + void setEnablePeriodicSynchro(bool state); // Период автоматической периодической синхронизации - int getPeriodicSyncroPeriod(void); - void setPeriodicSyncroPeriod(int period); + int getPeriodicSynchroPeriod(void); + void setPeriodicSynchroPeriod(int period); // Разрешено ли создавать запись без текста bool getEnableCreateEmptyRecord(void); @@ -266,53 +258,10 @@ class AppConfig : public QObject QString get_parameter(QString name); - QStringList removeParameterFromTable(QString removeName, QStringList table); - QString getParameterTypeFromTable(QString parameterName, QStringList table); - QString getParameterValueFromTable(QString parameterName, QStringList table); - QStringList replaceParameterInTable(QString replaceName, QString replaceType, QString replaceValue, QStringList table); - - + void add_default_param(const QString name, const QVariant value); + void set_version_1_default_params(); void update_version_process(void); - QStringList get_parameter_table_1 (bool withEndSignature=true); - QStringList get_parameter_table_2 (bool withEndSignature=true); - QStringList get_parameter_table_3 (bool withEndSignature=true); - QStringList get_parameter_table_4 (bool withEndSignature=true); - QStringList get_parameter_table_5 (bool withEndSignature=true); - QStringList get_parameter_table_6 (bool withEndSignature=true); - QStringList get_parameter_table_7 (bool withEndSignature=true); - QStringList get_parameter_table_8 (bool withEndSignature=true); - QStringList get_parameter_table_9 (bool withEndSignature=true); - QStringList get_parameter_table_10(bool withEndSignature=true); - QStringList get_parameter_table_11(bool withEndSignature=true); - QStringList get_parameter_table_12(bool withEndSignature=true); - QStringList get_parameter_table_13(bool withEndSignature=true); - QStringList get_parameter_table_14(bool withEndSignature=true); - QStringList get_parameter_table_15(bool withEndSignature=true); - QStringList get_parameter_table_16(bool withEndSignature=true); - QStringList get_parameter_table_17(bool withEndSignature=true); - QStringList get_parameter_table_18(bool withEndSignature=true); - QStringList get_parameter_table_19(bool withEndSignature=true); - QStringList get_parameter_table_20(bool withEndSignature=true); - QStringList get_parameter_table_21(bool withEndSignature=true); - QStringList get_parameter_table_22(bool withEndSignature=true); - QStringList get_parameter_table_23(bool withEndSignature=true); - QStringList get_parameter_table_24(bool withEndSignature=true); - QStringList get_parameter_table_25(bool withEndSignature=true); - QStringList get_parameter_table_26(bool withEndSignature=true); - QStringList get_parameter_table_27(bool withEndSignature=true); - QStringList get_parameter_table_28(bool withEndSignature=true); - QStringList get_parameter_table_29(bool withEndSignature=true); - QStringList get_parameter_table_30(bool withEndSignature=true); - QStringList get_parameter_table_31(bool withEndSignature=true); - QStringList get_parameter_table_32(bool withEndSignature=true); - QStringList get_parameter_table_33(bool withEndSignature=true); - QStringList get_parameter_table_34(bool withEndSignature=true); - QStringList get_parameter_table_35(bool withEndSignature=true); - QStringList get_parameter_table_36(bool withEndSignature=true); - QStringList get_parameter_table_37(bool withEndSignature=true); - QStringList get_parameter_table_38(bool withEndSignature=true); - bool is_init_flag; }; diff --git a/app/src/models/appConfig/AppConfigUpdater.cpp b/app/src/models/appConfig/AppConfigUpdater.cpp deleted file mode 100644 index ecef7c624..000000000 --- a/app/src/models/appConfig/AppConfigUpdater.cpp +++ /dev/null @@ -1,278 +0,0 @@ -#include -#include - -#include "AppConfigUpdater.h" -#include "main.h" -#include "libraries/helpers/DebugHelper.h" - -#define APPCONFIGUPDATER_VERSION "APPCONFIGUPDATER v.1.0 Build 29.10.2010" - - -AppConfigUpdater::AppConfigUpdater(QObject *pobj) : maxParameterCount(100) -{ - Q_UNUSED(pobj); - - conf=NULL; -} - - -AppConfigUpdater::~AppConfigUpdater() -{ - delete conf; -} - - -void AppConfigUpdater::setConfigFile(QString fileName) -{ - // Проверяется, есть ли файл конфигурации - QFile conffile(fileName); - if(!conffile.exists()) - criticalError("appconfigupdater::set_config_file() - File "+fileName+" not found."); - - // Создается рабочий объект для работы с конфигурацией - conf=new QSettings(fileName, QSettings::IniFormat, this); - conf->setPath(QSettings::IniFormat, QSettings::UserScope,"./"); - conf->setPath(QSettings::IniFormat, QSettings::SystemScope,"./"); -} - - -// Обновление значения в случае, -// если значение есть в конфиге, но его представление нужно изменить -QString AppConfigUpdater::updateValueRepresentation(int versionFrom, - int versionTo, - QString name, - QString value) -{ - if(versionFrom==37 and versionTo==38 and name=="dockableWindowsState") - { - if(value.trimmed().size()>1) - { - QStringList chunks=value.split(';'); - - for(int i=0; i > fromTable; - for(int i=0; i line; - line.clear(); - line["type"]=type; - if(conf->contains(name)) - line["value"]=this->updateValueRepresentation(versionFrom, - versionTo, - name, - conf->value(name).toString()); // Значение из конфига - else - line["value"]=defValue; // Дефолтное значение - - // Для текущего имени параметра запоминается массив - fromTable[name]=line; - } - - - // Таблица конечных параметров преобразуется к более удобному для работы виду - // Параллельно создаётся список контролирующий обработанные параметры - // Далее из контролирующего списка будут убираться обработанные параметры - // Контролирующий список нужен для того, чтобы не удалять записи - // из конечного массива во время обхода через итератор - QMap< QString, QMap< QString, QString > > toTable; - QList controlList; - for(int i=0; i line; - line.clear(); - line["type"]=type; - line["value"]=defValue; // Дефолтное значение - - // Для текущего имени параметра запоминается массив - toTable[name]=line; - controlList << name; // Имя заносится в контролирующий список - } - - qDebug() << "From table"; - qDebug() << fromTable; - qDebug() << "To table"; - qDebug() << toTable; - - // Перебирается конечный массив - QMapIterator< QString, QMap< QString, QString > > i(toTable); - while(i.hasNext()) - { - i.next(); - - // Данные для новой версии конфига - QString toName=i.key(); - QMap< QString, QString > line=i.value(); - QString toType=line["type"]; - QString toValue=line["value"]; - - qDebug() << "To name: " << toName; - qDebug() << "To type: " << toType; - qDebug() << "To value: " << toValue; - - // Определяется, есть ли полный аналог параметра в предыдущей версии конфига - int beforeParamFlag=0; - QMap< QString, QString > line2; - QString fromType; - QString fromValue; - if(fromTable.contains(toName)) - { - line2=fromTable[toName]; - fromType=line2["type"]; - fromValue=line2["value"]; - - qDebug() << "Line2: " << line2; - qDebug() << "From type: " << fromType; - qDebug() << "From value: " << fromValue; - - if(toType==fromType) - beforeParamFlag=1; // Параметр есть, и типы совпадают - else - beforeParamFlag=2; // Параметр есть, но типы не совпадают - } - - - // Параметра в предыдущей версии конфига не было - if(beforeParamFlag==0) - { - // Будет просто сохранено новое дефолтное значение - // Ничего с конечным параметром делать не нужно - // Параметр из контролирующего массива исключается - controlList.removeOne(toName); - } - - - // Параметр в предыдущей версии конфига есть, и типы совпадают - if(beforeParamFlag==1) - { - // Будет сохранено предыдущее значение - toTable[toName]["value"]=fromValue; - - // Параметр из контролирующего массива исключается - controlList.removeOne(toName); - } - - - // Параметр в предыдущей версии конфига есть, но типы не совпадают - if(beforeParamFlag==2) - { - // Будет возвращено высчитанное значение - toTable[toName]["value"]=updateVersionAllowCollision(versionFrom,versionTo,toName, - fromType,fromValue, - toType,toValue); - - // Параметр из контролирующего массива исключается - controlList.removeOne(toName); - } - - } // Закрылся перебор конечного массива - - - // Если в контролирующем массиве остались необработанные параметры - if(controlList.size()>0) - { - // Программа завершается - qDebug() << "Can not compute parameter " << controlList; - criticalError("Error while update config from "+(QString::number(versionFrom))+" to "+(QString::number(versionTo)) ); - } - - // Конфиг обнуляется - conf->clear(); - - // Конечный массив записывается в конфиг - QMapIterator< QString, QMap< QString, QString > > j(toTable); - while(j.hasNext()) - { - j.next(); - - QString toName=j.key(); - - QMap< QString, QString > line=j.value(); - QString toType=line["type"]; - QString toValue=line["value"]; - - if(toType=="QString") - conf->setValue(toName,toValue); - else if(toType=="int") - conf->setValue(toName,toValue.toInt()); - else if(toType=="bool") - { - if(toValue=="true") conf->setValue(toName, true); - else conf->setValue(toName, false); - } - } - - // Устанавливается новый номер версии - conf->setValue("version", versionTo); - - // Конфигурация записывается на диск - conf->sync(); -} - diff --git a/app/src/models/appConfig/AppConfigUpdater.h b/app/src/models/appConfig/AppConfigUpdater.h deleted file mode 100644 index ebc5f4aca..000000000 --- a/app/src/models/appConfig/AppConfigUpdater.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef __APPCONFIGUPDATER_H__ -#define __APPCONFIGUPDATER_H__ - -#include -#include -#include -#include - - -#define MYTETRA_CONFIG_PARAM_NUM 100 -#define MYTETRA_CONFIG_PARAM_FIELDS_AT_RECORD 3 - - -class AppConfigUpdater : public QObject -{ - Q_OBJECT - -public: - AppConfigUpdater(QObject *pobj=nullptr); - virtual ~AppConfigUpdater(); - - void setConfigFile(QString fileName); - - void updateVersion(int versionFrom, - int versionTo, - QStringList baseTable, - QStringList finalTable); - -private: - - const int maxParameterCount; - - QString updateValueRepresentation(int versionFrom, - int versionTo, - QString name, - QString value); - - QString updateVersionAllowCollision(int versionFrom, - int versionTo, - QString name, - QString fromType, - QString fromValue, - QString toType, - QString toValue); - - QSettings *conf; - -}; - -#endif /* __APPCONFIGUPDATER_H__ */ - diff --git a/app/src/models/attachTable/Attach.cpp b/app/src/models/attachTable/Attach.cpp index d1a01cb6d..5698bbe12 100644 --- a/app/src/models/attachTable/Attach.cpp +++ b/app/src/models/attachTable/Attach.cpp @@ -360,7 +360,8 @@ bool Attach::copyFileToBase(QString iFileName) qDebug() << "After real copy file."; if(result==false) - showMessageBox(QObject::tr("Can't copy file %1. May be directory %2 not writable, or target file %3 already exists.").arg(iFileName).arg(getFullInnerDirName()).arg(getFullInnerFileName())); + showMessageBox(QObject::tr("Can't copy file %1. May be directory %2 not writable, or target file %3 already exists.") + .arg(iFileName, getFullInnerDirName(), getFullInnerFileName())); return result; } @@ -497,7 +498,7 @@ void Attach::encrypt(unsigned int area) // Если аттач уже зашифрован, значит есть какая-то ошибка в логике выше if(getField("crypt")=="1") - criticalError("Attach::encrypt() : Cant encrypt already encrypted attach."); + criticalError("Attach::encrypt() : Can't encrypt already encrypted attach."); // Шифруется файл @@ -533,7 +534,7 @@ void Attach::decrypt(unsigned int area) { // Если аттач не зашифрован, и происходит расшифровка, значит есть какая-то ошибка в логике выше if(getField("crypt")!="1") - criticalError("Attach::decrypt() : Cant decrypt unencrypted attach."); + criticalError("Attach::decrypt() : Can't decrypt unencrypted attach."); // Расшифровывается файл if(area & areaFile) @@ -567,14 +568,16 @@ void Attach::decrypt(unsigned int area) void Attach::decryptDomElement(QDomElement &iDomElement) { if(iDomElement.hasAttribute("crypt") && iDomElement.attribute("crypt")=="1") - foreach( QString fieldName, fieldCryptedList() ) // Перебираются зашифрованные поля + { + const auto fields = fieldCryptedList(); + for(const auto & fieldName : fields ) // Перебираются зашифрованные поля if(iDomElement.hasAttribute(fieldName) && iDomElement.attribute(fieldName).length()>0) { QString decryptAttribute=CryptService::decryptString( globalParameters.getCryptKey(), iDomElement.attribute(fieldName)); iDomElement.setAttribute(fieldName, decryptAttribute); } - + } iDomElement.setAttribute("crypt", "0"); } diff --git a/app/src/models/attachTable/AttachTableData.h b/app/src/models/attachTable/AttachTableData.h index 832782ec3..ac529537e 100644 --- a/app/src/models/attachTable/AttachTableData.h +++ b/app/src/models/attachTable/AttachTableData.h @@ -6,7 +6,7 @@ #include #include -#include "models/attachTable/Attach.h" +#include "Attach.h" class Record; class AttachTableModel; diff --git a/app/src/models/dataBaseConfig/DataBaseConfig.cpp b/app/src/models/dataBaseConfig/DataBaseConfig.cpp index afaa02a22..9933ca542 100644 --- a/app/src/models/dataBaseConfig/DataBaseConfig.cpp +++ b/app/src/models/dataBaseConfig/DataBaseConfig.cpp @@ -6,7 +6,6 @@ #include "DataBaseConfig.h" #include "models/appConfig/AppConfig.h" -#include "models/appConfig/AppConfigUpdater.h" #include "libraries/GlobalParameters.h" #include "libraries/helpers/DebugHelper.h" diff --git a/app/src/models/databasesManagement/KnownBasesConfig.cpp b/app/src/models/databasesManagement/KnownBasesConfig.cpp index 6b229800c..a680d2490 100644 --- a/app/src/models/databasesManagement/KnownBasesConfig.cpp +++ b/app/src/models/databasesManagement/KnownBasesConfig.cpp @@ -6,7 +6,6 @@ #include "KnownBasesConfig.h" #include "models/appConfig/AppConfig.h" -#include "models/appConfig/AppConfigUpdater.h" #include "libraries/GlobalParameters.h" #include "libraries/helpers/DebugHelper.h" diff --git a/app/src/models/recordTable/Record.cpp b/app/src/models/recordTable/Record.cpp index 87ea745fb..6cfca369b 100644 --- a/app/src/models/recordTable/Record.cpp +++ b/app/src/models/recordTable/Record.cpp @@ -399,7 +399,7 @@ QMap Record::getNaturalFieldList() const AttachTableData Record::getAttachTable() const { if(this->isLite()!=attachTableData.isLite()) - criticalError("getAttachTable(): Unsyncro lite state for record: "+getIdAndNameAsString()); + criticalError("getAttachTable(): Unsynchro lite state for record: "+getIdAndNameAsString()); return attachTableData; } @@ -408,7 +408,7 @@ AttachTableData Record::getAttachTable() const AttachTableData *Record::getAttachTablePointer() { if(this->isLite()!=attachTableData.isLite()) - criticalError("getAttachTable(): Unsyncro lite state for record: "+getIdAndNameAsString()); + criticalError("getAttachTable(): Unsynchro lite state for record: "+getIdAndNameAsString()); return &attachTableData; } @@ -417,7 +417,7 @@ AttachTableData *Record::getAttachTablePointer() void Record::setAttachTable(AttachTableData iAttachTable) { if(this->isLite()!=attachTableData.isLite()) - criticalError("setAttachTable(): Unsyncro lite state for record: "+getIdAndNameAsString()); + criticalError("setAttachTable(): Unsynchro lite state for record: "+getIdAndNameAsString()); attachTableData=iAttachTable; } @@ -429,7 +429,7 @@ QString Record::getText() const { // У легкого объекта невозможно запросить текст из памяти, если так происходит - это ошибка вызывающей логики if(liteFlag==true) - criticalError("Cant get text from lite record object"+getIdAndNameAsString()); + criticalError("Can't get text from lite record object"+getIdAndNameAsString()); // Если запись зашифрована, но ключ не установлен (т.е. человек не вводил пароль) // то расшифровка невозможна @@ -454,7 +454,7 @@ QString Record::getTextDirect() const { // У тяжелого объекта невозможно получить текст записи из файла (у тяжелого объекта текст записи хранится в памяти) if(liteFlag==false) - criticalError("Cant run Record::getTextDirect() for non lite record "+getIdAndNameAsString()); + criticalError("Can't run Record::getTextDirect() for non lite record "+getIdAndNameAsString()); // Если запись зашифрована, но ключ не установлен (т.е. человек не вводил пароль) // то расшифровка невозможна @@ -519,7 +519,7 @@ void Record::setText(const QString &iText) { // Легкому объекту невозможно установить текст, если так происходит - это ошибка вызывающей логики if(liteFlag==true) - criticalError("Cant set text for lite record object"+getIdAndNameAsString()); + criticalError("Can't set text for lite record object"+getIdAndNameAsString()); // Если шифровать не нужно if(fieldList.value("crypt").length()==0 || fieldList.value("crypt")=="0") @@ -544,10 +544,9 @@ void Record::saveTextDirect(QString iText) const QFile wfile(fileName); if(!wfile.open(QIODevice::WriteOnly | QIODevice::Text)) - criticalError("Cant open text file "+fileName+" for write."); + criticalError("Can't open text file "+fileName+" for write."); QTextStream out(&wfile); - out.setCodec("UTF-8"); out << iText; } else if(fieldList.value("crypt")=="1") @@ -559,7 +558,7 @@ void Record::saveTextDirect(QString iText) const QFile wfile(fileName); if(!wfile.open(QIODevice::WriteOnly)) - criticalError("Cant open binary file "+fileName+" for write."); + criticalError("Can't open binary file "+fileName+" for write."); wfile.write(encryptData); } @@ -575,7 +574,7 @@ void Record::saveText() QFile wfile(fileName); if(!wfile.open(QIODevice::WriteOnly)) - criticalError("Record::saveText() : Cant open binary file "+fileName+" for write."); + criticalError("Record::saveText() : Can't open binary file "+fileName+" for write."); // Сохраняется QByteArray с текстом записи (в QByteArray могут быть как зашифрованные, так и не зашифрованные данные) wfile.write(text); @@ -586,7 +585,7 @@ QMap Record::getPictureFiles() const { // У легкого объекта невозможно запросить картинки, если так происходит - это ошибка вызывающей логики if(liteFlag==true) - criticalError("Cant get picture files from lite record object"+getIdAndNameAsString()); + criticalError("Can't get picture files from lite record object"+getIdAndNameAsString()); return pictureFiles; } @@ -597,7 +596,7 @@ void Record::setPictureFiles(QMap iPictureFiles) { // Легкому объекту невозможно установить картики, если так происходит - это ошибка вызывающей логики if(liteFlag==true) - criticalError("Cant set picture files for lite record object"+getIdAndNameAsString()); + criticalError("Can't set picture files for lite record object"+getIdAndNameAsString()); pictureFiles=iPictureFiles; } @@ -656,11 +655,11 @@ void Record::switchToEncryptAndSaveLite(void) { // Метод обрабатывает только легкий объект if(liteFlag==false) - criticalError("Cant call switchToEncryptAndSaveLite() for non lite record object "+getIdAndNameAsString()); + criticalError("Can't call switchToEncryptAndSaveLite() for non lite record object "+getIdAndNameAsString()); // Нельзя шифровать уже зашифрованную запись if(fieldList.value("crypt")=="1") - criticalError("Cant call switchToEncryptAndSaveLite() for crypt record object "+getIdAndNameAsString()); + criticalError("Can't call switchToEncryptAndSaveLite() for crypt record object "+getIdAndNameAsString()); // В легком объекте данные не из полей находятся в файлах @@ -683,11 +682,11 @@ void Record::switchToEncryptAndSaveFat(void) { // Метод обрабатывает только тяжелый объект if(liteFlag==true) - criticalError("Cant call switchToEncryptFat() for non fat record object "+getIdAndNameAsString()); + criticalError("Can't call switchToEncryptFat() for non fat record object "+getIdAndNameAsString()); // Нельзя шифровать уже зашифрованную запись if(fieldList.value("crypt")=="1") - criticalError("Cant call switchToEncryptAndSaveFat() for crypt record object "+getIdAndNameAsString()); + criticalError("Can't call switchToEncryptAndSaveFat() for crypt record object "+getIdAndNameAsString()); // Зашифровывается текст записи в памяти text=CryptService::encryptByteArray(globalParameters.getCryptKey(), text); @@ -708,11 +707,11 @@ void Record::switchToDecryptAndSaveLite(void) { // Метод обрабатывает только легкий объект if(liteFlag==false) - criticalError("Cant call switchToDecryptAndSaveLite() for non lite record object "+getIdAndNameAsString()); + criticalError("Can't call switchToDecryptAndSaveLite() for non lite record object "+getIdAndNameAsString()); // Нельзя расшифровать не зашифрованную запись if(fieldList.value("crypt")!="1") - criticalError("Cant call switchToDecryptAndSaveLite() for non crypt record object "+getIdAndNameAsString()); + criticalError("Can't call switchToDecryptAndSaveLite() for non crypt record object "+getIdAndNameAsString()); // Расшифровка файла с текстом записи на диске QString dirName; @@ -735,11 +734,11 @@ void Record::switchToDecryptAndSaveFat(void) { // Метод обрабатывает только тяжелый объект if(liteFlag==true) - criticalError("Cant call switchToDecryptAndSaveFat() for non fat record object "+getIdAndNameAsString()); + criticalError("Can't call switchToDecryptAndSaveFat() for non fat record object "+getIdAndNameAsString()); // Нельзя расшифровать не зашифрованную запись if(fieldList.value("crypt")!="1") - criticalError("Cant call switchToDecryptAndSaveFat() for non crypt record object "+getIdAndNameAsString()); + criticalError("Can't call switchToDecryptAndSaveFat() for non crypt record object "+getIdAndNameAsString()); // Расшифровывается текст записи в памяти text=CryptService::decryptByteArray(globalParameters.getCryptKey(), text); @@ -761,7 +760,7 @@ void Record::pushFatAttributes() { // Легкий объект невозможно сбросить на диск, потому что он не содержит данных, сбрасываемых в файлы if(liteFlag==true) - criticalError("Cant push lite record object"+getIdAndNameAsString()); + criticalError("Can't push lite record object"+getIdAndNameAsString()); // Если запись зашифрована, но ключ не установлен (т.е. человек не вводил пароль) // то зашифровать текст невозможно @@ -807,18 +806,13 @@ void Record::replaceInternalReferenceByTranslateTable(QString recordFileName, QM // Подготавливается регулярное выражение - QRegExp rx("href=\""+FixedParameters::appTextId+":\\/\\/note/(.*)\""); - rx.setMinimal(true); // Регулярка делается ленивой (ленивые квантификаторы в строке регвыра в Qt не поддерживаются) + QRegularExpression rx("href=\""+FixedParameters::appTextId+":\\/\\/note/(.*)\"", QRegularExpression::InvertedGreedinessOption); // Заполняется список идентификаторов, встречающихся во внутренних ссылках QStringList internalIdList; - int pos = 0; - while ((pos = rx.indexIn(lines, pos))!=-1) - { - internalIdList << rx.cap(1); - pos += rx.matchedLength(); - } - + auto m = rx.globalMatch(lines); + while (m.hasNext()) + internalIdList << m.next().captured(1); // Перебираются найденные внутри mytetra-ссылок идентификаторы bool isIdReplace=false; diff --git a/app/src/models/recordTable/Record.h b/app/src/models/recordTable/Record.h index 5dd85093b..7c441df02 100644 --- a/app/src/models/recordTable/Record.h +++ b/app/src/models/recordTable/Record.h @@ -11,8 +11,8 @@ #include #include -#include "models/attachTable/Attach.h" -#include "models/attachTable/AttachTableData.h" +#include "../attachTable/Attach.h" +#include "../attachTable/AttachTableData.h" // Класс одной записи в таблице записей diff --git a/app/src/models/recordTable/RecordTableData.cpp b/app/src/models/recordTable/RecordTableData.cpp index 386db20f3..beb14b5f2 100644 --- a/app/src/models/recordTable/RecordTableData.cpp +++ b/app/src/models/recordTable/RecordTableData.cpp @@ -176,10 +176,9 @@ void RecordTableData::editorSaveCallback(QObject *editor, QFile wfile(fileName); if(!wfile.open(QIODevice::WriteOnly | QIODevice::Text)) - criticalError("RecordTableData::editor_save_callback() : Cant open text file "+fileName+" for write."); + criticalError("RecordTableData::editor_save_callback() : Can't open text file "+fileName+" for write."); QTextStream out(&wfile); - out.setCodec("UTF-8"); out << saveText; } else @@ -191,7 +190,7 @@ void RecordTableData::editorSaveCallback(QObject *editor, QFile wfile(fileName); if(!wfile.open(QIODevice::WriteOnly)) - criticalError("RecordTableData::editor_save_callback() : Cant open binary file "+fileName+" for write."); + criticalError("RecordTableData::editor_save_callback() : Can't open binary file "+fileName+" for write."); wfile.write(encryptData); } @@ -285,7 +284,7 @@ QSet RecordTableData::getRecordsIdList() { QSet ids; - for( auto record : tableData) + for( const auto & record : std::as_const(tableData)) { ids << record.getField("id"); } @@ -480,8 +479,9 @@ int RecordTableData::insertNewRecord(int mode, data["recordName"]=record.getNaturalFieldSource("name"); if(treeItem!=nullptr) { - data["branchId"]=treeItem->getAllFieldsDirect()["id"]; - data["branchName"]=treeItem->getAllFieldsDirect()["name"]; + auto fields=treeItem->getAllFieldsDirect(); + data["branchId"]=fields["id"]; + data["branchName"]=fields["name"]; } if(!isCrypt) actionLogger.addAction("createRecord", data); diff --git a/app/src/models/recordTable/RecordTableModel.cpp b/app/src/models/recordTable/RecordTableModel.cpp index b9a940520..b2dff49a8 100644 --- a/app/src/models/recordTable/RecordTableModel.cpp +++ b/app/src/models/recordTable/RecordTableModel.cpp @@ -64,10 +64,8 @@ QVariant RecordTableModel::data(const QModelIndex &index, int role) const { // Преобразование временного штампа в дату и время QDateTime fieldDateTime=QDateTime::fromString(field, "yyyyMMddhhmmss"); - if(mytetraConfig.getEnableCustomDateTimeFormat()==false) - return fieldDateTime.toString(Qt::SystemLocaleDate); - else - return fieldDateTime.toString( mytetraConfig.getCustomDateTimeFormat() ); + auto fmt = mytetraConfig.getEnableCustomDateTimeFormat() ? mytetraConfig.getCustomDateTimeFormat() : QLocale::system().dateTimeFormat(QLocale::ShortFormat); + QLocale::system().toString(fieldDateTime, fmt); } else if( role==Qt::DisplayRole && fieldName=="hasAttach") // Наличие аттачей @@ -81,7 +79,7 @@ QVariant RecordTableModel::data(const QModelIndex &index, int role) const else if( role==Qt::DisplayRole && fieldName=="attachCount") // Количество аттачей { if(field=="0") - return ""; // Если количество аттачей нуливое, выводится пустая строка. Это повышает читабельность + return ""; // Если количество аттачей нулевое, выводится пустая строка. Это повышает читабельность else return field; } diff --git a/app/src/models/shortcutSettings/ShortcutSettingsModel.cpp b/app/src/models/shortcutSettings/ShortcutSettingsModel.cpp index eaaed8fcc..b08c0d437 100644 --- a/app/src/models/shortcutSettings/ShortcutSettingsModel.cpp +++ b/app/src/models/shortcutSettings/ShortcutSettingsModel.cpp @@ -19,7 +19,7 @@ ShortcutSettingsModel::ShortcutSettingsModel(QObject *parent) : QStandardItemMod // Создание строк с шорткатами this->insertRows(0, copyShortcutManager.getActionsNameList(sectionName).size(), sectionIndex); - this->insertColumns(0, this->columnCount(), sectionIndex); + this->insertColumns(0, ShortcutSettingsModel::columnCount(), sectionIndex); // Заполнение строк с шорткатами int j=0; @@ -181,7 +181,7 @@ bool ShortcutSettingsModel::smartUpdate(updateMode mode) // Проверка, допустимо ли повторение сочетания if( !copyShortcutManager.isOverloadEnable(sectionNameA, sectionNameB) ) { - duplicateError=tr("Found duplicate key sequense %3 for action %1 and %2").arg(altrnateFullCommandName).arg(fullCommandName).arg(keysName); + duplicateError=tr("Found duplicate key sequense %3 for action %1 and %2").arg(altrnateFullCommandName, fullCommandName, keysName); return false; } } diff --git a/app/src/models/tree/KnowTreeModel.cpp b/app/src/models/tree/KnowTreeModel.cpp index b0feef2df..2ef4627ea 100644 --- a/app/src/models/tree/KnowTreeModel.cpp +++ b/app/src/models/tree/KnowTreeModel.cpp @@ -22,7 +22,6 @@ #include "libraries/helpers/ObjectHelper.h" #include "libraries/helpers/MessageHelper.h" #include "libraries/helpers/UniqueIdHelper.h" -#include "libraries/helpers/SortHelper.h" #include "libraries/wyedit/EditorShowTextDispatcher.h" @@ -217,11 +216,12 @@ QDomElement KnowTreeModel::exportFullModelDataToDom(TreeItem *root) QDomDocument doc; QDomElement elm=doc.createElement("content"); - QTime start = QTime::currentTime(); + QElapsedTimer timer; + timer.start(); parseTreeToDom(&doc, &elm, root); - qDebug() << "Parse tree to DOM elapsed time: " << start.elapsed() << " ms"; + qDebug() << "Parse tree to DOM elapsed time: " << timer.elapsed() << " ms"; // qDebug() << "In export_fullmodeldata_to_dom stop element " << xmlNodeToString(elm); @@ -295,7 +295,6 @@ bool KnowTreeModel::exportBranchToDirectory(TreeItem *startItem, QString exportD return false; } QTextStream out(&wfile); - out.setCodec("UTF-8"); out << doc.toString(); @@ -353,7 +352,7 @@ void KnowTreeModel::exportRelatedDataAndDecryptIfNeedRecurse(QDomElement &elemen // Создание директории if( !QDir().mkpath(toDir) ) - criticalError("Cant create directory "+toDir); + criticalError("Can't create directory "+toDir); // Копирование всех файлов из директории записи в директорию экспортируемой записи DiskHelper::copyDirectory(fromDir, toDir); @@ -478,7 +477,6 @@ bool KnowTreeModel::copyImportRecordDirectories( QDomDocument &doc, QMap idRecordTranslate, QMap dirRecordTranslate ) { - QMap translateTable; QDomNodeList nodeList=doc.elementsByTagName("record"); for(int i=0; i branch // Обязательно должны быть установлены поля id и name if(!branchFields.contains("id")) - criticalError("In KnowTreeModel::addNewBranch() cant setted ID field"); + criticalError("In KnowTreeModel::addNewBranch() can't setted ID field"); if(!branchFields.contains("name")) - criticalError("In KnowTreeModel::addNewBranch() cant setted name field"); + criticalError("In KnowTreeModel::addNewBranch() can't setted name field"); // Перебираются поля новой ветки и их значения foreach(QString fieldName, branchFields.keys()) @@ -1130,11 +1127,7 @@ void KnowTreeModel::deleteItemsByModelIndexList(QModelIndexList &selectItems) QStringList path_1=(this->getItem(selectItems.at(j-1)))->getPath(); QStringList path_2=(this->getItem(selectItems.at(j)))->getPath(); if(path_1.size() < path_2.size()) - #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) selectItems.swapItemsAt(j-1, j); - #else - selectItems.swap(j-1, j); - #endif } qDebug() << "Path for delete"; @@ -1177,7 +1170,7 @@ void KnowTreeModel::deleteOneBranch(QModelIndex index) QList subbranchespath=item->getAllChildrenPath(); // Сортировка массива веток по длине пути - std::sort(subbranchespath.begin(), subbranchespath.end(), compareQStringListLen); + std::sort(subbranchespath.begin(), subbranchespath.end(), [](const auto & a, const auto & b){return a.size() < b.size();}); // Удаление всех таблиц конечных записей для нужных подветок // Удаление всех подчиненных элементов для нужных подветок diff --git a/app/src/models/tree/TreeItem.cpp b/app/src/models/tree/TreeItem.cpp index 25a1c8175..05620b452 100644 --- a/app/src/models/tree/TreeItem.cpp +++ b/app/src/models/tree/TreeItem.cpp @@ -390,11 +390,7 @@ bool TreeItem::moveUp(void) if(num==0)return false; // Элемент перемещается вверх по списку - #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) ( parentItem->childItems ).swapItemsAt(num,num-1); - #else - ( parentItem->childItems ).swap(num,num-1); - #endif return true; } @@ -410,11 +406,7 @@ bool TreeItem::moveDn(void) return false; // Элемент перемещается вниз по списку - #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) ( parentItem->childItems ).swapItemsAt(num,num+1); - #else - ( parentItem->childItems ).swap(num,num+1); - #endif return true; } diff --git a/app/src/models/tree/XmlTree.cpp b/app/src/models/tree/XmlTree.cpp index 4017939fb..8c548eec5 100644 --- a/app/src/models/tree/XmlTree.cpp +++ b/app/src/models/tree/XmlTree.cpp @@ -1,6 +1,5 @@ #include #include -#include #include "XmlTree.h" #include "main.h" @@ -25,10 +24,7 @@ bool XmlTree::load(QString file) // Если файл не может быть открыт if(!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - QMessageBox::information(0, tr("Error"), - tr("Cannot read file %1:\n%2.") - .arg(file) - .arg(xmlFile.errorString())); + QMessageBox::information(0, tr("Error"), tr("Cannot read file %1:\n%2.").arg(file, xmlFile.errorString())); return false; } diff --git a/app/src/views/actionLog/ActionLogScreen.cpp b/app/src/views/actionLog/ActionLogScreen.cpp index c22901367..b3f037710 100644 --- a/app/src/views/actionLog/ActionLogScreen.cpp +++ b/app/src/views/actionLog/ActionLogScreen.cpp @@ -64,7 +64,7 @@ void ActionLogScreen::setupActions(void) void ActionLogScreen::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); shortcutManager.initAction("actionLog-copy", actionCopy ); } diff --git a/app/src/views/actionLog/ActionLogView.cpp b/app/src/views/actionLog/ActionLogView.cpp index 36af2f4a1..dddbd4664 100644 --- a/app/src/views/actionLog/ActionLogView.cpp +++ b/app/src/views/actionLog/ActionLogView.cpp @@ -63,8 +63,8 @@ void ActionLogView::setupSignals(void) // Соединение сигнал-слот чтобы показать контекстное меню по долгому нажатию // (пока долгое нажатие не обрабатывается и сигнал не эмитируется) - connect(this, SIGNAL(tapAndHoldGestureFinished(const QPoint &)), - this, SLOT(onCustomContextMenuRequested(const QPoint &))); + connect(this, &ActionLogView::tapAndHoldGestureFinished, + this, &ActionLogView::onCustomContextMenuRequested); } diff --git a/app/src/views/appConfigWindow/AppConfigDialog.cpp b/app/src/views/appConfigWindow/AppConfigDialog.cpp index 0801b5639..5cc23f893 100644 --- a/app/src/views/appConfigWindow/AppConfigDialog.cpp +++ b/app/src/views/appConfigWindow/AppConfigDialog.cpp @@ -101,7 +101,7 @@ void AppConfigDialog::changePage(QString name) if(item!=nullptr) configDialog->externalChangePage(item); else - qDebug() << "AppConfigDialog::changePage cant find item for name: " << name; + qDebug() << "AppConfigDialog::changePage can't find item for name: " << name; } diff --git a/app/src/views/appConfigWindow/AppConfigPage_Appearance.cpp b/app/src/views/appConfigWindow/AppConfigPage_Appearance.cpp index c36113613..78150e23d 100644 --- a/app/src/views/appConfigWindow/AppConfigPage_Appearance.cpp +++ b/app/src/views/appConfigWindow/AppConfigPage_Appearance.cpp @@ -35,7 +35,7 @@ void AppConfigPage_Appearance::setupUi() runInMinimizedWindow->setChecked( mytetraConfig.get_runinminimizedwindow() ); - // Настройка поведения открепляемых окон, как они будут сворачиваться и разворачитьваться + // Настройка поведения открепляемых окон, как они будут сворачиваться и разворачиваться dockableWindowsBehavior=new QCheckBox(this); dockableWindowsBehavior->setText(tr("Hide detached windows if close main window")); dockableWindowsBehavior->setChecked( mytetraConfig.getDockableWindowsBehavior()=="together" ); diff --git a/app/src/views/appConfigWindow/AppConfigPage_Appearance.h b/app/src/views/appConfigWindow/AppConfigPage_Appearance.h index b17d2db4e..ba7f29c79 100644 --- a/app/src/views/appConfigWindow/AppConfigPage_Appearance.h +++ b/app/src/views/appConfigWindow/AppConfigPage_Appearance.h @@ -10,6 +10,8 @@ class AppConfigPage_Appearance : public ConfigPage { + Q_OBJECT + public: AppConfigPage_Appearance(QWidget *parent = nullptr); virtual ~AppConfigPage_Appearance(); diff --git a/app/src/views/appConfigWindow/AppConfigPage_History.h b/app/src/views/appConfigWindow/AppConfigPage_History.h index 86be047a7..3b29ad0b8 100644 --- a/app/src/views/appConfigWindow/AppConfigPage_History.h +++ b/app/src/views/appConfigWindow/AppConfigPage_History.h @@ -10,6 +10,7 @@ class AppConfigPage_History : public ConfigPage { + Q_OBJECT public: AppConfigPage_History(QWidget *parent = nullptr); virtual ~AppConfigPage_History(); diff --git a/app/src/views/appConfigWindow/AppConfigPage_Main.cpp b/app/src/views/appConfigWindow/AppConfigPage_Main.cpp index 5093c5f2a..dd7e93dee 100644 --- a/app/src/views/appConfigWindow/AppConfigPage_Main.cpp +++ b/app/src/views/appConfigWindow/AppConfigPage_Main.cpp @@ -84,6 +84,8 @@ void AppConfigPage_Main::setupUi(void) interfaceLanguage->setMinimumContentsLength(2); interfaceLanguage->addItem("en"); interfaceLanguage->setItemIcon(interfaceLanguage->count()-1, QIcon(":/resource/pic/countryFlags/United-Kingdom.png")); + interfaceLanguage->addItem("fr"); + interfaceLanguage->setItemIcon(interfaceLanguage->count()-1, QIcon(":/resource/pic/countryFlags/France.png")); interfaceLanguage->addItem("ru"); interfaceLanguage->setItemIcon(interfaceLanguage->count()-1, QIcon(":/resource/pic/countryFlags/Russia.png")); interfaceLanguage->setCurrentIndex(interfaceLanguage->findText(mytetraConfig.get_interfacelanguage(), Qt::MatchCaseSensitive)); diff --git a/app/src/views/appConfigWindow/AppConfigPage_Synchro.cpp b/app/src/views/appConfigWindow/AppConfigPage_Synchro.cpp index 860ca1e3e..8e7399b73 100644 --- a/app/src/views/appConfigWindow/AppConfigPage_Synchro.cpp +++ b/app/src/views/appConfigWindow/AppConfigPage_Synchro.cpp @@ -6,12 +6,12 @@ #include "AppConfigPage_Synchro.h" #include "models/appConfig/AppConfig.h" #include "libraries/PeriodicCheckBase.h" -#include "libraries/PeriodicSyncro.h" +#include "libraries/PeriodicSynchro.h" #include "libraries/helpers/MessageHelper.h" extern AppConfig mytetraConfig; extern PeriodicCheckBase periodicCheckBase; -extern PeriodicSyncro periodicSyncro; +extern PeriodicSynchro periodicSynchro; AppConfigPage_Synchro::AppConfigPage_Synchro(QWidget *parent) : ConfigPage(parent) @@ -40,7 +40,7 @@ void AppConfigPage_Synchro::setupUi(void) synchroOnPeriodic=new QCheckBox(this); synchroOnPeriodic->setText(tr("Enable periodic background synchronize")); - synchroOnPeriodic->setChecked(mytetraConfig.getEnablePeriodicSyncro()); + synchroOnPeriodic->setChecked(mytetraConfig.getEnablePeriodicSynchro()); // Область ввода команды синхронизации commandText=new QLabel(this); @@ -65,7 +65,7 @@ void AppConfigPage_Synchro::setupUi(void) synchroPeriod=new QSpinBox(this); synchroPeriod->setMaximum( 100000 ); // Максимальная граница должна устанавливаться перед заданием значения - synchroPeriod->setValue( mytetraConfig.getPeriodicSyncroPeriod() ); + synchroPeriod->setValue( mytetraConfig.getPeriodicSynchroPeriod() ); synchroPeriodPostfix=new QLabel(this); synchroPeriodPostfix->setText( tr("sec.") ); @@ -80,7 +80,7 @@ void AppConfigPage_Synchro::setupUi(void) synchroOnBox->setLayout( synchroOnLayout ); // Начальное состояние зависимых параметров (активны-неактивны) для периодической синхронизации - onEnablePeriodicSyncro( mytetraConfig.getEnablePeriodicSyncro() ); + onEnablePeriodicSynchro( mytetraConfig.getEnablePeriodicSynchro() ); // Виджеты настройки периодической проверки базы на предмет изменений @@ -141,7 +141,7 @@ void AppConfigPage_Synchro::assembly(void) void AppConfigPage_Synchro::setupSignals(void) { connect( enablePeriodicCheckBase, &QCheckBox::toggled, this, &AppConfigPage_Synchro::onEnablePeriodicCheckBase); - connect( synchroOnPeriodic, &QCheckBox::toggled, this, &AppConfigPage_Synchro::onEnablePeriodicSyncro); + connect( synchroOnPeriodic, &QCheckBox::toggled, this, &AppConfigPage_Synchro::onEnablePeriodicSynchro); } @@ -155,7 +155,7 @@ void AppConfigPage_Synchro::onEnablePeriodicCheckBase(bool state) } -void AppConfigPage_Synchro::onEnablePeriodicSyncro(bool state) +void AppConfigPage_Synchro::onEnablePeriodicSynchro(bool state) { synchroPeriodText->setEnabled(state); synchroPeriod->setEnabled(state); @@ -185,26 +185,26 @@ int AppConfigPage_Synchro::applyChanges(void) // Сохраняется период синхронизации // установка периода должна производиться перед обработкой галки включения/выключения - if(mytetraConfig.getPeriodicSyncroPeriod()!=synchroPeriod->value()) + if(mytetraConfig.getPeriodicSynchroPeriod()!=synchroPeriod->value()) { - mytetraConfig.setPeriodicSyncroPeriod( synchroPeriod->value() ); + mytetraConfig.setPeriodicSynchroPeriod( synchroPeriod->value() ); - periodicSyncro.setDelay( synchroPeriod->value() ); + periodicSynchro.setDelay( synchroPeriod->value() ); } // Сохраняется настройка париодического запуска синхронизации - if(mytetraConfig.getEnablePeriodicSyncro()!=synchroOnPeriodic->isChecked()) + if(mytetraConfig.getEnablePeriodicSynchro()!=synchroOnPeriodic->isChecked()) { - mytetraConfig.setEnablePeriodicSyncro(synchroOnPeriodic->isChecked()); + mytetraConfig.setEnablePeriodicSynchro(synchroOnPeriodic->isChecked()); - if( mytetraConfig.getEnablePeriodicSyncro() ) + if( mytetraConfig.getEnablePeriodicSynchro() ) { showMessageBox(tr("The first background synchronizing starting.
Maybe a slight delay or freezing window...")); - periodicSyncro.start(); + periodicSynchro.start(); } else - periodicSyncro.stop(); + periodicSynchro.stop(); } diff --git a/app/src/views/appConfigWindow/AppConfigPage_Synchro.h b/app/src/views/appConfigWindow/AppConfigPage_Synchro.h index e6c4d1137..0a71e2ced 100644 --- a/app/src/views/appConfigWindow/AppConfigPage_Synchro.h +++ b/app/src/views/appConfigWindow/AppConfigPage_Synchro.h @@ -24,7 +24,7 @@ class AppConfigPage_Synchro : public ConfigPage private slots: void onEnablePeriodicCheckBase(bool); - void onEnablePeriodicSyncro(bool); + void onEnablePeriodicSynchro(bool); protected: diff --git a/app/src/views/attachTable/AttachTableScreen.cpp b/app/src/views/attachTable/AttachTableScreen.cpp index 8a54e266a..cc39445fb 100644 --- a/app/src/views/attachTable/AttachTableScreen.cpp +++ b/app/src/views/attachTable/AttachTableScreen.cpp @@ -80,7 +80,7 @@ void AttachTableScreen::setupActions(void) void AttachTableScreen::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); shortcutManager.initAction("attach-addAttach", actionAddAttach ); shortcutManager.initAction("attach-addAttachFromUrl", actionAddAttachFromUrl ); diff --git a/app/src/views/consoleEmulator/CommandRun.cpp b/app/src/views/consoleEmulator/CommandRun.cpp index b08736cb2..62a7aeacd 100644 --- a/app/src/views/consoleEmulator/CommandRun.cpp +++ b/app/src/views/consoleEmulator/CommandRun.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include #include "CommandRun.h" @@ -20,30 +19,6 @@ extern GlobalParameters globalParameters; CommandRun::CommandRun(QObject *parent) : QObject(parent) { - QString os=getOsFamily(); - - // Определение командной оболочки, которую надо использовать - m_shell=""; - if(os=="unix") - { - if(system("sh -c exit")==0) - m_shell="sh -c"; - else if(system("bash -c exit")==0) - m_shell="bash -c"; - } - else if(os=="windows") - { - m_shell="cmd.exe /C"; - } - - if(m_shell.length()==0) - { - criticalError("Can't detect sh, bash or cmd shell."); - } - - - // Определяется кодек для вывода текста терминального потока - m_outputCodec = QTextCodec::codecForName(globalParameters.getConsoleCodepage().toLatin1()); } @@ -63,24 +38,15 @@ CommandRun::~CommandRun() } } - -QString CommandRun::getOsFamily() -{ - QString os="unix"; - - #if defined(Q_WS_WIN) || defined(Q_OS_WIN32) || defined(Q_OS_WINCE) || defined(Q_OS_MSDOS) || defined(Q_OS_CYGWIN) - os="windows"; - #endif - - return os; -} - - void CommandRun::setCommand(QString cmd) { m_command=cmd; } +void CommandRun::setArgs(QStringList args) +{ + m_args=args; +} void CommandRun::setWindowTitle(QString title) { @@ -126,10 +92,9 @@ void CommandRun::createProcessAndConsole() m_console->setWindowTitle(m_windowTitle); m_console->setMessageText(m_messageText); - m_console->setConsoleOutput( this->getCommandForProcessExecute()+"\n" ); + m_console->setConsoleOutput( m_command + " " + m_args.join(' ') + "\n" ); - qDebug() << "Run shell" << m_shell; - qDebug() << "Run command" << m_command; + qDebug() << "Run command" << m_command << " " << m_args; } @@ -170,37 +135,24 @@ void CommandRun::removeProcessAndConsole(void) } -// Команда, которая должна запускаться в процессе -QString CommandRun::getCommandForProcessExecute() -{ - return m_shell+" \""+m_command+"\""; -} - - // Простой запуск консольных команд на исполнение с ожиданием завершения, // Метод возвращет код возврата выполняемой команды. -// Консоль не создается, команду просто выполняется в процессе +// Консоль не создается, команда просто выполняется в процессе int CommandRun::runSimple() { - // Если командный интерпретатор не установлен - if(m_shell.length()==0) - criticalError("ExecuteCommand::run() : Not detect available shell"); - // Создается процесс QProcess simpleProcess; + qDebug() << "Run command" << m_command << " " << m_args; + // Запускается команда на исполнение - return simpleProcess.execute( this->getCommandForProcessExecute() ); + return simpleProcess.execute(m_command, m_args ); } // Запуск процесса выполнения команды void CommandRun::run(bool visible) { - // Если командный интерпретатор не установлен - if(m_shell.length()==0) - criticalError("ExecuteCommand::run() : Not detect available shell"); - m_isError=false; // Создается процесс и консоль к нему @@ -228,19 +180,19 @@ void CommandRun::run(bool visible) // Отслеживание завершения запущенного процесса // (Сигнал finished перегружен, поэтому новый синтаксис надо писать в виде замыкания) - connect(m_process, QOverload::of(&QProcess::finished), + connect(m_process, &QProcess::finished, this, [=](int exitCode, QProcess::ExitStatus exitStatus){ this->onProcessFinish(exitCode, exitStatus); } ); // Запускается команда на исполнение внутри процесса - m_process->start( this->getCommandForProcessExecute() ); + m_process->start( m_command, m_args ); } // Слот, срабатывающий когда пользователь нажал Cancel в эмуляторе консоли void CommandRun::onManualCloseProcess(void) { - qDebug() << "Manual close process, PID" << m_process->pid(); + qDebug() << "Manual close process, PID" << m_process->processId(); this->removeProcessAndConsole(); } @@ -283,7 +235,8 @@ void CommandRun::onProcessError(QProcess::ProcessError error) QMap data; data["errCode"]=QString::number(error); - actionLogger.addAction("syncroProcessError", data); + actionLogger.addAction("synchroProcessError", data); + m_console->switchToErrorView(); m_isError=true; } @@ -297,9 +250,7 @@ void CommandRun::printOutput() const return; } - // Преобразование в QString, необходимо чтобы исключать строки с нулями - QString output=m_outputCodec->toUnicode( m_process->readAllStandardOutput() ); - + auto output = m_process->readAllStandardOutput(); if(output.length()>0) { m_console->addConsoleOutput(output); diff --git a/app/src/views/consoleEmulator/CommandRun.h b/app/src/views/consoleEmulator/CommandRun.h index 2bcf7ce65..b6a46d850 100644 --- a/app/src/views/consoleEmulator/CommandRun.h +++ b/app/src/views/consoleEmulator/CommandRun.h @@ -17,9 +17,8 @@ class CommandRun : public QObject CommandRun(QObject *parent=nullptr); virtual ~CommandRun(); - static QString getOsFamily(); - void setCommand(QString cmd); + void setArgs(QStringList args); void run(bool visible=true); int runSimple(); @@ -42,7 +41,6 @@ private slots: private: - QString getCommandForProcessExecute(); void printOutput() const; void createProcessAndConsole(void); @@ -50,12 +48,11 @@ private slots: QString m_command; - QString m_shell; + QStringList m_args; QString m_windowTitle; QString m_messageText; QProcess *m_process=nullptr; - QTextCodec *m_outputCodec=nullptr; ConsoleEmulator *m_console=nullptr; diff --git a/app/src/views/consoleEmulator/ConsoleEmulator.cpp b/app/src/views/consoleEmulator/ConsoleEmulator.cpp index dfa6adb58..491f9d7f5 100644 --- a/app/src/views/consoleEmulator/ConsoleEmulator.cpp +++ b/app/src/views/consoleEmulator/ConsoleEmulator.cpp @@ -40,7 +40,7 @@ void ConsoleEmulator::setupUI(void) consoleOutput=new QTextEdit(this); consoleOutput->setReadOnly(true); consoleOutput->setFontFamily("monospace"); - if(mytetraConfig.getSyncroConsoleDetails()==false) + if(mytetraConfig.getSynchroConsoleDetails()==false) consoleOutput->hide(); waitClock=new WaitClock(this); @@ -149,12 +149,12 @@ void ConsoleEmulator::onDetailsClick(void) if(consoleOutput->isHidden()) { consoleOutput->show(); - mytetraConfig.setSyncroConsoleDetails(true); + mytetraConfig.setSynchroConsoleDetails(true); } else { consoleOutput->hide(); - mytetraConfig.setSyncroConsoleDetails(false); + mytetraConfig.setSynchroConsoleDetails(false); } this->adjustSize(); @@ -167,12 +167,7 @@ void ConsoleEmulator::switchToErrorView(void) isErrorMode=true; - actionLogger.addAction("syncroError"); - - // Верхняя строка скрывается - // QLayoutItem *child; - // while ((child = upToolbar->takeAt(0)) != 0) - // child->widget()->hide(); + actionLogger.addAction("synchroError"); // Сообщение об обнаруженной ошибке messageLabel->setText(""+tr("Commands running error")+""); diff --git a/app/src/views/findInBaseScreen/FindTableWidget.cpp b/app/src/views/findInBaseScreen/FindTableWidget.cpp index ba666fdd4..fcb3d6fec 100644 --- a/app/src/views/findInBaseScreen/FindTableWidget.cpp +++ b/app/src/views/findInBaseScreen/FindTableWidget.cpp @@ -152,7 +152,6 @@ void FindTableWidget::addRow(QString title, QString branchName, QString tags, QS // Информация о записи QStandardItem *item_info=new QStandardItem(); - QString info; tags=tags.trimmed(); if(tags.length()>0) item_info->setText(branchName+" ("+tags+")"); diff --git a/app/src/views/installDialog/InstallDialog.cpp b/app/src/views/installDialog/InstallDialog.cpp index 69cc03f8f..7e527262f 100644 --- a/app/src/views/installDialog/InstallDialog.cpp +++ b/app/src/views/installDialog/InstallDialog.cpp @@ -20,7 +20,7 @@ InstallDialog::InstallDialog(QWidget *parent) : this->setupSignals(); - ui->m_title->setText( tr("Welcome to MyTetra v.")+QString::number(APPLICATION_RELEASE_VERSION)+'.'+QString::number(APPLICATION_RELEASE_SUBVERSION)+'.'+QString::number(APPLICATION_RELEASE_MICROVERSION)+"!" ); + ui->m_title->setText( tr("Welcome to MyTetra ")+APPLICATION_VERSION+"!" ); ui->m_text->setText( tr("Please select a knowledge base installation mode:") ); } @@ -101,8 +101,7 @@ void InstallDialog::setPortableData(QString fullCurrentPath) void InstallDialog::update() { ui->m_labelStandart->setText( tr("Create subdirectory \"%1\"\nin user directory \"%2\",\nand create application files in it."). - arg(m_standartDataDirName). - arg(m_standartHomePath) ); + arg(m_standartDataDirName, m_standartHomePath) ); if(m_enablePortable) { diff --git a/app/src/views/mainWindow/MainWindow.cpp b/app/src/views/mainWindow/MainWindow.cpp index 3305806d3..37ad0a597 100644 --- a/app/src/views/mainWindow/MainWindow.cpp +++ b/app/src/views/mainWindow/MainWindow.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include "main.h" #include "models/appConfig/AppConfig.h" @@ -23,7 +22,6 @@ #include "views/actionLog/ActionLogScreen.h" #include "views/databasesManagement/DatabasesManagementScreen.h" #include "libraries/ShortcutManager.h" -#include "libraries/RandomInitter.h" #include "libraries/helpers/ObjectHelper.h" #include "libraries/wyedit/EditorTextArea.h" #include "libraries/wyedit/EditorShowTextDispatcher.h" @@ -68,10 +66,7 @@ MainWindow::MainWindow() : QMainWindow() // Закрывать ли по-настоящему окно при обнаружении сигнала closeEvent enableRealClose=false; - // Инициализация генератора случайных чисел - int x=this->mapFromGlobal(QCursor::pos()).x(); - int y=this->mapFromGlobal(QCursor::pos()).y(); - RandomInitter::init( static_cast( x * y + (x % (y==0 ? 1 : y)) + x + y ) ); + srand(time(NULL)); } @@ -115,8 +110,7 @@ void MainWindow::setupUI(void) globalParameters.setWindowSwitcher(windowSwitcher); // Вспомогательный объект с виджетом синхронизации базы знаний - syncroCommandRun=new CommandRun( this ); - globalParameters.setSyncroCommandRun( syncroCommandRun ); + synchroCommandRun=new CommandRun( this ); // todo: Для проверки, почему то в этом месте поиск объекта по имени не работает, разобраться. // MetaEditor *edView=find_object("editorScreen"); @@ -201,10 +195,10 @@ void MainWindow::setupSignals(void) connect(actionFocusEditor, &QAction::triggered, this, &MainWindow::onClickFocusEditor); // Связывание сигнала окончания выполнения команды синхронизации со слотом, срабатывающем при завершении выполнения команды - connect(syncroCommandRun, &CommandRun::finishWork, - recordTableScreen, &RecordTableScreen::onSyncroCommandFinishWork); - connect(syncroCommandRun, &CommandRun::finishWork, - this, &MainWindow::onSyncroCommandFinishWork); + connect(synchroCommandRun, &CommandRun::finishWork, + recordTableScreen, &RecordTableScreen::onSynchroCommandFinishWork); + connect(synchroCommandRun, &CommandRun::finishWork, + this, &MainWindow::onSynchroCommandFinishWork); // Связывание сигнала вызова обработки открепляемых окон на предмет того, // что они отображают существующие записи @@ -374,7 +368,7 @@ void MainWindow::saveWindowGeometry(void) // Запоминается размер сплиттера только при видимом виджете поиска, - // т.к. если виджета поиска невидно, будет запомнен нуливой размер + // т.к. если виджета поиска невидно, будет запомнен нулевой размер // if(findScreenDisp->isVisible()) - так делать нельзя, т.к. // данный метод вызывается из декструктора главного окна, и к этому моменту @@ -693,7 +687,7 @@ void MainWindow::initHiddenActions(void) void MainWindow::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); shortcutManager.initAction("misc-print", actionFileMenuPrint ); shortcutManager.initAction("misc-exportPdf", actionFileMenuExportPdf ); @@ -823,12 +817,12 @@ void MainWindow::applicationExit(void) if(mytetraConfig.get_synchrocommand().trimmed().length()>0) { enableRealClose=true; - synchronization(); // В конце синхронизации будет вызван слот onSyncroCommandFinishWork() + synchronization(); // В конце синхронизации будет вызван слот onSynchroCommandFinishWork() } // Запуск выхода из программы enableRealClose=true; - emit close(); + close(); } @@ -839,7 +833,7 @@ void MainWindow::applicationFastExit(void) // Запуск выхода из программы enableRealClose=true; - emit close(); + close(); } @@ -890,7 +884,7 @@ void MainWindow::onExpandEditArea(bool flag) void MainWindow::onClickHelpAboutMyTetra(void) { - QString version=QString::number(APPLICATION_RELEASE_VERSION)+"."+QString::number(APPLICATION_RELEASE_SUBVERSION)+"."+QString::number(APPLICATION_RELEASE_MICROVERSION); + QString version=APPLICATION_VERSION; QString infoProgramName; QString infoVersion; @@ -899,7 +893,7 @@ void MainWindow::onClickHelpAboutMyTetra(void) QString infoLicense; infoProgramName="MyTetra - smart manager
for information collecting

"; - infoVersion="v."+version+"

"; + infoVersion=version+"

"; infoAuthor="Author: Sergey M. Stepanov
"; infoEmail="Author Email:xintrea@gmail.com

"; infoLicense="GNU General Public License v.3.0

"; @@ -910,17 +904,13 @@ void MainWindow::onClickHelpAboutMyTetra(void) infoEmail+ infoLicense; - QMessageBox *msgBox = new QMessageBox(this); - msgBox->about(this, - "MyTetra v."+version, - info); + QMessageBox(this).about(this, "MyTetra v."+version, info); } void MainWindow::onClickHelpAboutQt(void) { - QMessageBox *msgBox = new QMessageBox(this); - msgBox->aboutQt(this); + QMessageBox(this).aboutQt(this); } @@ -938,14 +928,8 @@ void MainWindow::onClickHelpTechnicalInfo(void) infoProgramFile="Program file: "+globalParameters.getMainProgramFile()+"
"; infoWorkDirectory="Work directory: "+globalParameters.getWorkDirectory()+"
"; -#if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000 infoDevicePixelRatio="Device pixel ratio: "+(QString::number( qApp->devicePixelRatio(), 'f', 2 ))+"
"; - infoPhysicalDpi="Physical DPI (from screen): "+(QString::number( QApplication::screens().at(0)->physicalDotsPerInch(), 'f', 2 ))+"
"; -#endif - - infoPhysicalDpiX="Physical DPI X (from desktop): "+(QString::number( qApp->desktop()->physicalDpiX(), 'f', 2 ))+"
"; - infoPhysicalDpiY="Physical DPI Y (from desktop): "+(QString::number( qApp->desktop()->physicalDpiY(), 'f', 2 ))+"
"; - + infoPhysicalDpi="Physical DPI: "+(QString::number( QApplication::screens().at(0)->physicalDotsPerInch(), 'f', 2 ))+"
"; QString info=infoTargetOs+ infoProgramFile+ infoWorkDirectory+ @@ -954,12 +938,12 @@ void MainWindow::onClickHelpTechnicalInfo(void) infoPhysicalDpiX+ infoPhysicalDpiY; - QMessageBox *msgBox = new QMessageBox(this); - msgBox->setIcon( QMessageBox::Information ); - msgBox->setWindowTitle(tr("Technical info")); - msgBox->setText(tr("Technical info")); - msgBox->setInformativeText(info); - msgBox->exec(); + QMessageBox msgBox(this); + msgBox.setIcon( QMessageBox::Information ); + msgBox.setWindowTitle(tr("Technical info")); + msgBox.setText(tr("Technical info")); + msgBox.setInformativeText(info); + msgBox.exec(); } @@ -1045,13 +1029,13 @@ void MainWindow::reloadLoadStage(bool isLongTimeReload) void MainWindow::synchronization(bool visible) { // Если кнопка синхронизации заблокирована, начинать синхронизацию нельзя - if(!recordTableScreen->actionSyncro->isEnabled()) + if(!recordTableScreen->actionSynchro->isEnabled()) return; // Блокируется кнопка синхронизации, чтобы два раза случайно не нажать синхронизацию (окно синхронизации не модально) - recordTableScreen->actionSyncro->setEnabled(false); + recordTableScreen->actionSynchro->setEnabled(false); - actionLogger.addAction("startSyncro"); + actionLogger.addAction("startSynchro"); reloadSaveStage(); @@ -1067,29 +1051,31 @@ void MainWindow::synchronization(bool visible) QMessageBox::Close); // Кнопка синхронизации разблокируется, чтобы ее можно было снова нажать - recordTableScreen->actionSyncro->setEnabled(true); + recordTableScreen->actionSynchro->setEnabled(true); return; } - + auto cmdArgs = QProcess::splitCommand(command); // Макрос %a заменяется на путь к директории базы данных // QString databasePath=globalParameters.getWorkDirectory()+"/"+mytetraConfig.get_tetradir(); QDir databaseDir( mytetraConfig.get_tetradir() ); QString databasePath=databaseDir.canonicalPath(); - command.replace("%a", databasePath); + cmdArgs.replaceInStrings("%a", databasePath); // Запуск команды синхронизации - globalParameters.getSyncroCommandRun()->setWindowTitle(tr("MyTetra synchronization")); - globalParameters.getSyncroCommandRun()->setMessageText(tr("Synchronization in progress, please wait...")); - globalParameters.getSyncroCommandRun()->setCommand(command); - globalParameters.getSyncroCommandRun()->run(visible); + synchroCommandRun->setWindowTitle(tr("MyTetra synchronization")); + synchroCommandRun->setMessageText(tr("Synchronization in progress, please wait...")); + synchroCommandRun->setCommand(cmdArgs[0]); + cmdArgs.removeFirst(); + synchroCommandRun->setArgs(cmdArgs); + synchroCommandRun->run(visible); } // Завершение синхронизации -void MainWindow::onSyncroCommandFinishWork() +void MainWindow::onSynchroCommandFinishWork() { // Функция перечитывания дерева знаний вызывается с флагом, // что от предыдущей стадии была большая задержка @@ -1105,7 +1091,7 @@ void MainWindow::onSyncroCommandFinishWork() // делается через сингнал-слот emit doUpdateDetachedWindows(); - actionLogger.addAction("stopSyncro"); + actionLogger.addAction("stopSynchro"); // В конце синхронизации нужно проверить, не происходит ли выход из программы if(enableRealClose==true) diff --git a/app/src/views/mainWindow/MainWindow.h b/app/src/views/mainWindow/MainWindow.h index e0c06811b..50d87a8d1 100644 --- a/app/src/views/mainWindow/MainWindow.h +++ b/app/src/views/mainWindow/MainWindow.h @@ -9,8 +9,6 @@ #include #include -#include -#include #include #include @@ -30,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -141,7 +138,7 @@ private slots: void runDirectPreferences(QAction *action); - void onSyncroCommandFinishWork(void); + void onSynchroCommandFinishWork(void); void iconActivated(QSystemTrayIcon::ActivationReason reason); @@ -218,7 +215,7 @@ private slots: QSplitter *hSplitter; QSplitter *findSplitter; - CommandRun *syncroCommandRun=nullptr; + CommandRun *synchroCommandRun=nullptr; protected: diff --git a/app/src/views/printPreview/PrintPreview.cpp b/app/src/views/printPreview/PrintPreview.cpp index 77f795974..8f3e4e132 100644 --- a/app/src/views/printPreview/PrintPreview.cpp +++ b/app/src/views/printPreview/PrintPreview.cpp @@ -60,7 +60,7 @@ PrintPreview::~PrintPreview() void PrintPreview::setupPrintDoc() { - QSizeF page = printer.pageRect().size(); + QSizeF page = printer.pageLayout().paintRectPoints().size(); page.setWidth(page.width() * view->logicalDpiX() / printer.logicalDpiX()); page.setHeight(page.height() * view->logicalDpiY() / printer.logicalDpiY()); @@ -106,7 +106,7 @@ void PrintPreview::setupUI() void PrintPreview::setupShortcuts() { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); buttonPrint->setShortcut( shortcutManager.getKeySequence("misc-print") ); // Устанавливается шорткат buttonPrint->setToolTip( shortcutManager.getKeySequenceAsText("misc-print") ); // ToolTip зависит от шортката diff --git a/app/src/views/record/AddNewRecord.cpp b/app/src/views/record/AddNewRecord.cpp index 27e94020b..a0fc6a675 100644 --- a/app/src/views/record/AddNewRecord.cpp +++ b/app/src/views/record/AddNewRecord.cpp @@ -50,7 +50,6 @@ void AddNewRecord::setupUI(void) // Редактор текста записи recordTextEditor.initEnableAssembly(true); recordTextEditor.initConfigFileName(globalParameters.getWorkDirectory()+"/editorconf.ini"); - recordTextEditor.initEnableRandomSeed(false); recordTextEditor.initDisableToolList( mytetraConfig.getHideEditorTools() + (QStringList() << "save" << "showText" << "toAttach" << "settings" << "expandEditArea") ); recordTextEditor.init(Editor::WYEDIT_DESKTOP_MODE); // Так как это окно, в мобильном режиме его инициализировать не нужно, так как есть кнопка Отмена @@ -77,7 +76,7 @@ void AddNewRecord::setupUI(void) void AddNewRecord::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); // На кнопку OK назначается комбинация клавиш Ctrl+Enter QPushButton *okButton=buttonBox.button(QDialogButtonBox::Ok); // Выясняется указатель на кнопку OK @@ -100,7 +99,7 @@ void AddNewRecord::assembly(void) { // Размещалка элементов QVBoxLayout *layout=new QVBoxLayout(); - layout->setMargin(8); + layout->setContentsMargins(8, 8, 8, 8); layout->setSpacing(10); // Добавление элементов в размещалку diff --git a/app/src/views/record/AddNewRecord.h b/app/src/views/record/AddNewRecord.h index 7a72e5e50..7e436d206 100644 --- a/app/src/views/record/AddNewRecord.h +++ b/app/src/views/record/AddNewRecord.h @@ -19,7 +19,7 @@ Q_OBJECT public: - AddNewRecord( QWidget * parent = nullptr, Qt::WindowFlags f = nullptr ); + AddNewRecord( QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags() ); ~AddNewRecord(); diff --git a/app/src/views/record/InfoFieldEnter.cpp b/app/src/views/record/InfoFieldEnter.cpp index 2f1a97b4c..6a2da6222 100644 --- a/app/src/views/record/InfoFieldEnter.cpp +++ b/app/src/views/record/InfoFieldEnter.cpp @@ -81,7 +81,7 @@ void InfoFieldEnter::assembly(void) { // Размещалка элементов infoFieldLayout=new QGridLayout(); // Попробовать this - infoFieldLayout->setMargin(8); + infoFieldLayout->setContentsMargins(8, 8, 8, 8); infoFieldLayout->setSpacing(10); int y=-1; diff --git a/app/src/views/record/MetaEditor.cpp b/app/src/views/record/MetaEditor.cpp index 36cbf8e5f..6ea2a8f5c 100644 --- a/app/src/views/record/MetaEditor.cpp +++ b/app/src/views/record/MetaEditor.cpp @@ -27,7 +27,6 @@ MetaEditor::MetaEditor(QWidget *parent) : Editor(parent) { Editor::initEnableAssembly(false); Editor::initConfigFileName(globalParameters.getWorkDirectory()+"/editorconf.ini"); - Editor::initEnableRandomSeed(false); Editor::initDisableToolList( mytetraConfig.getHideEditorTools() ); if(mytetraConfig.getInterfaceMode()=="desktop") @@ -116,7 +115,7 @@ void MetaEditor::setupUI(void) // Область текстовых меток, которые выглядят на экране как [метка1] [метка2] [метка3] ... recordTagsLayout=new QHBoxLayout(); recordTagsLayout->setAlignment(Qt::AlignLeft); - recordTagsLayout->setMargin(0); + recordTagsLayout->setContentsMargins(0, 0, 0, 0); // Область текстовых меток QHBoxLayout невозможно добавить в QScrollArea, поэтому оборачивается в виджет recordTagsContainer = new QWidget(); @@ -301,7 +300,8 @@ void MetaEditor::setTags(QString tags) // Строка с метками разделяется на отдельные меки - recordTagsTextList = recordTagsText.split(QRegExp("[,;]+"), QString::SkipEmptyParts); + static const QRegularExpression re("[,;]+"); + recordTagsTextList = recordTagsText.split(re, Qt::SkipEmptyParts); // В каждой метке убираются лишние пробелы по краям for(int i = 0; i < recordTagsTextList.size(); ++i) diff --git a/app/src/views/record/MetaEditor.h b/app/src/views/record/MetaEditor.h index e10aa2229..69b335214 100644 --- a/app/src/views/record/MetaEditor.h +++ b/app/src/views/record/MetaEditor.h @@ -3,7 +3,6 @@ #include #include -#include #include "libraries/wyedit/Editor.h" diff --git a/app/src/views/record/RecordInfoFieldsEditor.cpp b/app/src/views/record/RecordInfoFieldsEditor.cpp index a026bdbd0..2e39ffe60 100644 --- a/app/src/views/record/RecordInfoFieldsEditor.cpp +++ b/app/src/views/record/RecordInfoFieldsEditor.cpp @@ -19,11 +19,7 @@ extern ShortcutManager shortcutManager; // Окно редактирования информационных полей записи (не текста записи!) // Оно появляется при двойном клике на записи или при клике на кнопку редактирования полей записи -#if QT_VERSION < 0x050000 -RecordInfoFieldsEditor::RecordInfoFieldsEditor( QWidget * parent, Qt::WFlags f) : QDialog(parent, f) -#else RecordInfoFieldsEditor::RecordInfoFieldsEditor( QWidget * parent, Qt::WindowFlags f) : QDialog(parent, f) -#endif { setupUI(); setupShortcuts(); @@ -53,7 +49,7 @@ void RecordInfoFieldsEditor::setupUI(void) // Может вызваться повторно при изменении схемы горячих клавиш void RecordInfoFieldsEditor::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); // На кнопку OK назначается комбинация клавиш Ctrl+Enter QPushButton *okButton=buttonBox->button(QDialogButtonBox::Ok); // Выясняется указатель на кнопку OK @@ -76,7 +72,7 @@ void RecordInfoFieldsEditor::assembly(void) { // Размещалка элементов QVBoxLayout *layout=new QVBoxLayout(); - layout->setMargin(8); + layout->setContentsMargins(8, 8, 8, 8); layout->setSpacing(10); // Добавление элементов в размещалку diff --git a/app/src/views/record/RecordInfoFieldsEditor.h b/app/src/views/record/RecordInfoFieldsEditor.h index 0beab3837..f481a3497 100644 --- a/app/src/views/record/RecordInfoFieldsEditor.h +++ b/app/src/views/record/RecordInfoFieldsEditor.h @@ -16,11 +16,7 @@ class RecordInfoFieldsEditor : public QDialog Q_OBJECT public: -#if QT_VERSION < 0x050000 - RecordInfoFieldsEditor( QWidget * parent = nullptr, Qt::WFlags f = 0 ); -#else - RecordInfoFieldsEditor( QWidget * parent = nullptr, Qt::WindowFlags f = 0 ); -#endif + RecordInfoFieldsEditor( QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags() ); ~RecordInfoFieldsEditor(); diff --git a/app/src/views/recordTable/RecordTablePrint.cpp b/app/src/views/recordTable/RecordTablePrint.cpp index 2ee29a8d3..94625a039 100644 --- a/app/src/views/recordTable/RecordTablePrint.cpp +++ b/app/src/views/recordTable/RecordTablePrint.cpp @@ -176,8 +176,7 @@ void RecordTablePrint::save(void) msgBox.exec(); } else { QTextStream stream(&file); - stream.setCodec("UTF-8"); - stream << textArea->document()->toHtml("UTF-8"); // Команда stream << textArea->toHtml() не подходит, так как не выствляет в заголовках charset + stream << textArea->document()->toHtml(); // Команда stream << textArea->toHtml() не подходит, так как не выствляет в заголовках charset stream.flush(); file.close(); } diff --git a/app/src/views/recordTable/RecordTableScreen.cpp b/app/src/views/recordTable/RecordTableScreen.cpp index 378b0434e..82c9ecd7e 100644 --- a/app/src/views/recordTable/RecordTableScreen.cpp +++ b/app/src/views/recordTable/RecordTableScreen.cpp @@ -101,8 +101,8 @@ void RecordTableScreen::setupActions(void) actionMoveDn->setIcon(QIcon(":/resource/pic/move_dn.svg")); // Синхронизация - actionSyncro=new QAction(this); - actionSyncro->setIcon(QIcon(":/resource/pic/synchronization.svg")); + actionSynchro=new QAction(this); + actionSynchro->setIcon(QIcon(":/resource/pic/synchronization.svg")); // Поиск по базе (клик связывается с действием в MainWindow) actionFindInBase=new QAction(shortcutManager.getDescriptionWithShortcut("misc-findInBase"), this); @@ -185,7 +185,7 @@ void RecordTableScreen::setupUI(void) if(mytetraConfig.getInterfaceMode()=="desktop") { - insertActionAsButton(extraToolsLine, actionSyncro); + insertActionAsButton(extraToolsLine, actionSynchro); insertActionAsButton(extraToolsLine, actionWalkHistoryPrevious); insertActionAsButton(extraToolsLine, actionWalkHistoryNext); } @@ -200,7 +200,7 @@ void RecordTableScreen::setupUI(void) void RecordTableScreen::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); // Добавление записи shortcutManager.initAction("note-addNewToEnd", actionAddNewToEnd); @@ -237,7 +237,7 @@ void RecordTableScreen::setupShortcuts(void) // Синхронизация - shortcutManager.initAction("misc-syncro", actionSyncro); + shortcutManager.initAction("misc-synchro", actionSynchro); // Переход на предыдущую запись в истории shortcutManager.initAction("note-previousNote", actionWalkHistoryPrevious); @@ -289,7 +289,7 @@ void RecordTableScreen::setupSignals(void) connect(actionFindInBase, &QAction::triggered, find_object("mainwindow"), &MainWindow::toolsFindInBase); // Синхронизация - connect(actionSyncro, &QAction::triggered, this, &RecordTableScreen::onSyncroClick); + connect(actionSynchro, &QAction::triggered, this, &RecordTableScreen::onSynchroClick); // Перемещение по истории посещаемых записей назад connect(actionWalkHistoryPrevious, &QAction::triggered, this, &RecordTableScreen::onWalkHistoryPreviousClick); @@ -522,16 +522,16 @@ void RecordTableScreen::setSelectionToId(QString id) // Действия при нажатии кнопки синхронизации -void RecordTableScreen::onSyncroClick(void) +void RecordTableScreen::onSynchroClick(void) { find_object("mainwindow")->synchronization(); } -void RecordTableScreen::onSyncroCommandFinishWork(void) +void RecordTableScreen::onSynchroCommandFinishWork(void) { // Разблокируется кнопка синхронизации - actionSyncro->setEnabled(true); + actionSynchro->setEnabled(true); } diff --git a/app/src/views/recordTable/RecordTableScreen.h b/app/src/views/recordTable/RecordTableScreen.h index 85a9afff0..9b0d01617 100644 --- a/app/src/views/recordTable/RecordTableScreen.h +++ b/app/src/views/recordTable/RecordTableScreen.h @@ -55,20 +55,20 @@ class RecordTableScreen : public QWidget QAction *actionSwitchSelectionMode; // Действие, которое может быть вызвано из MainWindows - QAction *actionSyncro; + QAction *actionSynchro; public slots: // Обновление состояния экранных элементов согласно состоянию записи и положении зиписи в таблице void toolsUpdate(void); - void onSyncroCommandFinishWork(void); + void onSynchroCommandFinishWork(void); void setupShortcuts(void); private slots: - void onSyncroClick(void); + void onSynchroClick(void); void onWalkHistoryPreviousClick(void); void onWalkHistoryNextClick(void); void onBackClick(void); diff --git a/app/src/views/recordTable/RecordTableView.cpp b/app/src/views/recordTable/RecordTableView.cpp index caf0cd839..582b36269 100644 --- a/app/src/views/recordTable/RecordTableView.cpp +++ b/app/src/views/recordTable/RecordTableView.cpp @@ -82,13 +82,8 @@ void RecordTableView::init(void) horizontalHeader()->setMinimumSectionSize(16); - // Горизонтальные заголовки делаются перемещяемыми - #if QT_VERSION >= 0x040000 && QT_VERSION < 0x050000 - horizontalHeader()->setMovable(true); - #endif - #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000 + // Горизонтальные заголовки делаются перемещаемыми horizontalHeader()->setSectionsMovable(true); - #endif // Установка высоты строки с принудительной стилизацией (если это необходимо), // так как стилизация через QSS для элементов QTableView полноценно не работает @@ -614,7 +609,7 @@ void RecordTableView::mouseMoveEvent(QMouseEvent *event) if(distance >= QApplication::startDragDistance()) { - startDrag(); // Начинается перетаскивание + startDrag({}); // Начинается перетаскивание } } @@ -661,8 +656,9 @@ void RecordTableView::mouseReleaseEvent(QMouseEvent *event) // Начало переноса записи -void RecordTableView::startDrag() +void RecordTableView::startDrag(Qt::DropActions supportedActions) { + Q_UNUSED(supportedActions); if( !startDragIndex.isValid() ) { return; @@ -671,7 +667,7 @@ void RecordTableView::startDrag() // Исправление особенности Qt // Выделяется строка, на которой был старт движения DragAndDrop, // так как метод startDrag() может сработать, когда выделена строка - // с соседней записью, которую на самом деле ненужно перемещать + // с соседней записью, которую на самом деле не нужно перемещать this->selectRow( startDragIndex.row() ); isDragHappeningNow=true; // Выставляется флаг что началось перетаскивание @@ -688,7 +684,7 @@ void RecordTableView::startDrag() unsigned int result=drag->exec(Qt::MoveAction); // Если перетаскивание завершено - // Это неточно, докуметаця и М.Шлее не объясняют внятно, когда срабатывает этот код + // Это неточно, докуметация и М.Шлее не объясняют внятно, когда срабатывает этот код if(result==0) { // Сюда код дойдет после того, как перетаскивание будет закончено @@ -758,7 +754,8 @@ void RecordTableView::selectionChanged(const QItemSelection &selected, qDebug() << "RecordTableView::selectionChanged()"; // Отладка - for(auto index : selected.indexes()) + const auto indices = selected.indexes(); + for(const auto & index : indices) { qDebug() << "Select row: " << index.row(); } diff --git a/app/src/views/recordTable/RecordTableView.h b/app/src/views/recordTable/RecordTableView.h index 6ea7b73cd..ffd1b6d09 100644 --- a/app/src/views/recordTable/RecordTableView.h +++ b/app/src/views/recordTable/RecordTableView.h @@ -118,7 +118,7 @@ protected slots: private: - void startDrag(); + void startDrag(Qt::DropActions supportedActions); QModelIndex startDragIndex; bool isDragHappeningNow=false; diff --git a/app/src/views/tree/KnowTreeView.cpp b/app/src/views/tree/KnowTreeView.cpp index 7efa86de0..eda4c517c 100644 --- a/app/src/views/tree/KnowTreeView.cpp +++ b/app/src/views/tree/KnowTreeView.cpp @@ -100,8 +100,11 @@ void KnowTreeView::dragMoveEvent(QDragMoveEvent *event) event->acceptProposedAction(); // Выясняется элемент дерева, над которым находится курсор +#if QT_VERSION > 0x060000 + QModelIndex index=indexAt(event->position().toPoint()); +#else QModelIndex index=indexAt(event->pos()); - +#endif // Указатель на родительский элемент, чтобы далее получить модель данных TreeScreen *parentPointer=qobject_cast( parent() ); @@ -150,8 +153,11 @@ void KnowTreeView::dropEvent(QDropEvent *event) clipboardRecords->print(); // Выясняется элемент дерева, над которым был сделан Drop +#if QT_VERSION > 0x060000 + QModelIndex index=indexAt(event->position().toPoint()); +#else QModelIndex index=indexAt(event->pos()); - +#endif // Если отпускание мышки произошло не на ветке дерева, а на свободном пустом месте в области виджета дерева if(!index.isValid()) return; diff --git a/app/src/views/tree/TreeScreen.cpp b/app/src/views/tree/TreeScreen.cpp index 71277dee4..127e7872d 100644 --- a/app/src/views/tree/TreeScreen.cpp +++ b/app/src/views/tree/TreeScreen.cpp @@ -161,7 +161,7 @@ void TreeScreen::setupActions(void) void TreeScreen::setupShortcuts(void) { - qDebug() << "Setup shortcut for" << this->metaObject()->className(); + qDebug() << "Setup shortcut for" << staticMetaObject.className(); shortcutManager.initAction("tree-expandAllSubbranch", actionList["expandAllSubbranch"] ); shortcutManager.initAction("tree-collapseAllSubbranch", actionList["collapseAllSubbranch"] ); @@ -1303,7 +1303,7 @@ void TreeScreen::importBranchFromDirectory(QString importDir) // Если импорт данных был успешным - if(importNodeId.count()>0) + if(importNodeId.size()>0) setCursorToId(importNodeId); // Курсор устанавливается на только что импортированную ветку showMessageBox(tr("Item importing finished.")); @@ -1504,10 +1504,8 @@ void TreeScreen::setCursorToIndex(QModelIndex index) // В мобильной версии реакции на выбор ветки нет (не обрабатывается сигнал смены строки в модели выбора) // Поэтому по ветке должен быть сделан виртуальный клик, чтобы заполнилась таблица конечных записей // Метод clicked() публичный начиная с Qt5 (мобильный интерфейс возможен только в Qt5) -#if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000 if(mytetraConfig.getInterfaceMode()=="mobile") emit knowTreeView->clicked(index); -#endif } diff --git a/cmake_modules/GetGitRevisionDescription.cmake b/cmake_modules/GetGitRevisionDescription.cmake new file mode 100644 index 000000000..4fbd90db7 --- /dev/null +++ b/cmake_modules/GetGitRevisionDescription.cmake @@ -0,0 +1,284 @@ +# - Returns a version string from Git +# +# These functions force a re-configure on each git commit so that you can +# trust the values of the variables in your build system. +# +# get_git_head_revision( [ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR]) +# +# Returns the refspec and sha hash of the current head revision +# +# git_describe( [ ...]) +# +# Returns the results of git describe on the source tree, and adjusting +# the output so that it tests false if an error occurs. +# +# git_describe_working_tree( [ ...]) +# +# Returns the results of git describe on the working tree (--dirty option), +# and adjusting the output so that it tests false if an error occurs. +# +# git_get_exact_tag( [ ...]) +# +# Returns the results of git describe --exact-match on the source tree, +# and adjusting the output so that it tests false if there was no exact +# matching tag. +# +# git_local_changes() +# +# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes. +# Uses the return code of "git diff-index --quiet HEAD --". +# Does not regard untracked files. +# +# Requires CMake 2.6 or newer (uses the 'function' command) +# +# Original Author: +# 2009-2020 Ryan Pavlik +# http://academic.cleardefinition.com +# +# Copyright 2009-2013, Iowa State University. +# Copyright 2013-2020, Ryan Pavlik +# Copyright 2013-2020, Contributors +# SPDX-License-Identifier: BSL-1.0 +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +if(__get_git_revision_description) + return() +endif() +set(__get_git_revision_description YES) + +# We must run the following at "include" time, not at function call time, +# to find the path to this module rather than the path to a calling list file +get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH) + +# Function _git_find_closest_git_dir finds the next closest .git directory +# that is part of any directory in the path defined by _start_dir. +# The result is returned in the parent scope variable whose name is passed +# as variable _git_dir_var. If no .git directory can be found, the +# function returns an empty string via _git_dir_var. +# +# Example: Given a path C:/bla/foo/bar and assuming C:/bla/.git exists and +# neither foo nor bar contain a file/directory .git. This wil return +# C:/bla/.git +# +function(_git_find_closest_git_dir _start_dir _git_dir_var) + set(cur_dir "${_start_dir}") + set(git_dir "${_start_dir}/.git") + while(NOT EXISTS "${git_dir}") + # .git dir not found, search parent directories + set(git_previous_parent "${cur_dir}") + get_filename_component(cur_dir "${cur_dir}" DIRECTORY) + if(cur_dir STREQUAL git_previous_parent) + # We have reached the root directory, we are not in git + set(${_git_dir_var} + "" + PARENT_SCOPE) + return() + endif() + set(git_dir "${cur_dir}/.git") + endwhile() + set(${_git_dir_var} + "${git_dir}" + PARENT_SCOPE) +endfunction() + +function(get_git_head_revision _refspecvar _hashvar) + _git_find_closest_git_dir("${CMAKE_CURRENT_SOURCE_DIR}" GIT_DIR) + + if("${ARGN}" STREQUAL "ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR") + set(ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR TRUE) + else() + set(ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR FALSE) + endif() + if(NOT "${GIT_DIR}" STREQUAL "") + file(RELATIVE_PATH _relative_to_source_dir "${CMAKE_SOURCE_DIR}" + "${GIT_DIR}") + if("${_relative_to_source_dir}" MATCHES "[.][.]" AND NOT ALLOW_LOOKING_ABOVE_CMAKE_SOURCE_DIR) + # We've gone above the CMake root dir. + set(GIT_DIR "") + endif() + endif() + if("${GIT_DIR}" STREQUAL "") + set(${_refspecvar} + "GITDIR-NOTFOUND" + PARENT_SCOPE) + set(${_hashvar} + "GITDIR-NOTFOUND" + PARENT_SCOPE) + return() + endif() + + # Check if the current source dir is a git submodule or a worktree. + # In both cases .git is a file instead of a directory. + # + if(NOT IS_DIRECTORY ${GIT_DIR}) + # The following git command will return a non empty string that + # points to the super project working tree if the current + # source dir is inside a git submodule. + # Otherwise the command will return an empty string. + # + execute_process( + COMMAND "${GIT_EXECUTABLE}" rev-parse + --show-superproject-working-tree + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE out + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT "${out}" STREQUAL "") + # If out is empty, GIT_DIR/CMAKE_CURRENT_SOURCE_DIR is in a submodule + file(READ ${GIT_DIR} submodule) + string(REGEX REPLACE "gitdir: (.*)$" "\\1" GIT_DIR_RELATIVE + ${submodule}) + string(STRIP ${GIT_DIR_RELATIVE} GIT_DIR_RELATIVE) + get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH) + get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE} + ABSOLUTE) + set(HEAD_SOURCE_FILE "${GIT_DIR}/HEAD") + else() + # GIT_DIR/CMAKE_CURRENT_SOURCE_DIR is in a worktree + file(READ ${GIT_DIR} worktree_ref) + # The .git directory contains a path to the worktree information directory + # inside the parent git repo of the worktree. + # + string(REGEX REPLACE "gitdir: (.*)$" "\\1" git_worktree_dir + ${worktree_ref}) + string(STRIP ${git_worktree_dir} git_worktree_dir) + _git_find_closest_git_dir("${git_worktree_dir}" GIT_DIR) + set(HEAD_SOURCE_FILE "${git_worktree_dir}/HEAD") + endif() + else() + set(HEAD_SOURCE_FILE "${GIT_DIR}/HEAD") + endif() + set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data") + if(NOT EXISTS "${GIT_DATA}") + file(MAKE_DIRECTORY "${GIT_DATA}") + endif() + + if(NOT EXISTS "${HEAD_SOURCE_FILE}") + return() + endif() + set(HEAD_FILE "${GIT_DATA}/HEAD") + configure_file("${HEAD_SOURCE_FILE}" "${HEAD_FILE}" COPYONLY) + + configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in" + "${GIT_DATA}/grabRef.cmake" @ONLY) + include("${GIT_DATA}/grabRef.cmake") + + set(${_refspecvar} + "${HEAD_REF}" + PARENT_SCOPE) + set(${_hashvar} + "${HEAD_HASH}" + PARENT_SCOPE) +endfunction() + +function(git_describe _var) + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + get_git_head_revision(refspec hash) + if(NOT GIT_FOUND) + set(${_var} + "GIT-NOTFOUND" + PARENT_SCOPE) + return() + endif() + if(NOT hash) + set(${_var} + "HEAD-HASH-NOTFOUND" + PARENT_SCOPE) + return() + endif() + + # TODO sanitize + #if((${ARGN}" MATCHES "&&") OR + # (ARGN MATCHES "||") OR + # (ARGN MATCHES "\\;")) + # message("Please report the following error to the project!") + # message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}") + #endif() + + #message(STATUS "Arguments to execute_process: ${ARGN}") + + execute_process( + COMMAND "${GIT_EXECUTABLE}" describe --tags --always ${hash} ${ARGN} + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE res + OUTPUT_VARIABLE out + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT res EQUAL 0) + set(out "${out}-${res}-NOTFOUND") + endif() + + set(${_var} + "${out}" + PARENT_SCOPE) +endfunction() + +function(git_describe_working_tree _var) + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + if(NOT GIT_FOUND) + set(${_var} + "GIT-NOTFOUND" + PARENT_SCOPE) + return() + endif() + + execute_process( + COMMAND "${GIT_EXECUTABLE}" describe --dirty ${ARGN} + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE res + OUTPUT_VARIABLE out + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(NOT res EQUAL 0) + set(out "${out}-${res}-NOTFOUND") + endif() + + set(${_var} + "${out}" + PARENT_SCOPE) +endfunction() + +function(git_get_exact_tag _var) + git_describe(out --exact-match ${ARGN}) + set(${_var} + "${out}" + PARENT_SCOPE) +endfunction() + +function(git_local_changes _var) + if(NOT GIT_FOUND) + find_package(Git QUIET) + endif() + get_git_head_revision(refspec hash) + if(NOT GIT_FOUND) + set(${_var} + "GIT-NOTFOUND" + PARENT_SCOPE) + return() + endif() + if(NOT hash) + set(${_var} + "HEAD-HASH-NOTFOUND" + PARENT_SCOPE) + return() + endif() + + execute_process( + COMMAND "${GIT_EXECUTABLE}" diff-index --quiet HEAD -- + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE res + OUTPUT_VARIABLE out + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(res EQUAL 0) + set(${_var} + "CLEAN" + PARENT_SCOPE) + else() + set(${_var} + "DIRTY" + PARENT_SCOPE) + endif() +endfunction() diff --git a/cmake_modules/GetGitRevisionDescription.cmake.in b/cmake_modules/GetGitRevisionDescription.cmake.in new file mode 100644 index 000000000..116efc4e4 --- /dev/null +++ b/cmake_modules/GetGitRevisionDescription.cmake.in @@ -0,0 +1,43 @@ +# +# Internal file for GetGitRevisionDescription.cmake +# +# Requires CMake 2.6 or newer (uses the 'function' command) +# +# Original Author: +# 2009-2010 Ryan Pavlik +# http://academic.cleardefinition.com +# Iowa State University HCI Graduate Program/VRAC +# +# Copyright 2009-2012, Iowa State University +# Copyright 2011-2015, Contributors +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) +# SPDX-License-Identifier: BSL-1.0 + +set(HEAD_HASH) + +file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024) + +string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS) +if(HEAD_CONTENTS MATCHES "ref") + # named branch + string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}") + if(EXISTS "@GIT_DIR@/${HEAD_REF}") + configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY) + else() + configure_file("@GIT_DIR@/packed-refs" "@GIT_DATA@/packed-refs" COPYONLY) + file(READ "@GIT_DATA@/packed-refs" PACKED_REFS) + if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}") + set(HEAD_HASH "${CMAKE_MATCH_1}") + endif() + endif() +else() + # detached HEAD + configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY) +endif() + +if(NOT HEAD_HASH) + file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024) + string(STRIP "${HEAD_HASH}" HEAD_HASH) +endif() diff --git a/mytetra.pro b/mytetra.pro deleted file mode 100644 index a6cd25915..000000000 --- a/mytetra.pro +++ /dev/null @@ -1,21 +0,0 @@ -TEMPLATE = subdirs - -RC_ICONS = app/bin/resource/pic/icon.ico - -# For desktop -!android { -SUBDIRS = app mimetex - -app.file = app/app.pro -app.depends = mimetex - -mimetex.file = thirdParty/mimetex/mimetex.pro -} - -# For Android -android { -SUBDIRS = app - -app.file = app/app.pro -} - diff --git a/script/start/mytetra.run b/script/start/mytetra.run deleted file mode 100755 index e2bc563e7..000000000 --- a/script/start/mytetra.run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -PROGDIR=$(dirname $(readlink -e $0)) -LD_LIBRARY_PATH=$PROGDIR/lib:${LD_LIBRARY_PATH} -export QT_QPA_PLATFORM_PLUGIN_PATH=$PROGDIR/platforms -export LD_LIBRARY_PATH -$PROGDIR/mytetra diff --git a/thirdParty/mimetex/CMakeLists.txt b/thirdParty/mimetex/CMakeLists.txt new file mode 100644 index 000000000..f32d26de8 --- /dev/null +++ b/thirdParty/mimetex/CMakeLists.txt @@ -0,0 +1,15 @@ +add_executable(mimetex "gifsave.c" "mimetex.c") + +target_compile_definitions(mimetex PRIVATE "AA") # turn on anti-aliasing +if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + target_compile_options(mimetex PRIVATE "/wd4267" "/wd4996") +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + target_compile_options(mimetex PRIVATE "-Wno-unused-parameter" "-Wno-sign-compare") + target_link_libraries(mimetex PRIVATE "m") +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + install(TARGETS mimetex DESTINATION "${CMAKE_INSTALL_BINDIR}") +elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") + install(TARGETS mimetex DESTINATION "${WIN_INSTALL_DIR}") +endif() diff --git a/thirdParty/mimetex/gifsave.c b/thirdParty/mimetex/gifsave.c index f495ff964..af05ad537 100644 --- a/thirdParty/mimetex/gifsave.c +++ b/thirdParty/mimetex/gifsave.c @@ -74,8 +74,8 @@ static int isCloseOutFile = 0; /* " */ #if !defined(MAXGIFSZ) /* " */ #define MAXGIFSZ 131072 /* " max #bytes comprising gif image */ #endif /* " */ -int gifSize = 0; /* " #bytes comprising gif */ -int maxgifSize = MAXGIFSZ; /* " max #bytes written to OutBuffer */ +unsigned gifSize = 0; /* " #bytes comprising gif */ +unsigned maxgifSize = MAXGIFSZ; /* " max #bytes written to OutBuffer */ extern int iscachecontenttype; /* " true to cache mime content-type */ extern char contenttype[2048]; /* " content-type:, etc. buffer */ @@ -626,8 +626,9 @@ LZW_Compress(int codesize, int (*inputbyte)(void)) { register int c; register Word index; - int clearcode, endofinfo, numbits, limit, errcode; + int clearcode, endofinfo, numbits, errcode; Word prefix = 0xFFFF; + unsigned limit; /* set up the given outfile */ InitBitFile(); diff --git a/thirdParty/mimetex/mimetex.c b/thirdParty/mimetex/mimetex.c index 570f0f6e2..9b42028d2 100644 --- a/thirdParty/mimetex/mimetex.c +++ b/thirdParty/mimetex/mimetex.c @@ -67,10 +67,8 @@ * PART2 --- raster constructor functions --- * new_raster(width,height,pixsz) allocation (and constructor) * new_subraster(width,height,pixsz)allocation (and constructor) - * new_chardef() allocate chardef struct * delete_raster(rp) deallocate raster (rp = raster ptr) * delete_subraster(sp) deallocate subraster (sp=subraster ptr) - * delete_chardef(cp) deallocate chardef (cp = chardef ptr) * --- primitive (sub)raster functions --- * rastcpy(rp) allocate new copy of rp * subrastcpy(sp) allocate new copy of sp @@ -83,7 +81,6 @@ * rastcompose(sp1,sp2,offset2,isalign,isfree) sp2 on top of sp1 * rastcat(sp1,sp2,isfree) concatanate sp1||sp2 * rastack(sp1,sp2,base,space,iscenter,isfree)stack sp2 atop sp1 - * rastile(tiles,ntiles) create composite raster from tiles * rastsmash(sp1,sp2,xmin,ymin) calc #smash pixels sp1||sp2 * rastsmashcheck(term) check if term is "safe" to smash * --- raster "drawing" functions --- @@ -104,11 +101,8 @@ * xbitmap_raster(rp,fp) emit mime xbitmap of rp on fp * type_pbmpgm(rp,ptype,file) pbm or pgm image of rp to file * read_pbm(fp,sf) read pbm from file (or pipe) opened on fp - * cstruct_chardef(cp,fp,col1) emit C struct of cp on fp - * cstruct_raster(rp,fp,col1) emit C struct of rp on fp * hex_bitmap(rp,fp,col1,isstr)emit hex dump of rp->pixmap on fp * --- ancillary output functions --- - * emit_string(fp,col1,string,comment) emit string and C comment * gftobitmap(rp) convert .gf-like pixmap to bitmap image * ====================== Font Functions ======================= * --- font lookup functions --- @@ -122,7 +116,7 @@ * get_delim(symbol,height,family) delim just larger than height * make_delim(symbol,height) construct delim exactly height size * ================= Tokenize/Parse Functions ================== - * texchar(expression,chartoken) retruns next char or \sequence + * texchar(expression,chartoken) returns next char or \sequence * texsubexpr(expr,subexpr,maxsubsz,left,right,isescape,isdelim) * texleft(expr,subexpr,maxsubsz,ldelim,rdelim) \left...\right * texscripts(expression,subscript,superscript,which)get scripts @@ -155,7 +149,6 @@ * rastdispmath(expression,size,sp) scripts for displaymath * --- table-driven handlers that rasterize... --- * rastleft(expression,size,basesp,ildelim,arg2,arg3)\left\right - * rastright(expression,size,basesp,ildelim,arg2,arg3) ...\right * rastmiddle(expression,size,basesp,arg1,arg2,arg3) \middle * rastflags(expression,size,basesp,flag,value,arg3) set flag * rastspace(expression,size,basesp,width,isfill,isheight)\,\:\; @@ -226,8 +219,9 @@ * ssweights(width,height,maxwt,wts)build canonical ss wt matrix * aacolormap(bytemap,nbytes,colors,colormap)make colors,colormap * aaweights(width,height) builds "canonical" weight matrix - * aawtpixel(image,ipixel,weights,rotate) weight image at ipixel * === miscellaneous === + * mimetexgetbytemap(expression,width,height) bytemap expression + * mimetextypebytemap(bp,grayscale,width,height,fp) type bytemap * mimetexsetmsg(newmsglevel,newmsgfp) set msglevel and msgfp * PART1 ========================== Driver =========================== * main(argc,argv) parses math expression and emits mime xbitmap @@ -406,7 +400,8 @@ * 11/15/11 J.Forkosh Version 1.73 released. * 02/15/12 J.Forkosh Version 1.74 released. * 12/28/16 J.Forkosh Version 1.75 released. - * 06/10/17 J.Forkosh Most recent revision (also see REVISIONDATE) + * 07/11/17 J.Forkosh Version 1.76 released. + * 07/11/17 J.Forkosh Most recent revision (also see REVISIONDATE) * See http://www.forkosh.com/mimetexchangelog.html for further details. * ****************************************************************************/ @@ -414,28 +409,25 @@ /* ------------------------------------------------------------------------- Program id -------------------------------------------------------------------------- */ -#define VERSION "1.75" /* mimeTeX version number */ -#define REVISIONDATE "10 June 2017" /* date of most recent revision */ +#define VERSION "1.76" /* mimeTeX version number */ +#define REVISIONDATE "11 July 2017" /* date of most recent revision */ #define COPYRIGHTTEXT "Copyright(c) 2002-2017, John Forkosh Associates, Inc" /* ------------------------------------------------------------------------- header files and macros -------------------------------------------------------------------------- */ - -// #define _GNU_SOURCE /* for strcasestr() in string.h */ -// char *strcasestr(); /* non-standard extension */ -// #define _GNU_SOURCE char *strcasestr(const char *haystack, const char *needle); -const char *strcasestr(const char *s1, const char *s2); - /* --- standard headers --- */ +#define _GNU_SOURCE /* for strcasestr() in string.h */ #include #include -/*#include */ #include #include #include #include -extern char **environ; /* for \environment directive */ + +#if !defined(_MSC_VER) + extern char ** environ; +#endif /* ------------------------------------------------------------------------- messages (used mostly by main() and also by rastmessage()) @@ -496,22 +488,50 @@ additional symbols #if defined(_O_BINARY) || defined(O_BINARY) /* setmode() now available */ #define HAVE_SETMODE /* so we'll use setmode() */ #endif - #if defined(_MSC_VER) - #define popen _popen - #define pclose _pclose - #define strncasecmp _strnicmp - - #if defined(_DEBUG) /* MS VC++ in debug mode */ + #if defined(_MSC_VER) && defined(_DEBUG) /* MS VC++ in debug mode */ /* to show source file and line numbers where memory leaks occur... */ - #define _CRTDBG_MAP_ALLOC /* ...include this debug macro */ - #include /* and this debug library */ - #endif + #define _CRTDBG_MAP_ALLOC /* ...include this debug macro */ + #include /* and this debug library */ #endif #define ISWINDOWS 1 #else #define ISWINDOWS 0 #endif +#if defined(_MSC_VER) +#define popen _popen +#define pclose _pclose +#define strncasecmp _strnicmp +int mystrncmpi(const char* s1, const char* s2,int n) +{ + int i=0; + while((s1[i]!='\0' || s2[i]!='\0') && i>will<< be compiled --- */ #define DRIVER /* main() driver will be compiled */ -#else /* --- main() won't be compiled (e.g., for gfuntype.c) --- */ - #if !defined(TEXFONTS) - #define NOTEXFONTS /* texfonts not required */ +#else /* --- no, main() >>won't<< be compiled (e.g., for gfuntype.c) --- */ + /* --- + * e.g., for gfuntype.c you should compile it as + * cc -DNOTEXFONTS gfuntype.c mimetex.c -lm -o gfuntype + * alternatively, gifscroll.c >>needs<< texfonts.h info + * and should be compiled >>without<< that -DNO... switch. + * Most programs should likely be compiled >>without<< it. + * ---------------------------------------------------------- */ + #if defined(NOTEXFONTS) && defined(TEXFONTS) /*do we want texfonts.h???*/ + #undef TEXFONTS /*assume texfonts.h >>not<< required if both given*/ #endif #endif /* --- * application headers - * ------------------- */ + * ---------------------- */ +/* --- TeX font info --- */ #if !defined(NOTEXFONTS) && !defined(TEXFONTS) - #define TEXFONTS /* to include texfonts.h */ + #define TEXFONTS /* default #include's texfonts.h */ #endif +/* --- "demo" programs only #include a few structs from mimetex.h --- */ +#define _MIMETEXMAIN (1) /* to include "everything" */ #include "mimetex.h" /* --- @@ -634,22 +664,28 @@ additional symbols * https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions * in function rotrast3d() * ------------------------------------------------------------------------ */ -/* --- 3d-point --- */ -#define point3d struct point3d_struct /* "typedef" for point3d_struct */ -point3d { - /* --- x,y,z-coords relative to 0.,0.,0. origin of abstract coord axes --- */ - double x; /* x-coord */ - double y; /* y-coord */ - double z; /* z-coord */ - } ; /* --- end-of-point3d_struct --- */ -/* --- 3d-matrix (rotation matrix) stored row-wise --- */ -#define matrix3d struct matrix3d_struct /* "typedef" for matrix3d_struct */ -matrix3d { - /* --- 3x3 matrix stored row-wise --- */ - point3d xrow; /* x-row */ - point3d yrow; /* y-row */ - point3d zrow; /* z-row */ - } ; /* --- end-of-matrix3d_struct --- */ +#if 0 + /* --- + * >> Note: point3d and matrix3d now defined in mimetex.h << + * (they're temporarily left here only as comments) + * ------------------------------------------------------------ */ + /* --- 3d-point --- */ + #define point3d struct point3d_struct /* "typedef" for point3d_struct */ + point3d { + /*---x,y,z-coords relative to 0.,0.,0. origin of abstract coord axes---*/ + double x; /* x-coord */ + double y; /* y-coord */ + double z; /* z-coord */ + } ; /* --- end-of-point3d_struct --- */ + /* --- 3d-matrix (rotation matrix) stored row-wise --- */ + #define matrix3d struct matrix3d_struct /* "typedef" for matrix3d_struct */ + matrix3d { + /* --- 3x3 matrix stored row-wise --- */ + point3d xrow; /* x-row */ + point3d yrow; /* y-row */ + point3d zrow; /* z-row */ + } ; /* --- end-of-matrix3d_struct --- */ +#endif /* --- 3d-rotation parameters --- */ #define YAXIS {0.,1.,0.} /* x-component=0, y=1, z=0 */ #define UTHETA 0.0 /* no rotation (in degrees) */ @@ -917,8 +953,8 @@ GLOBAL(int,errorstatus,ERRORSTATUS); /* exit status if error encountered*/ GLOBAL(int,exitstatus,0); /* exit status (0=success) */ STATIC FILE *msgfp; /* output in command-line mode */ /* --- logging macros --- */ -#define logdump(lvl,msg) if(msglevel>=(lvl)) {logmsg(msg);}else -#define logmsg(msg) if(1) {logger(msgfp,msglevel,(msg),NULL);}else +#define logdump(lvl,msg) if(msglevel>=(lvl)) {logmsg(msg);} +#define logmsg(msg) logger(msgfp,msglevel,(msg),NULL); /* --- embed warnings in rendered expressions, [\xxx?] if \xxx unknown --- */ #if defined(WARNINGS) #define WARNINGLEVEL WARNINGS @@ -1008,12 +1044,18 @@ GLOBAL(char,pathprefix[256],PATHPREFIX); /*prefix for \input,\counter paths*/ /* ------------------------------------------------------------------------- store for evalterm() [n.b., these are stripped-down funcs from nutshell] -------------------------------------------------------------------------- */ -#define STORE struct store_struct /* "typedef" for store struct */ -#define MAXSTORE 100 /* max 100 identifiers */ -STORE { - char *identifier; /* identifier */ - int *value; /* address of corresponding value */ - } ; /* --- end-of-store_struct --- */ +#if 0 + /* --- + * >> Note: STORE and MAXSTORE now defined in mimetex.h << + * (they're temporarily left here only as comments) + * ----------------------------------------------------------- */ + #define STORE struct store_struct /* "typedef" for store struct */ + #define MAXSTORE 100 /* max 100 identifiers */ + STORE { + char *identifier; /* identifier */ + int *value; /* address of corresponding value */ + } ; /* --- end-of-store_struct --- */ +#endif static STORE mimestore[MAXSTORE] = { { "fontsize", &fontsize }, { "fs", &fontsize }, /* font size */ { "fontnum", &fontnum }, { "fn", &fontnum }, /* font number */ @@ -1050,9 +1092,9 @@ miscellaneous macros #define dmod(x,y) ((x)-((y)*((double)((int)((x)/(y)))))) /*x%y for doubles*/ #endif #define compress(s,c) if((s)!=NULL) /* remove embedded c's from s */ \ - { char *p; while((p=strchr((s),(c)))!=NULL) {strsqueeze(p,1);} } else + { char *p; while((p=strchr((s),(c)))!=NULL) {strsqueeze(p,1);} } #define slower(s) if ((s)!=NULL) /* lowercase all chars in s */ \ - { char *p=(s); while(*p!='\000'){*p=tolower(*p); p++;} } else + { char *p=(s); while(*p!='\000'){*p=tolower(*p); p++;} } /*subraster *subrastcpy();*/ /* need global module declaration */ /*#define spnosmash(sp) if (sp->type==CHARASTER) sp=subrastcpy(sp); \ */ /* sp->type=blanksignal */ @@ -1072,7 +1114,7 @@ miscellaneous macros (thisstr)[thislen] = '\000'; \ else break; \ if ( (thislen = strspn((thisstr)," \t\n\r\f\v")) > 0 ) \ - {strsqueeze((thisstr),thislen);} } else + {strsqueeze((thisstr),thislen);} } /* --- strncpy() n bytes and make sure it's null-terminated --- */ #define strninit(target,source,n) if( (target)!=NULL && (n)>=0 ) { \ char *thissource = (source); \ @@ -1082,13 +1124,13 @@ miscellaneous macros (target)[(n)] = '\000'; } } /* --- strcpy(s,s+n) using memmove() (also works for negative n) --- */ #define strsqueeze(s,n) if((n)!=0) { if(!isempty((s))) { \ - int thislen3=strlen(s); \ + size_t thislen3=strlen(s); \ if ((n) >= thislen3) *(s) = '\000'; \ - else memmove(s,s+(n),1+thislen3-(n)); }} else/*user supplies final;*/ + else memmove(s,s+(n),1+thislen3-(n)); }} /* --- strsqueeze(s,t) with two pointers --- */ #define strsqueezep(s,t) if(!isempty((s))&&!isempty((t))) { \ int sqlen=strlen((s))-strlen((t)); \ - if (sqlen>0 && sqlen<=999) {strsqueeze((s),sqlen);} } else + if (sqlen>0 && sqlen<=999) {strsqueeze((s),sqlen);} } /* --- skip/find whitespace (from mathtex.c for getdirective()) --- */ #define findwhite(thisstr) while ( !isempty(thisstr) ) \ if ( isthischar(*(thisstr),WHITESPACE) ) break; else (thisstr)++ @@ -1119,7 +1161,7 @@ miscellaneous macros * Notes: * ======================================================================= */ /* --- entry point --- */ -raster *new_raster ( int width, int height, int pixsz ) +FUNCSCOPE raster *new_raster ( int width, int height, int pixsz ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -1128,7 +1170,7 @@ raster *rp = (raster *)NULL; /* raster ptr returned to caller */ pixbyte *pixmap = NULL; /* raster pixel map to be malloced */ int nbytes = pixsz*bitmapsz(width,height); /* #bytes needed for pixmap */ int filler = (isstring?' ':0); /* pixmap filler */ -int delete_raster(); /* in case pixmap malloc() fails */ +/*int delete_raster();*/ /* in case pixmap malloc() fails */ int npadding = (0&&issupersampling?8+256:0); /* padding bytes */ /* ------------------------------------------------------------------------- allocate and initialize raster struct and embedded bitmap @@ -1190,14 +1232,14 @@ Back to caller with address of raster struct, or NULL ptr for any error. * Notes: o if width or height <=0, embedded raster not allocated * ======================================================================= */ /* --- entry point --- */ -subraster *new_subraster ( int width, int height, int pixsz ) +FUNCSCOPE subraster *new_subraster ( int width, int height, int pixsz ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ subraster *sp=NULL; /* subraster returned to caller */ -raster *new_raster(), *rp=NULL; /* image raster embedded in sp */ -int delete_subraster(); /* in case new_raster() fails */ +raster /**new_raster(),*/ *rp=NULL; /* image raster embedded in sp */ +/*int delete_subraster();*/ /* in case new_raster() fails */ int size = NORMALSIZE, /* default size */ baseline = height-1; /* and baseline */ /* ------------------------------------------------------------------------- @@ -1236,47 +1278,6 @@ if ( width>0 && height>0 && pixsz>0 ) /* caller wants raster */ return ( sp ); } /* --- end-of-function new_subraster() --- */ - -/* ========================================================================== - * Function: new_chardef ( ) - * Purpose: Allocates and initializes a chardef struct, - * but _not_ the embedded raster struct. - * -------------------------------------------------------------------------- - * Arguments: none - * -------------------------------------------------------------------------- - * Returns: ( chardef * ) ptr to allocated and initialized - * chardef struct, or NULL for any error. - * -------------------------------------------------------------------------- - * Notes: - * ======================================================================= */ -/* --- entry point --- */ -chardef *new_chardef ( ) -{ -/* ------------------------------------------------------------------------- -Allocations and Declarations --------------------------------------------------------------------------- */ -chardef *cp = (chardef *)NULL; /* chardef ptr returned to caller */ -/* ------------------------------------------------------------------------- -allocate and initialize chardef struct --------------------------------------------------------------------------- */ -cp = (chardef *)malloc(sizeof(chardef)); /* malloc chardef struct */ -if ( cp == (chardef *)NULL ) /* malloc failed */ - goto end_of_job; /* return error to caller */ -cp->charnum = cp->location = 0; /* init character description */ -cp->toprow = cp->topleftcol = 0; /* init upper-left corner */ -cp->botrow = cp->botleftcol = 0; /* init lower-left corner */ -cp->image.width = cp->image.height = 0; /* init raster dimensions */ -cp->image.format = 0; /* init raster format */ -cp->image.pixsz = 0; /* and #bits per pixel */ -cp->image.pixmap = NULL; /* init raster pixmap as null */ -/* ------------------------------------------------------------------------- -Back to caller with address of chardef struct, or NULL ptr for any error. --------------------------------------------------------------------------- */ -end_of_job: - return ( cp ); -} /* --- end-of-function new_chardef() --- */ - - /* ========================================================================== * Function: delete_raster ( rp ) * Purpose: Destructor for raster. @@ -1290,7 +1291,7 @@ Back to caller with address of chardef struct, or NULL ptr for any error. * Notes: * ======================================================================= */ /* --- entry point --- */ -int delete_raster ( raster *rp ) +FUNCSCOPE int delete_raster ( raster *rp ) { /* ------------------------------------------------------------------------- free raster bitmap and struct @@ -1317,12 +1318,12 @@ return ( 1 ); /* back to caller, 1=okay 0=failed */ * Notes: * ======================================================================= */ /* --- entry point --- */ -int delete_subraster ( subraster *sp ) +FUNCSCOPE int delete_subraster ( subraster *sp ) { /* ------------------------------------------------------------------------- free subraster struct -------------------------------------------------------------------------- */ -int delete_raster(); /* to delete embedded raster */ +/*int delete_raster();*/ /* to delete embedded raster */ if ( sp != (subraster *)NULL ) /* can't free null ptr */ { if ( sp->type != CHARASTER ) /* not static character data */ @@ -1334,36 +1335,6 @@ return ( 1 ); /* back to caller, 1=okay 0=failed */ } /* --- end-of-function delete_subraster() --- */ -/* ========================================================================== - * Function: delete_chardef ( cp ) - * Purpose: Deallocates a chardef (and bitmap of embedded raster) - * -------------------------------------------------------------------------- - * Arguments: cp (I) ptr to chardef struct to be deleted. - * -------------------------------------------------------------------------- - * Returns: ( int ) 1 if completed successfully, - * or 0 otherwise (for any error). - * -------------------------------------------------------------------------- - * Notes: - * ======================================================================= */ -/* --- entry point --- */ -int delete_chardef ( chardef *cp ) -{ -/* ------------------------------------------------------------------------- -free chardef struct --------------------------------------------------------------------------- */ -if ( cp != (chardef *)NULL ) /* can't free null ptr */ - { - if ( cp->image.pixmap != NULL ) /* pixmap allocated within raster */ - free((void *)cp->image.pixmap); /* so free embedded pixmap */ - free((void *)cp); /* and free chardef struct itself */ - } /* --- end-of-if(cp!=NULL) --- */ -/* ------------------------------------------------------------------------- -Back to caller with 1=okay, 0=failed. --------------------------------------------------------------------------- */ -return ( 1 ); -} /* --- end-of-function delete_chardef() --- */ - - /* ========================================================================== * Function: rastcpy ( rp ) * Purpose: makes duplicate copy of rp @@ -1376,12 +1347,12 @@ return ( 1 ); * Notes: o * ======================================================================= */ /* --- entry point --- */ -raster *rastcpy ( raster *rp ) +FUNCSCOPE raster *rastcpy ( raster *rp ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *new_raster(), *newrp=NULL; /*copied raster returned to caller*/ +raster /**new_raster(),*/ *newrp=NULL; /*copied raster returned to caller*/ int height= (rp==NULL?0:rp->height), /* original and copied height */ width = (rp==NULL?0:rp->width), /* original and copied width */ pixsz = (rp==NULL?0:rp->pixsz), /* #bits per pixel */ @@ -1410,14 +1381,14 @@ return ( newrp ); /* return copied raster to caller */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *subrastcpy ( subraster *sp ) +FUNCSCOPE subraster *subrastcpy ( subraster *sp ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *newsp=NULL; /* allocate new subraster */ -raster *rastcpy(), *newrp=NULL; /* and new raster image within it */ -int delete_subraster(); /* dealloc newsp if rastcpy() fails*/ +subraster /**new_subraster(),*/ *newsp=NULL; /* allocate new subraster */ +raster /**rastcpy(),*/ *newrp=NULL; /* and new raster image within it */ +/*int delete_subraster();*/ /* dealloc newsp if rastcpy() fails*/ /* ------------------------------------------------------------------------- make copy, and return it to caller -------------------------------------------------------------------------- */ @@ -1461,12 +1432,12 @@ switch ( sp->type ) /* set new raster image type */ * a hat is <, etc. * ======================================================================= */ /* --- entry point --- */ -raster *rastrot ( raster *rp ) +FUNCSCOPE raster *rastrot ( raster *rp ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *new_raster(), *rotated=NULL; /*rotated raster returned to caller*/ +raster /**new_raster(),*/ *rotated=NULL;/*rotated raster returned to caller*/ int height = rp->height, irow, /* original height, row index */ width = rp->width, icol, /* original width, column index */ pixsz = rp->pixsz; /* #bits per pixel */ @@ -1480,8 +1451,8 @@ if ( (rotated = new_raster(height,width,pixsz)) /* flip width,height */ for ( irow=0; irowwidth, icol = 0, /* raster width, column index */ height= rp->height, irow = 0, /* raster height, row index */ pixsz = rp->pixsz; /* #bits per pixel */ double midcol = ((double)(width))/2.0, /* x-origin index coord */ midrow = ((double)(height))/2.0; /* y-origin index coord */ int bgpixel = 0; /* background pixel value */ -matrix3d *rotmatrix(), *rotmat=NULL; /* rotation matrix */ -point3d *matmult(); /* matrix multiplication */ +matrix3d /**rotmatrix(),*/ *rotmat=NULL; /* rotation matrix */ +/*point3d *matmult();*/ /* matrix multiplication */ /* ------------------------------------------------------------------------- Initialization -------------------------------------------------------------------------- */ @@ -1573,12 +1544,12 @@ for ( irow=0; irowheight, irow, /* height, row index */ width = rp->width, icol, /* width, column index */ mrow = 0, mcol = 0, /* dup pixels magstep*magstep times*/ @@ -1626,7 +1597,8 @@ if ( (magnified = new_raster(magstep*width,magstep*height,pixsz))/*allocate*/ * as described by http://en.wikipedia.org/wiki/2xSaI * ======================================================================= */ /* --- entry point --- */ -intbyte *bytemapmag ( intbyte *bytemap, int width, int height, int magstep ) +FUNCSCOPE intbyte *bytemapmag ( intbyte *bytemap, + int width, int height, int magstep ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -1745,12 +1717,12 @@ if ( (magnified = (intbyte *)(malloc(magstep*width*magstep*height)))/*alloc*/ * Notes: o * ======================================================================= */ /* --- entry point --- */ -raster *rastref ( raster *rp, int axis ) +FUNCSCOPE raster *rastref ( raster *rp, int axis ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *new_raster(), *reflected=NULL; /* reflected raster back to caller */ +raster /**new_raster(),*/ *reflected=NULL;/*reflected raster back to caller*/ int height = rp->height, irow, /* height, row index */ width = rp->width, icol, /* width, column index */ pixsz = rp->pixsz; /* #bits per pixel */ @@ -1790,8 +1762,8 @@ return ( reflected ); /*return reflected raster to caller*/ * Notes: * ======================================================================= */ /* --- entry point --- */ -int rastput ( raster *target, raster *source, - int top, int left, int isopaque ) +FUNCSCOPE int rastput ( raster *target, raster *source, + int top, int left, int isopaque ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -1897,16 +1869,16 @@ Back to caller with 1=okay, 0=failed. * +------------------------+ --- * ======================================================================= */ /* --- entry point --- */ -subraster *rastcompose ( subraster *sp1, subraster *sp2, int offset2, - int isalign, int isfree ) +FUNCSCOPE subraster *rastcompose ( subraster *sp1, subraster *sp2, + int offset2, int isalign, int isfree ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *sp=(subraster *)NULL; /* returned subraster */ +subraster /**new_subraster(),*/ *sp=(subraster *)NULL; /*returned subraster*/ raster *rp=(raster *)NULL; /* new composite raster in sp */ -int delete_subraster(); /* in case isfree non-zero */ -int rastput(); /*place sp1,sp2 in composite raster*/ +/*int delete_subraster();*/ /* in case isfree non-zero */ +/*int rastput();*/ /*place sp1,sp2 in composite raster*/ int base1 = sp1->baseline, /*baseline for underlying subraster*/ height1 = (sp1->image)->height, /* height for underlying subraster */ width1 = (sp1->image)->width, /* width for underlying subraster */ @@ -2013,16 +1985,16 @@ Back to caller with pointer to concatted subraster or with null for error * Notes: * ======================================================================= */ /* --- entry point --- */ -subraster *rastcat ( subraster *sp1, subraster *sp2, int isfree ) +FUNCSCOPE subraster *rastcat ( subraster *sp1, subraster *sp2, int isfree ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *sp=(subraster *)NULL; /* returned subraster */ +subraster /**new_subraster(),*/ *sp=(subraster *)NULL; /*returned subraster*/ raster *rp=(raster *)NULL; /* new concatted raster */ -int delete_subraster(); /* in case isfree non-zero */ -int rastput(); /*place sp1,sp2 in concatted raster*/ -int type_raster(); /* debugging display */ +/*int delete_subraster();*/ /* in case isfree non-zero */ +/*int rastput();*/ /*place sp1,sp2 in concatted raster*/ +/*int type_raster();*/ /* debugging display */ int base1 = sp1->baseline, /*baseline for left-hand subraster*/ height1 = (sp1->image)->height, /* height for left-hand subraster */ width1 = (sp1->image)->width, /* width for left-hand subraster */ @@ -2217,16 +2189,16 @@ Back to caller with pointer to concatted subraster or with null for error * Notes: * ======================================================================= */ /* --- entry point --- */ -subraster *rastack ( subraster *sp1, subraster *sp2, - int base, int space, int iscenter, int isfree ) +FUNCSCOPE subraster *rastack ( subraster *sp1, subraster *sp2, + int base, int space, int iscenter, int isfree ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *sp=(subraster *)NULL; /* returned subraster */ +subraster /**new_subraster(),*/ *sp=(subraster *)NULL; /*returned subraster*/ raster *rp=(raster *)NULL; /* new stacked raster in sp */ -int delete_subraster(); /* in case isfree non-zero */ -int rastput(); /* place sp1,sp2 in stacked raster */ +/*int delete_subraster();*/ /* in case isfree non-zero */ +/*int rastput();*/ /* place sp1,sp2 in stacked raster */ int base1 = sp1->baseline, /* baseline for lower subraster */ height1 = (sp1->image)->height, /* height for lower subraster */ width1 = (sp1->image)->width, /* width for lower subraster */ @@ -2282,81 +2254,6 @@ Back to caller with pointer to stacked subraster or with null for error } /* --- end-of-function rastack() --- */ -/* ========================================================================== - * Function: rastile ( tiles, ntiles ) - * Purpose: Allocate and build up a composite raster - * from the ntiles components/characters supplied in tiles. - * -------------------------------------------------------------------------- - * Arguments: tiles (I) subraster * to array of subraster structs - * describing the components and their locations - * ntiles (I) int containing number of subrasters in tiles[] - * -------------------------------------------------------------------------- - * Returns: ( raster * ) ptr to composite raster, - * or NULL for any error. - * -------------------------------------------------------------------------- - * Notes: o The top,left corner of a raster is row=0,col=0 - * with row# increasing as you move down, - * and col# increasing as you move right. - * Metafont numbers rows with the baseline=0, - * so the top row is a positive number that - * decreases as you move down. - * o rastile() is no longer used. - * It was used by an earlier rasterize() algorithm, - * and I've left it in place should it be needed again. - * But recent changes haven't been tested/exercised. - * ======================================================================= */ -/* --- entry point --- */ -raster *rastile ( subraster *tiles, int ntiles ) -{ -/* ------------------------------------------------------------------------- -Allocations and Declarations --------------------------------------------------------------------------- */ -raster *new_raster(), *composite=(raster *)NULL; /*raster back to caller*/ -int width=0, height=0, pixsz=0, /*width,height,pixsz of composite raster*/ - toprow=9999, rightcol=-999, /* extreme upper-right corner of tiles */ - botrow=-999, leftcol=9999; /* extreme lower-left corner of tiles */ -int itile; /* tiles[] index */ -int rastput(); /* overlay each tile in composite raster */ -/* ------------------------------------------------------------------------- -run through tiles[] to determine dimensions for composite raster --------------------------------------------------------------------------- */ -/* --- determine row and column bounds of composite raster --- */ -for ( itile=0; itiletoprow); - leftcol = min2(leftcol, tile->leftcol); - /* --- lower-right corner of composite --- */ - botrow = max2(botrow, tile->toprow + (tile->image)->height - 1); - rightcol = max2(rightcol, tile->leftcol + (tile->image)->width - 1); - /* --- pixsz of composite --- */ - pixsz = max2(pixsz,(tile->image)->pixsz); - } /* --- end-of-for(itile) --- */ -/* --- calculate width and height from bounds --- */ -width = rightcol - leftcol + 1; -height = botrow - toprow + 1; -/* --- sanity check (quit if bad dimensions) --- */ -if ( width<1 || height<1 ) goto end_of_job; -/* ------------------------------------------------------------------------- -allocate composite raster, and embed tiles[] within it --------------------------------------------------------------------------- */ -/* --- allocate composite raster --- */ -if ( (composite=new_raster(width,height,pixsz)) /*allocate composite raster*/ -== (raster *)NULL ) goto end_of_job; /* and quit if failed */ -/* --- embed tiles[] in composite --- */ -for ( itile=0; itileimage, /* overlay tile image at...*/ - tile->toprow-toprow, tile->leftcol-leftcol, 1); } /*upper-left corner*/ -/* ------------------------------------------------------------------------- -Back to caller with composite raster (or null for any error) --------------------------------------------------------------------------- */ -end_of_job: - return ( composite ); /* back with composite or null ptr */ -} /* --- end-of-function rastile() --- */ - - /* ========================================================================== * Function: rastsmash ( sp1, sp2 ) * Purpose: When concatanating sp1||sp2, calculate #pixels @@ -2372,7 +2269,7 @@ Back to caller with composite raster (or null for any error) * Notes: o * ======================================================================= */ /* --- entry point --- */ -int rastsmash ( subraster *sp1, subraster *sp2 ) +FUNCSCOPE int rastsmash ( subraster *sp1, subraster *sp2 ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -2391,8 +2288,8 @@ int base = max2(base1,base2), /* max ascenders - 1 above baseline*/ int irow1=0,irow2=0, icol=0; /* row,col indexes */ int firstcol1[1025], nfirst1=0, /* 1st sp1 col containing set pixel*/ firstcol2[1025], nfirst2=0; /* 1st sp2 col containing set pixel*/ -int smin=9999, xmin=9999,ymin=9999; /* min separation (s=x+y) */ -int type_raster(); /* display debugging output */ +int smin=9999, xmin=9999; /* min separation (s=x+y) */ +/*int type_raster();*/ /* display debugging output */ /* ------------------------------------------------------------------------- find right edge of sp1 and left edge of sp2 (these will be abutting edges) -------------------------------------------------------------------------- */ @@ -2440,7 +2337,7 @@ for ( irow2=top2; irow2<=bot2; irow2++ ) { /* check each row inside sp2 */ int dx=(margin1+margin2), dy=absval(irow2-irow1), ds=dx+dy; /* deltas */ if ( ds >= smin ) continue; /* min unchanged */ if ( dy>smashmargin && dxarrow, false for -->*/ @@ -2655,7 +2552,7 @@ switch ( accent ) /* --- sqrt request --- */ case SQRTACCENT: serifwidth = SURDSERIFWIDTH(height); /* leading serif on surd */ - col1 = SQRTWIDTH(height,(iswidthneg?1:2)) - 1; /*right col of sqrt*/ + col1 = (int)(SQRTWIDTH(height,(iswidthneg?1:2)) - 1); /*right col of sqrt*/ /*col0 = (col1-serifwidth+2)/3;*/ /* midpoint col of sqrt */ col0 = (col1-serifwidth+1)/2; /* midpoint col of sqrt */ row0 = max2(1,((height+1)/2)-2); /* midpoint row of sqrt */ @@ -2748,14 +2645,14 @@ return ( sp ); /* return accent or NULL to caller */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *arrow_subraster ( int width, int height, int pixsz, - int drctn, int isBig ) +FUNCSCOPE subraster *arrow_subraster ( int width, int height, int pixsz, + int drctn, int isBig ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *arrowsp=NULL; /* allocate arrow subraster */ -int rule_raster(); /* draw arrow line */ +subraster /**new_subraster(),*/ *arrowsp=NULL; /* allocate arrow subraster */ +/*int rule_raster();*/ /* draw arrow line */ int irow, midrow=height/2; /* index, midrow is arrowhead apex */ int icol, thickness=(height>15?2:2); /* arrowhead thickness and index */ int pixval = (pixsz==1? 1 : (pixsz==8?255:(-1))); /* black pixel value */ @@ -2824,14 +2721,14 @@ for ( irow=0; irow15?2:2); /* arrowhead thickness and index */ int pixval = (pixsz==1? 1 : (pixsz==8?255:(-1))); /* black pixel value */ @@ -2907,8 +2804,8 @@ for ( icol=0; icol 0 ) /* zero width implies strut*/ * whose top-left corner is row0,col0. * ======================================================================= */ /* --- entry point --- */ -int line_raster ( raster *rp, int row0, int col0, - int row1, int col1, int thickness ) +FUNCSCOPE int line_raster ( raster *rp, int row0, int col0, + int row1, int col1, int thickness ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3020,7 +2917,7 @@ double ar = ASPECTRATIO, /* aspect ratio width/height of one pixel */ xwidth= (isline? 0.0 : /*#pixels per row to get sloped line thcknss*/ ((double)thickness)*sqrt((dx*dx)+(dy*dy*ar*ar))/fabs(dy*ar)), xheight = 1.0; -int line_recurse(), isrecurse=1; /* true to draw line recursively */ +int /*line_recurse(),*/ isrecurse=1; /* true to draw line recursively */ /* ------------------------------------------------------------------------- Check args -------------------------------------------------------------------------- */ @@ -3130,8 +3027,8 @@ Back to caller with 1=okay, 0=failed. * until a horizontal or vertical segment is found * ======================================================================= */ /* --- entry point --- */ -int line_recurse ( raster *rp, double row0, double col0, - double row1, double col1, int thickness ) +FUNCSCOPE int line_recurse ( raster *rp, double row0, double col0, + double row1, double col1, int thickness ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3191,8 +3088,8 @@ return ( 1 ); * o using ellipse equation x^2/a^2 + y^2/b^2 = 1 * ======================================================================= */ /* --- entry point --- */ -int circle_raster ( raster *rp, int row0, int col0, - int row1, int col1, int thickness, char *quads ) +FUNCSCOPE int circle_raster ( raster *rp, int row0, int col0, + int row1, int col1, int thickness, char *quads ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3223,7 +3120,7 @@ double xy, xy2, /* major axis ellipse coord */ yx2, yx; /* solved minor ellipse coord */ int isokay = 1; /* true if no pixels out-of-bounds */ char *qptr=NULL, *allquads="1234"; /* quadrants if input quads==NULL */ -int circle_recurse(), isrecurse=1; /* true to draw ellipse recursively*/ +int /*circle_recurse(),*/ isrecurse=1; /*true to draw ellipse recursively*/ /* ------------------------------------------------------------------------- pixel-by-pixel along positive major axis, quit when it goes negative -------------------------------------------------------------------------- */ @@ -3264,7 +3161,7 @@ else switch ( *qptr ) /* check for quadrant 1,2,3,4 */ { default: break; /* unrecognized, assume quadrant 1 */ case '4': rsign = 1; break; /* row,col both pos in quadrant 4 */ - case '3': rsign = 1; /* row pos, col neg in quadrant 3 */ + case '3': rsign = 1; /* FALLTHRU */ /* row pos, col neg in quadrant 3 */ case '2': csign = (-1); break; } /* row,col both neg in quadrant 2 */ irow = iround(midrow + (double)rsign*(islandscape?yx:xy)); irow = min2(hirow,max2(lorow,irow)); /* keep irow in bounds */ @@ -3299,7 +3196,7 @@ else switch ( *qptr ) /* check for quadrant 1,2,3,4 */ { default: break; /* unrecognized, assume quadrant 1 */ case '4': rsign = 1; break; /* row,col both pos in quadrant 4 */ - case '3': rsign = 1; /* row pos, col neg in quadrant 3 */ + case '3': rsign = 1; /* FALLTHRU */ /* row pos, col neg in quadrant 3 */ case '2': csign = (-1); break; } /* row,col both neg in quadrant 2 */ irow = iround(midrow + (double)rsign*(islandscape?yx:xy)); irow = min2(hirow,max2(lorow,irow)); /* keep irow in bounds */ @@ -3352,8 +3249,8 @@ return ( isokay ); * equation is r = ab/sqrt(a^2*sin^2(theta)+b^2*cos^2(theta)) * ======================================================================= */ /* --- entry point --- */ -int circle_recurse ( raster *rp, int row0, int col0, - int row1, int col1, int thickness, double theta0, double theta1 ) +FUNCSCOPE int circle_recurse ( raster *rp, int row0, int col0, int row1, + int col1, int thickness, double theta0, double theta1 ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3427,8 +3324,8 @@ return ( 1 ); * until a point is found * ======================================================================= */ /* --- entry point --- */ -int bezier_raster ( raster *rp, double r0, double c0, - double r1, double c1, double rt, double ct ) +FUNCSCOPE int bezier_raster ( raster *rp, double r0, double c0, + double r1, double c1, double rt, double ct ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3461,7 +3358,7 @@ icol = iround(midcol); /* col pixel coord */ /* --- bounds check --- */ if ( irow>=0 && irowheight /* row in bounds */ && icol>=0 && icolwidth ) /* col in bounds */ - setpixel(rp,irow,icol,255); /* so set pixel at irow,icol*/ + setpixel(rp,irow,icol,255); /* so set pixel at irow,icol*/ else status = 0; /* bad status if out-of-bounds */ return ( status ); } /* --- end-of-function bezier_raster() --- */ @@ -3502,14 +3399,14 @@ return ( status ); * draws all four sides, too. * ======================================================================= */ /* --- entry point --- */ -raster *border_raster ( raster *rp, int ntop, int nbot, - int isline, int isfree ) +FUNCSCOPE raster *border_raster ( raster *rp, int ntop, int nbot, + int isline, int isfree ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *new_raster(), *bp=(raster *)NULL; /*raster back to caller*/ -int rastput(); /* overlay rp in new bordered raster */ +raster /**new_raster(),*/ *bp=(raster *)NULL; /*raster back to caller*/ +/*int rastput();*/ /* overlay rp in new bordered raster */ int width = (rp==NULL?0:rp->width), /* width of raster */ height = (rp==NULL?0:rp->height), /* height of raster */ istopneg=0, isbotneg=0, /* true if ntop or nbot negative */ @@ -3615,14 +3512,14 @@ Back to caller with bordered raster (or null for any error) * Notes: o For \! negative space, for \hspace{-10}, etc. * ======================================================================= */ /* --- entry point --- */ -raster *backspace_raster ( raster *rp, int nback, int *pback, int minspace, - int isfree ) +FUNCSCOPE raster *backspace_raster ( raster *rp, int nback, int *pback, + int minspace, int isfree ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *new_raster(), *bp=(raster *)NULL; /* raster returned to caller */ -int delete_raster(); /* free input rp if isfree is true */ +raster /**new_raster(),*/ *bp=(raster *)NULL; /*raster returned to caller*/ +/*int delete_raster();*/ /* free input rp if isfree is true */ int width = (rp==NULL?0:rp->width), /* original width of raster */ height = (rp==NULL?0:rp->height), /* height of raster */ mback = nback, /* nback adjusted for minspace */ @@ -3684,7 +3581,7 @@ Back to caller with backspaced raster (or null for any error) * Notes: * ======================================================================= */ /* --- entry point --- */ -int type_raster ( raster *rp, FILE *fp ) +FUNCSCOPE int type_raster ( raster *rp, FILE *fp ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3695,8 +3592,8 @@ static char display_chars[16] = /* display chars for bytemap */ char scanline[133]; /* ascii image for one scan line */ int scan_width; /* #chars in scan (<=display_width)*/ int irow, locol,hicol=(-1); /* height index, width indexes */ -raster *gftobitmap(), *bitmaprp=rp; /* convert .gf to bitmap if needed */ -int delete_raster(); /*free bitmap converted for display*/ +raster /**gftobitmap(),*/ *bitmaprp=rp; /* convert .gf to bitmap if needed */ +/*int delete_raster();*/ /*free bitmap converted for display*/ /* -------------------------------------------------------------------------- initialization -------------------------------------------------------------------------- */ @@ -3782,8 +3679,8 @@ return ( 1 ); * Notes: * ======================================================================= */ /* --- entry point --- */ -int type_bytemap ( intbyte *bp, int grayscale, - int width, int height, FILE *fp ) +FUNCSCOPE int type_bytemap ( intbyte *bp, int grayscale, + int width, int height, FILE *fp ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3801,6 +3698,8 @@ int ibyte, /* bp[] index */ /* -------------------------------------------------------------------------- initialization -------------------------------------------------------------------------- */ +/* --- check args --- */ +if ( bp == NULL ) goto end_of_job; /* nothing to do */ /* --- redirect null fp --- */ if ( fp == (FILE *)NULL ) fp = stdout; /* default fp to stdout if null */ /* --- check for ascii string --- */ @@ -3853,10 +3752,11 @@ while ( (locol=hicol+1) < width ) /*start where prev segment left off*/ /* ------------------------------------------------------------------------- Back to caller with 1=okay, 0=failed. -------------------------------------------------------------------------- */ -return ( 1 ); +end_of_job: return ( 1 ); } /* --- end-of-function type_bytemap() --- */ +#if !defined(GIF) /* ========================================================================== * Function: xbitmap_raster ( rp, fp ) * Purpose: Emit a mime xbitmap representing rp, on fp. @@ -3872,13 +3772,13 @@ return ( 1 ); * Notes: * ======================================================================= */ /* --- entry point --- */ -int xbitmap_raster ( raster *rp, FILE *fp ) +FUNCSCOPE int xbitmap_raster ( raster *rp, FILE *fp ) { /* ------------------------------------------------------------------------- Allocations and Declarations --------------------------------------------------------------------------- */ +--------------------------------------------------------------------------- */ char *title = "image"; /* dummy title */ -int hex_bitmap(); /* dump bitmap as hex bytes */ +/*int hex_bitmap();*/ /* dump bitmap as hex bytes */ /* -------------------------------------------------------------------------- emit text to display mime xbitmap representation of rp->bitmap image -------------------------------------------------------------------------- */ @@ -3890,7 +3790,7 @@ if ( isstring ) /* pixmap has string, not raster */ /* --- emit prologue strings and hex dump of bitmap for mime xbitmap --- */ fprintf( fp, "Content-type: image/x-xbitmap\n\n" ); fprintf( fp, "#define %s_width %d\n#define %s_height %d\n", - title,rp->width, title,rp->height ); + title,rp->width, title,rp->height ); fprintf( fp, "static char %s_bits[] = {\n", title ); hex_bitmap(rp,fp,0,0); /* emit hex dump of bitmap bytes */ fprintf (fp,"};\n"); /* ending with "};" for C array */ @@ -3899,6 +3799,7 @@ Back to caller with 1=okay, 0=failed. -------------------------------------------------------------------------- */ return ( 1 ); } /* --- end-of-function xbitmap_raster() --- */ +#endif /*GIF*/ /* ========================================================================== @@ -3927,7 +3828,7 @@ return ( 1 ); * by .pbm or .pgm depending on ptype. * ======================================================================= */ /* --- entry point --- */ -int type_pbmpgm ( raster *rp, int ptype, char *file ) +FUNCSCOPE int type_pbmpgm ( raster *rp, int ptype, char *file ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -3939,7 +3840,7 @@ int pixmin=9999, pixmax=(-9999), /* min, max pixel value in raster */ FILE /* *fopen(), */ *fp=NULL; /* pointer to output file (or NULL) */ char outline[1024], outfield[256], /* output line, field */ cr[16] = "\n\000"; /* cr at end-of-line */ -int maxlinelen = 70; /* maximum allowed line length */ +size_t maxlinelen = 70; /* maximum allowed line length */ int pixfrac=6; /* use (pixmax-pixmin)/pixfrac as step */ static char *suffix[] = { NULL, ".pbm", ".pgm" }, /* file.suffix[ptype] */ @@ -4059,16 +3960,16 @@ Back to caller with total #bytes written, or 0=failed. * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *read_pbm ( FILE *fp, double sf ) +FUNCSCOPE subraster *read_pbm ( FILE *fp, double sf ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *sp = NULL; /* subraster corresponding to pbm */ +subraster /**new_subraster(),*/ *sp = NULL; /*subraster corresponding to pbm*/ raster *rp = NULL; /* sp->image raster in subraster */ -raster *ssrp=NULL, *imgsupsamp(); /* supersampled/shrunk rp */ -int delete_subraster(), /* in case of problem/error */ - delete_raster(); /* in case we shrink/supersample rp */ +raster *ssrp=NULL /*, *imgsupsamp()*/; /* supersampled/shrunk rp */ +/*int delete_subraster(),*/ /* in case of problem/error */ +/* delete_raster();*/ /* in case we shrink/supersample rp */ unsigned char *pixels = NULL; /* pixels returned in pbm image */ char fline[8192], /* fgets(fline,8190,fp) buffer */ *lineptr=NULL, *endptr=NULL; /* strtol ptr to 1st char after num*/ @@ -4163,92 +4064,7 @@ if ( sf>0.01 && sf<0.99 ) { /* valid sf means shrink requested */ } /* --- end-of-function read_pbm() --- */ -/* ========================================================================== - * Function: cstruct_chardef ( cp, fp, col1 ) - * Purpose: Emit a C struct of cp on fp, starting in col1. - * -------------------------------------------------------------------------- - * Arguments: cp (I) ptr to chardef struct for which - * a C struct is to be generated. - * fp (I) File ptr to output device (defaults to - * stdout if passed as NULL). - * col1 (I) int containing 0...65; output lines - * are preceded by col1 blanks. - * -------------------------------------------------------------------------- - * Returns: ( int ) 1 if completed successfully, - * or 0 otherwise (for any error). - * -------------------------------------------------------------------------- - * Notes: - * ======================================================================= */ -/* --- entry point --- */ -int cstruct_chardef ( chardef *cp, FILE *fp, int col1 ) -{ -/* ------------------------------------------------------------------------- -Allocations and Declarations --------------------------------------------------------------------------- */ -char field[64]; /* field within output line */ -int cstruct_raster(), /* emit a raster */ - emit_string(); /* emit a string and comment */ -/* ------------------------------------------------------------------------- -emit charnum, location, name / hirow, hicol, lorow, locol --------------------------------------------------------------------------- */ -/* --- charnum, location, name --- */ -sprintf(field,"{ %3d,%5d,\n", cp->charnum,cp->location); /*char#,location*/ -emit_string ( fp, col1, field, "character number, location"); -/* --- toprow, topleftcol, botrow, botleftcol --- */ -sprintf(field," %3d,%2d, %3d,%2d,\n", /* format... */ - cp->toprow,cp->topleftcol, /* toprow, topleftcol, */ - cp->botrow,cp->botleftcol); /* and botrow, botleftcol */ -emit_string ( fp, col1, field, "topleft row,col, and botleft row,col"); -/* ------------------------------------------------------------------------- -emit raster and chardef's closing brace, and then return to caller --------------------------------------------------------------------------- */ -cstruct_raster(&cp->image,fp,col1+4); /* emit raster */ -emit_string ( fp, 0, " }", NULL); /* emit closing brace */ -return ( 1 ); /* back to caller with 1=okay, 0=failed */ -} /* --- end-of-function cstruct_chardef() --- */ - - -/* ========================================================================== - * Function: cstruct_raster ( rp, fp, col1 ) - * Purpose: Emit a C struct of rp on fp, starting in col1. - * -------------------------------------------------------------------------- - * Arguments: rp (I) ptr to raster struct for which - * a C struct is to be generated. - * fp (I) File ptr to output device (defaults to - * stdout if passed as NULL). - * col1 (I) int containing 0...65; output lines - * are preceded by col1 blanks. - * -------------------------------------------------------------------------- - * Returns: ( int ) 1 if completed successfully, - * or 0 otherwise (for any error). - * -------------------------------------------------------------------------- - * Notes: - * ======================================================================= */ -/* --- entry point --- */ -int cstruct_raster ( raster *rp, FILE *fp, int col1 ) -{ -/* ------------------------------------------------------------------------- -Allocations and Declarations --------------------------------------------------------------------------- */ -char field[64]; /* field within output line */ -char typecast[64] = "(pixbyte *)"; /* type cast for pixmap string */ -int hex_bitmap(); /* to emit raster bitmap */ -int emit_string(); /* emit a string and comment */ -/* ------------------------------------------------------------------------- -emit width and height --------------------------------------------------------------------------- */ -sprintf(field,"{ %2d, %3d,%2d,%2d, %s\n", /* format width,height,pixsz */ - rp->width,rp->height,rp->format,rp->pixsz,typecast); -emit_string ( fp, col1, field, "width,ht, fmt,pixsz,map..."); -/* ------------------------------------------------------------------------- -emit bitmap and closing brace, and return to caller --------------------------------------------------------------------------- */ -hex_bitmap(rp,fp,col1+2,1); /* emit bitmap */ -emit_string ( fp, 0, " }", NULL); /* emit closing brace */ -return ( 1 ); /* back to caller with 1=okay, 0=failed */ -} /* --- end-of-function cstruct_raster() --- */ - - +#if !defined (GIF) /* ========================================================================== * Function: hex_bitmap ( rp, fp, col1, isstr ) * Purpose: Emit a hex dump of the bitmap of rp on fp, starting in col1. @@ -4271,7 +4087,7 @@ return ( 1 ); /* back to caller with 1=okay, 0=failed */ * Notes: * ======================================================================= */ /* --- entry point --- */ -int hex_bitmap ( raster *rp, FILE *fp, int col1, int isstr ) +FUNCSCOPE int hex_bitmap ( raster *rp, FILE *fp, int col1, int isstr ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -4314,72 +4130,7 @@ for ( ibyte=0; ibyte 6 ) /* can fit all or part of comment */ - sprintf(line+linelen-fieldlen,"/%c %.*s %c/", /* so embed it in line */ - '*', fieldlen-6,comment, '*'); - col1 = linelen; } /* indicate line filled */ -/* --- line completed --- */ -line[col1] = '\000'; /* null-terminate completed line */ -/* ------------------------------------------------------------------------- -emit line, then back to caller with 1=okay, 0=failed. --------------------------------------------------------------------------- */ -/* --- first redirect null fp --- */ -if ( fp == (FILE *)NULL ) fp = stdout; /* default fp to stdout if null */ -/* --- emit line (and optional newline) --- */ -fprintf(fp,"%.*s",linelen,line); /* no more than linelen chars */ -if ( isnewline ) fprintf(fp,"\n"); /*caller wants terminating newline*/ -return ( 1 ); -} /* --- end-of-function emit_string() --- */ +#endif /*GIF*/ /* ========================================================================== @@ -4394,12 +4145,12 @@ return ( 1 ); * Notes: o * ======================================================================= */ /* --- entry point --- */ -raster *gftobitmap ( raster *gf ) +FUNCSCOPE raster *gftobitmap ( raster *gf ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *new_raster(), *rp=NULL; /* image raster retuned to caller */ +raster /**new_raster(),*/ *rp=NULL; /* image raster retuned to caller */ int width=0, height=0, totbits=0; /* gf->width, gf->height, #bits */ int format=0, icount=0, ncounts=0, /*.gf format, count index, #counts*/ ibit=0, bitval=0; /* bitmap index, bit value */ @@ -4480,7 +4231,7 @@ for ( icount=0,bitval=0; icount0 */ -int delete_subraster(); /* in case gftobitmap() fails */ -int delete_raster(); /* in case IMAGERASTER replaced */ -int aasupsamp(), /*antialias char with supersampling*/ +chardef /**get_chardef(),*/ *gfdata=NULL; /* chardef struct for symdef,size */ +/*int get_baseline();*/ /* baseline of gfdata */ +subraster /**new_subraster(),*/ *sp=NULL; /* subraster containing gfdata */ +raster *bitmaprp=NULL /*, *gftobitmap()*/; /* convert .gf-format to bitmap */ +raster *rotp=NULL /*, *rastrot3d()*/; /* rotate character if utheta>0 */ +/*int delete_subraster();*/ /* in case gftobitmap() fails */ +/*int delete_raster();*/ /* in case IMAGERASTER replaced */ +int /*aasupsamp(),*/ /*antialias char with supersampling*/ grayscale=256; /* aasupersamp() parameters */ /* ------------------------------------------------------------------------- look up chardef for symdef at size, and embed data (gfdata) in subraster @@ -4854,13 +4605,13 @@ return ( sp ); /* back to caller */ * Notes: o just combines get_symdef() and get_charsubraster() * ======================================================================= */ /* --- entry point --- */ -subraster *get_symsubraster ( char *symbol, int size ) +FUNCSCOPE subraster *get_symsubraster ( char *symbol, int size ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *sp=NULL, *get_charsubraster(); /* subraster containing gfdata */ -mathchardef *symdef=NULL, *get_symdef(); /* mathchardef lookup for symbol */ +subraster *sp=NULL /*, *get_charsubraster()*/; /*subraster containing gfdata*/ +mathchardef *symdef=NULL /*, *get_symdef()*/;/*mathchardef lookup for symbol*/ /* ------------------------------------------------------------------------- look up mathchardef for symbol -------------------------------------------------------------------------- */ @@ -4892,7 +4643,7 @@ return ( sp ); /* back to caller with sp or NULL */ * and everything else descends below the baseline. * ======================================================================= */ /* --- entry point --- */ -int get_baseline ( chardef *gfdata ) +FUNCSCOPE int get_baseline ( chardef *gfdata ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -4930,15 +4681,15 @@ return ( (height-1) + botrow ); /* note: descenders have botrow<0 */ * but the best-fit width is searched for (rather than height) * ======================================================================= */ /* --- entry point --- */ -subraster *get_delim ( char *symbol, int height, int family ) +FUNCSCOPE subraster *get_delim ( char *symbol, int height, int family ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ mathchardef *symdefs = symtable; /* table of mathchardefs */ -subraster *get_charsubraster(), *sp=(subraster *)NULL; /* best match char */ -subraster *make_delim(); /* construct delim if can't find it*/ -chardef *get_chardef(), *gfdata=NULL; /* get chardef struct for a symdef */ +subraster /**get_charsubraster(),*/ *sp=(subraster *)NULL; /*best match char*/ +/*subraster *make_delim();*/ /* construct delim if can't find it*/ +chardef /**get_chardef(),*/ *gfdata=NULL; /*get chardef struct for a symdef*/ char lcsymbol[256], *symptr, /* lowercase symbol for comparison */ *unescsymbol = symbol; /* unescaped symbol */ int symlen = (symbol==NULL?0:strlen(symbol)), /* #chars in caller's sym*/ @@ -5059,20 +4810,20 @@ return ( sp ); * and interpreted as width (rather than height) * ======================================================================= */ /* --- entry point --- */ -subraster *make_delim ( char *symbol, int height ) +FUNCSCOPE subraster *make_delim ( char *symbol, int height ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *sp = (subraster *)NULL, /* subraster returned to caller */ - *new_subraster(); /* allocate subraster */ -subraster *get_symsubraster(), /* look up delim pieces in cmex10 */ +subraster *sp = (subraster *)NULL /* subraster returned to caller */ + /*,*new_subraster()*/; /* allocate subraster */ +subraster /**get_symsubraster(),*/ /* look up delim pieces in cmex10 */ *symtop=NULL, *symbot=NULL, *symmid=NULL, *symbar=NULL, /* pieces */ - *topsym=NULL, *botsym=NULL, *midsym=NULL, *barsym=NULL, /* +filler */ - *rastack(), *rastcat(); /* stack pieces, concat filler */ + *topsym=NULL, *botsym=NULL, *midsym=NULL, *barsym=NULL /* +filler */ + /*,*rastack(), *rastcat()*/; /* stack pieces, concat filler */ int isdrawparen = 0; /*1=draw paren, 0=build from pieces*/ raster *rasp = (raster *)NULL; /* sp->image */ -int isokay=0, delete_subraster(); /* set true if delimiter drawn ok */ +int isokay=0 /*, delete_subraster()*/; /*set true if delimiter drawn ok*/ int pixsz = 1, /* pixels are one bit each */ symsize = 0; /* size arg for get_symsubraster() */ int thickness = 1; /* drawn lines are one pixel thick */ @@ -5083,10 +4834,10 @@ char *lp=NULL, *rp=NULL, /* check symbol for left or right */ *lp2=NULL, *rp2=NULL, /* synonym for lp,rp */ *lp3=NULL, *rp3=NULL, /* synonym for lp,rp */ *lp4=NULL, *rp4=NULL; /* synonym for lp,rp */ -int circle_raster(), /* ellipse for ()'s in sp->image */ - rule_rsater(), /* horizontal or vertical lines */ - line_raster(); /* line between two points */ -subraster *uparrow_subraster(); /* up/down arrows */ +/*int circle_raster(),*/ /* ellipse for ()'s in sp->image */ +/* rule_rsater(),*/ /* horizontal or vertical lines */ +/* line_raster();*/ /* line between two points */ +/*subraster *uparrow_subraster();*/ /* up/down arrows */ int isprealloc = 1; /*pre-alloc subraster, except arrow*/ int oldsmashmargin = smashmargin, /* save original smashmargin */ wasnocatspace = isnocatspace; /* save original isnocatspace */ @@ -5425,7 +5176,7 @@ back to caller * returns any whitespace character as the next character. * ======================================================================= */ /* --- entry point --- */ -char *texchar ( char *expression, char *chartoken ) +FUNCSCOPE char *texchar ( char *expression, char *chartoken ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -5550,17 +5301,17 @@ if ( esclen >= 1 ) { /*only for alpha \sequences*/ * And it also acts as a LaTeX \left. and matches any \right) * ======================================================================= */ /* --- entry point --- */ -char *texsubexpr ( char *expression, char *subexpr, int maxsubsz, - char *left, char *right, int isescape, int isdelim ) +FUNCSCOPE char *texsubexpr ( char *expression, char *subexpr, int maxsubsz, + char *left, char *right, int isescape, int isdelim ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texchar(); /*next char (or \sequence) from expression*/ +/*char *texchar();*/ /*next char (or \sequence) from expression*/ char *leftptr, leftdelim[256] = "(\000", /* left( found in expression */ rightdelim[256] = ")\000"; /* and matching right) */ char *origexpression=expression, *origsubexpr=subexpr; /*original inputs*/ -char *strtexchr(), *texleft(); /* check for \left, and get it */ +/*char *strtexchr(), *texleft();*/ /* check for \left, and get it */ int gotescape = 0, /* true if leading char of expression is \ */ prevescape = 0; /* while parsing, true if preceding char \ */ int isbrace(); /* check for left,right braces */ @@ -5701,14 +5452,14 @@ while ( 1 ) /*until balanced right} */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *texleft ( char *expression, char *subexpr, int maxsubsz, - char *ldelim, char *rdelim ) +FUNCSCOPE char *texleft ( char *expression, char *subexpr, int maxsubsz, + char *ldelim, char *rdelim ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texchar(), /* get delims after \left,\right */ - *strtexchr(), *pright=expression; /* locate matching \right */ +char /**texchar(),*/ /* get delims after \left,\right */ + /**strtexchr(),*/ *pright=expression; /* locate matching \right */ static char left[16]="\\left", right[16]="\\right"; /* tex delimiters */ int sublen = 0; /* #chars between \left...\right */ /* ------------------------------------------------------------------------- @@ -5803,13 +5554,13 @@ if ( sublen > 0 ) /* have subexpr */ * i.e., totally ignoring all but the last "script" encountered * ======================================================================= */ /* --- entry point --- */ -char *texscripts ( char *expression, char *subscript, - char *superscript, int which ) +FUNCSCOPE char *texscripts ( char *expression, char *subscript, + char *superscript, int which ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(); /* next subexpression from expression */ +/*char *texsubexpr();*/ /* next subexpression from expression */ int gotsub=0, gotsup=0; /* check that we don't eat, e.g., x_1_2 */ /* ------------------------------------------------------------------------- init "scripts" @@ -5870,7 +5621,7 @@ return ( expression ); * Notes: o * ======================================================================= */ /* --- entry point --- */ -int isbrace ( char *expression, char *braces, int isescape ) +FUNCSCOPE int isbrace ( char *expression, char *braces, int isescape ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -5902,10 +5653,9 @@ back to caller if ( msglevel>=999 && msgfp!=NULL ) { fprintf(msgfp,"isbrace> expression=%.8s, gotbrace=%d (isligature=%d)\n", expression,gotbrace,isligature); fflush(msgfp); } - if ( gotbrace && /* found a brace */ - ( isescape==2 || /* escape irrelevant */ - gotescape==isescape ) /* un/escaped as requested */ - ) return ( 1 ); return ( 0 ); /* return 1,0 accordingly */ + if ( gotbrace && ( isescape==2 || gotescape==isescape/* un/escaped as requested */)) + return 1; + return 0; } /* --- end-of-function isbrace() --- */ @@ -5934,7 +5684,7 @@ back to caller * ptr will have "flushed" and preamble parameters after size * ======================================================================= */ /* --- entry point --- */ -char *preamble ( char *expression, int *size, char *subexpr ) +FUNCSCOPE char *preamble ( char *expression, int *size, char *subexpr ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -6039,18 +5789,18 @@ back to caller * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *mimeprep ( char *expression ) +FUNCSCOPE char *mimeprep ( char *expression ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ char *expptr=expression, /* ptr within expression */ *tokptr=NULL, /*ptr to token found in expression*/ - *texsubexpr(), argval[8192]; /*parse for macro args after token*/ -char *strchange(); /* change leading chars of string */ -int strreplace(); /* replace nnn with actual num, etc*/ -char *strwstr(); /*use strwstr() instead of strstr()*/ -char *findbraces(); /*find left { and right } for \atop*/ + /**texsubexpr(),*/ argval[8192]; /*parse for macro args after token*/ +/*char *strchange();*/ /* change leading chars of string */ +/*int strreplace();*/ /* replace nnn with actual num, etc*/ +/*char *strwstr();*/ /*use strwstr() instead of strstr()*/ +/*char *findbraces();*/ /*find left { and right } for \atop*/ int idelim=0, /* left- or right-index */ isymbol=0; /*symbols[],rightcomment[],etc index*/ int xlateleft = 0; /* true to xlate \left and \right */ @@ -6355,7 +6105,7 @@ for(isymbol=0; (htmlsym=symbols[isymbol].html) != NULL; isymbol++) int htmllen = strlen(htmlsym); /* length of escape, _without_ ; */ int isalgebra = isalpha((int)(*htmlsym)); /* leading char alphabetic */ int isembedded = 0, /* true to xlate even if embedded */ - istag=0, isamp=0, /* true for , &char; symbols */ + istag=0, /* true for */ isstrwstr = 0, /* true to use strwstr() */ wstrlen = 0; /* length of strwstr() match */ char *aleft="{([<|", *aright="})]>|"; /*left,right delims for alg syntax*/ @@ -6371,7 +6121,6 @@ for(isymbol=0; (htmlsym=symbols[isymbol].html) != NULL; isymbol++) skipwhite(htmlsym); /*skip any bogus leading whitespace*/ htmllen = strlen(htmlsym); /* reset length of html token */ istag = (isthischar(*htmlsym,"<")?1:0); /* html starts with < */ - isamp = (isthischar(*htmlsym,"&")?1:0); /* html &char; starts with & */ if ( args != NULL ) /*we have args (or htmlterm) param*/ if ( *args != '\000' ) { /* and it's not an empty string */ if ( strchr("0123456789",*args) != NULL ) /* is 1st char #args=0-9 ? */ @@ -6615,7 +6364,7 @@ return ( expression ); * (i.e., we don't do a realloc) * ======================================================================= */ /* --- entry point --- */ -char *strchange ( int nfirst, char *from, char *to ) +FUNCSCOPE char *strchange ( int nfirst, char *from, char *to ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -6660,7 +6409,7 @@ return ( from ); /* changed string back to caller */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int strreplace ( char *string, char *from, char *to, int nreplace ) +FUNCSCOPE int strreplace ( char *string, char *from, char *to, int nreplace ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -6668,8 +6417,8 @@ Allocations and Declarations int fromlen = (from==NULL?0:strlen(from)), /* #chars to be replaced */ tolen = (to==NULL?0:strlen(to)); /* #chars in replacement string */ char *pfrom = (char *)NULL, /*ptr to 1st char of from in string*/ - *pstring = string, /*ptr past previously replaced from*/ - *strchange(); /* change 'from' to 'to' */ + *pstring = string /*ptr past previously replaced from*/ + /*,*strchange()*/; /* change 'from' to 'to' */ int nreps = 0; /* #replacements returned to caller*/ /* ------------------------------------------------------------------------- repace occurrences of 'from' in string to 'to' @@ -6742,7 +6491,7 @@ return ( nreps ); /* #replacements back to caller */ * by "virtual blanks". * ======================================================================= */ /* --- entry point --- */ -char *strwstr ( char *string, char *substr, char *white, int *sublen ) +FUNCSCOPE char *strwstr(char *string, char *substr, char *white, int *sublen) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -6857,13 +6606,13 @@ Back to caller with ptr to first occurrence of substr in string * with output from the preceding call. * ======================================================================= */ /* --- entry point --- */ -char *strdetex ( char *s, int mode ) +FUNCSCOPE char *strdetex ( char *s, int mode ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ static char sbuff[4096]; /* copy of s with no math chars */ -int strreplace(); /* replace _ with -, etc */ +/*int strreplace();*/ /* replace _ with -, etc */ /* ------------------------------------------------------------------------- Make a clean copy of s -------------------------------------------------------------------------- */ @@ -6909,7 +6658,7 @@ strreplace(sbuff,"^","{\\fs{+2}\\^}",0); /* change all ^'s to \^ */ * Notes: o texchr should contain its leading \, e.g., "\\left" * ======================================================================= */ /* --- entry point --- */ -char *strtexchr ( char *string, char *texchr ) +FUNCSCOPE char *strtexchr ( char *string, char *texchr ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -6955,7 +6704,7 @@ return ( ptexchr ); /* ptr to texchar back to caller */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *findbraces ( char *expression, char *command ) +FUNCSCOPE char *findbraces ( char *expression, char *command ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7034,7 +6783,7 @@ while ( 1 ) /* search for brace, or until end */ * o leading/trailing whitespace is trimmed from returned segment * ======================================================================= */ /* --- entry point --- */ -char *strpspn ( char *s, char *reject, char *segment ) +FUNCSCOPE char *strpspn ( char *s, char *reject, char *segment ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7094,7 +6843,7 @@ while ( *ps != '\000' ) { /* search till end of input string */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int isstrstr ( char *string, char *snippets, int iscase ) +FUNCSCOPE int isstrstr ( char *string, char *snippets, int iscase ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7155,7 +6904,7 @@ end_of_job: return ( status ); /*1 if snippet found in list, else 0*/ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int isnumeric ( char *s ) +FUNCSCOPE int isnumeric ( char *s ) { /* ------------------------------------------------------------------------- determine whether s is an integer @@ -7197,7 +6946,7 @@ status = 1; /* numeric after checks succeeded */ * (index?a:b:c:etc) which must be enclosed in parentheses. * ======================================================================= */ /* --- entry point --- */ -int evalterm ( STORE *store, char *term ) +FUNCSCOPE int evalterm ( STORE *store, char *term ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7257,9 +7006,11 @@ if ( *term != '\000' ) { /* found arithmetic operation */ case '-': termval = leftval-rightval; break; /* subtraction */ case '*': termval = leftval*rightval; break; /* multiplication */ case '/': if ( rightval != 0 ) /* guard against divide by zero */ - termval = leftval/rightval; break; /* integer division */ + termval = leftval/rightval; + break; /* integer division */ case '%': if ( rightval != 0 ) /* guard against divide by zero */ - termval = leftval%rightval; break; /*left modulo right */ + termval = leftval%rightval; + break; /*left modulo right */ } /* --- end-of-switch(*relation) --- */ goto end_of_job; /* return result to caller */ } /* --- end-of-if(*term!='\000')) --- */ @@ -7317,7 +7068,7 @@ back to caller with truth value of proposition * Notes: o * ======================================================================= */ /* --- entry point --- */ -int getstore ( STORE *store, char *identifier ) +FUNCSCOPE int getstore ( STORE *store, char *identifier ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7383,8 +7134,8 @@ if ( store[istore].value != NULL ) /* address of int supplied */ * 8 means arg terminated by first whitespace char * ======================================================================= */ /* --- entry point --- */ -char *getdirective ( char *string, char *directive, - int iscase, int isvalid, int nargs, void *args ) +FUNCSCOPE char *getdirective ( char *string, char *directive, + int iscase, int isvalid, int nargs, void *args ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7399,7 +7150,7 @@ int nfmt=0, /*isnegfmt=0,*/ /* {arg} format */ argfmt[9]={0,0,0,0,0,0,0,0,0}; /* argformat digits */ int gotargs = (args==NULL?0:1); /* true if args array supplied */ int isdalpha = 1; /* true if directive ends with alpha*/ -char *strpspn(char *s,char *reject,char *segment); /*non-() not in rej*/ +/*char *strpspn(char *s,char *reject,char *segment);*/ /*non-() not in rej*/ #if 0 /* --- declared globally above --- */ /* --- * mathtex global variables (not used by mimetex) @@ -7507,7 +7258,7 @@ if ( nargs > 0 ) /* \directive has {args} */ /* --- store argument field in caller's array --- */ if ( kfmt==0 && *plbrace=='[' ) { /*store [arg] as optionalarg instead*/ if ( noptional < 8 ) { /* don't overflow our buffer */ - strninit(optionalargs[noptional],argfld,254); } /*copy to optionalarg*/ + strninit(optionalargs[noptional],argfld,sizeof(optionalargs[0])-1); } /*copy to optionalarg*/ noptional++; } /* count another optional [arg] */ else /*{args} returned in caller's array*/ if ( gotargs ) { /*caller supplied address or array*/ @@ -7573,13 +7324,13 @@ Back to caller * o leading/trailing whitespace is trimmed from returned segment * ======================================================================= */ /* --- entry point --- */ -char *strpspn ( char *s, char *reject, char *segment ) +FUNCSCOPE char *strpspn ( char *s, char *reject, char *segment ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ char *ps = s; /* current pointer into s */ -char *strqspn(char *s,char *q,int isunescape); /*span quoted string*/ +/*char *strqspn(char *s,char *q,int isunescape);*/ /*span quoted string*/ char qreject[256]="\000", *pq=qreject, *pr=reject; /*find "or' in reject*/ int isqspan = 0; /* true to span quoted strings */ int depth = 0; /* () paren nesting level */ @@ -7665,7 +7416,7 @@ while ( *ps != '\000' ) { /* search till end of input string */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *strqspn ( char *s, char *q, int isunescape ) +FUNCSCOPE char *strqspn ( char *s, char *q, int isunescape ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -7756,11 +7507,11 @@ while ( *(++ps) != '\000' ) { /* end-of-string always terminates */ * o Added ^M,^F,etc to blank xlation 0n 01-Oct-06 * ======================================================================= */ /* --- entry point --- */ -int unescape_url(char *url, int isescape) { +FUNCSCOPE int unescape_url(char *url, int isescape) { int x=0,y=0,prevescape=0,gotescape=0; int xlateplus = (isplusblank==1?1:0); /* true to xlate plus to blank */ int strreplace(); /* replace + with blank, if needed */ - char x2c(); + /*char x2c();*/ static char *hex="0123456789ABCDEFabcdef"; /* --- * xlate ctrl chars to blanks @@ -7838,7 +7589,7 @@ int unescape_url(char *url, int isescape) { return 0; } /* --- end-of-function unescape_url() --- */ /* --- entry point --- */ -char x2c(char *what) { +FUNCSCOPE char x2c(char *what) { char digit; digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0')); digit *= 16; @@ -7869,35 +7620,35 @@ char x2c(char *what) { * of that expression. Then do what you want with the bitmap. * ======================================================================= */ /* --- entry point --- */ -subraster *rasterize ( char *expression, int size ) +FUNCSCOPE subraster *rasterize ( char *expression, int size ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *preamble(), pretext[512]; /* process preamble, if present */ -char chartoken[MAXSUBXSZ+1], *texsubexpr(), /*get subexpression from expr*/ +char /**preamble(),*/ pretext[512]; /* process preamble, if present */ +char chartoken[MAXSUBXSZ+1], /**texsubexpr(),*/ /*get subexpr from expr*/ *subexpr = chartoken; /* token may be parenthesized expr */ -int isbrace(); /* check subexpr for braces */ -mathchardef *symdef, *get_symdef(); /*get mathchardef struct for symbol*/ -int ligdef, get_ligature(); /*get symtable[] index for ligature*/ +/*int isbrace();*/ /* check subexpr for braces */ +mathchardef *symdef /*, *get_symdef()*/; /*get mathchardef struct for symbol*/ +int ligdef /*, get_ligature()*/; /*get symtable[] index for ligature*/ int natoms=0; /* #atoms/tokens processed so far */ -int type_raster(); /* display debugging output */ -subraster *rasterize(), /* recurse */ - *rastparen(), /* handle parenthesized subexpr's */ - *rastlimits(); /* handle sub/superscripted expr's */ -subraster *rastcat(), /* concatanate atom subrasters */ - *subrastcpy(), /* copy final result if a charaster*/ - *new_subraster(); /* new subraster for isstring mode */ -subraster *get_charsubraster(), /* character subraster */ +/*int type_raster();*/ /* display debugging output */ +/*subraster *rasterize(),*/ /* recurse */ +/* *rastparen(),*/ /* handle parenthesized subexpr's */ +/* *rastlimits();*/ /* handle sub/superscripted expr's */ +/*subraster *rastcat(),*/ /* concatanate atom subrasters */ +/* *subrastcpy(),*/ /* copy final result if a charaster*/ +/* *new_subraster();*/ /* new subraster for isstring mode */ +subraster /**get_charsubraster(),*/ /* character subraster */ *sp=NULL, *prevsp=NULL, /* raster for current, prev char */ *expraster = (subraster *)NULL; /* raster returned to caller */ -int delete_subraster(); /* free everything before returning*/ +/*int delete_subraster();*/ /* free everything before returning*/ int family = fontinfo[fontnum].family; /* current font family */ int isleftscript = 0, /* true if left-hand term scripted */ wasscripted = 0, /* true if preceding token scripted*/ wasdelimscript = 0; /* true if preceding delim scripted*/ /*int pixsz = 1;*/ /*default #bits per pixel, 1=bitmap*/ -char *strdetex(); /* detex token for error message */ +/*char *strdetex();*/ /* detex token for error message */ /* --- global values saved/restored at each recursive iteration --- */ int wasstring = isstring, /* initial isstring mode flag */ wasdisplaystyle = isdisplaystyle, /*initial displaystyle mode flag*/ @@ -8144,7 +7895,7 @@ back to caller with rasterized expression * but passed for consistency * ======================================================================= */ /* --- entry point --- */ -subraster *rastparen ( char **subexpr, int size, subraster *basesp ) +FUNCSCOPE subraster *rastparen ( char **subexpr, int size, subraster *basesp ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -8156,14 +7907,14 @@ int isescape = 0, /* true if parens \escaped */ isleftdot = 0; /* true if left paren is \left. */ char left[32], right[32]; /* parens enclosing expresion */ char noparens[MAXSUBXSZ+1]; /* get subexpr without parens */ -subraster *rasterize(), *sp=NULL; /* rasterize what's between ()'s */ +subraster /**rasterize(),*/ *sp=NULL; /* rasterize what's between ()'s */ int isheight = 1; /*true=full height, false=baseline*/ int height, /* height of rasterized noparens[] */ baseline; /* and its baseline */ int family = /*CMSYEX*/ CMEX10; /* family for paren chars */ -subraster *get_delim(), *lp=NULL, *rp=NULL; /* left and right paren chars */ -subraster *rastcat(); /* concatanate subrasters */ -int delete_subraster(); /*in case of error after allocation*/ +subraster /**get_delim(),*/ *lp=NULL, *rp=NULL; /*left and right paren chars*/ +/*subraster *rastcat();*/ /* concatanate subrasters */ +/*int delete_subraster();*/ /*in case of error after allocation*/ /* ------------------------------------------------------------------------- rasterize "interior" of expression, i.e., without enclosing parens -------------------------------------------------------------------------- */ @@ -8245,25 +7996,26 @@ if ( sp != NULL ) /* succeeded or ignored \left. */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastlimits ( char **expression, int size, subraster *basesp ) +FUNCSCOPE subraster *rastlimits ( char **expression, int size, + subraster *basesp ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *rastscripts(), *rastdispmath(), /*one of these will do the work*/ - *rastcat(), /* may need to concat scripts */ - *rasterize(), /* may need to construct dummy base*/ +subraster /**rastscripts(),*rastdispmath(),*/ /*one of these will do the work*/ + /**rastcat(),*/ /* may need to concat scripts */ + /**rasterize(),*/ /* may need to construct dummy base*/ *scriptsp = basesp, /* and this will become the result */ *dummybase = basesp; /* for {}_i construct a dummy base */ int isdisplay = (-1); /* set 1 for displaystyle, else 0 */ int oldsmashmargin = smashmargin; /* save original smashmargin */ -int type_raster(); /* display debugging output */ -int delete_subraster(); /* free dummybase, if necessary */ -int rastsmashcheck(); /* check if okay to smash scripts */ +/*int type_raster();*/ /* display debugging output */ +/*int delete_subraster();*/ /* free dummybase, if necessary */ +/*int rastsmashcheck();*/ /* check if okay to smash scripts */ /* --- to check for \limits or \nolimits preceding scripts --- */ -char *texchar(), *exprptr=*expression, limtoken[255]; /*check for \limits*/ +char /**texchar(),*/ *exprptr=*expression, limtoken[255]; /*check \limits*/ int toklen=0; /* strlen(limtoken) */ -mathchardef *tokdef, *get_symdef(); /* mathchardef struct for limtoken */ +mathchardef *tokdef /*, *get_symdef()*/; /* mathchardef struct for limtoken */ int class=(leftsymdef==NULL?NOVALUE:leftsymdef->class); /*base sym class*/ /* ------------------------------------------------------------------------- determine whether or not to use displaymath @@ -8373,33 +8125,33 @@ else { /* scripts alongside base symbol */ * but is called directly from rasterize(), as necessary. * ======================================================================= */ /* --- entry point --- */ -subraster *rastscripts ( char **expression, int size, subraster *basesp ) +FUNCSCOPE subraster *rastscripts ( char **expression, int size, + subraster *basesp ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texscripts(), /* parse expression for scripts */ +char /**texscripts(),*/ /* parse expression for scripts */ subscript[512], supscript[512]; /* scripts parsed from expression */ -subraster *rasterize(), *subsp=NULL, *supsp=NULL; /* rasterize scripts */ -subraster *new_subraster(), *sp=NULL, /* super- over subscript subraster */ - *rastack(); /*sets scripts in displaymath mode*/ +subraster /**rasterize(),*/ *subsp=NULL, *supsp=NULL; /* rasterize scripts */ +subraster /**new_subraster(),*/ *sp=NULL /*super- over subscript subraster*/ + /*,*rastack()*/; /*sets scripts in displaymath mode*/ raster *rp=NULL; /* image raster embedded in sp */ int height=0, width=0, baseline=0, /* height,width,baseline of sp */ - subht=0, subwidth=0, subln=0, /* height,width,baseline of sub */ - supht=0, supwidth=0, supln=0, /* height,width,baseline of sup */ + subht=0, subwidth=0, /* height,width of sub */ + supht=0, supwidth=0, /* height,width of sup */ baseht=0, baseln=0; /* height,baseline of base */ int bdescend=0, sdescend=0; /* descender of base, subscript */ -int issub=0, issup=0, isboth=0, /* true if we have sub,sup,both */ - isbase=0; /* true if we have base symbol */ +int issub=0, issup=0, isboth=0; /* true if we have sub,sup,both */ int szval = min2(max2(size,0),LARGESTSIZE), /* 0...LARGESTSIZE */ vbetween = 2, /* vertical space between scripts */ vabove = szval+1, /*sup's top/bot above base's top/bot*/ vbelow = szval+1, /*sub's top/bot below base's top/bot*/ vbottom = szval+1; /*sup's bot above (sub's below) bsln*/ /*int istweak = 1;*/ /* true to tweak script positioning */ -int rastput(); /*put scripts in constructed raster*/ -int delete_subraster(); /* free work areas */ -int rastsmashcheck(); /* check if okay to smash scripts */ +/*int rastput();*/ /*put scripts in constructed raster*/ +/*int delete_subraster();*/ /* free work areas */ +/*int rastsmashcheck();*/ /* check if okay to smash scripts */ int pixsz = 1; /*default #bits per pixel, 1=bitmap*/ /* ------------------------------------------------------------------------- Obtain subscript and/or superscript expressions, and rasterize them/it @@ -8434,13 +8186,11 @@ get height, width, baseline of scripts, and height, baseline of base symbol -------------------------------------------------------------------------- */ /* --- get height and width of components --- */ if ( issub ) /* we have a subscript */ - { subht = (subsp->image)->height; /* so get its height */ - subwidth = (subsp->image)->width; /* and width */ - subln = subsp->baseline; } /* and baseline */ + { subht = (subsp->image)->height; + subwidth = (subsp->image)->width; } if ( issup ) /* we have a superscript */ - { supht = (supsp->image)->height; /* so get its height */ - supwidth = (supsp->image)->width; /* and width */ - supln = supsp->baseline; } /* and baseline */ + { supht = (supsp->image)->height; + supwidth = (supsp->image)->width; } /* --- get height and baseline of base, and descender of base and sub --- */ if ( basesp == (subraster *)NULL ) /* no base symbol for scripts */ basesp = leftexpression; /* try using left side thus far */ @@ -8448,8 +8198,7 @@ if ( basesp != (subraster *)NULL ) /* we have base symbol for scripts */ { baseht = (basesp->image)->height; /* height of base symbol */ baseln = basesp->baseline; /* and its baseline */ bdescend = baseht-(baseln+1); /* and base symbol descender */ - sdescend = bdescend + vbelow; /*sub must descend by at least this*/ - if ( baseht > 0 ) isbase = 1; } /* set flag */ + sdescend = bdescend + vbelow; }/*sub must descend by at least this*/ /* ------------------------------------------------------------------------- determine width of constructed raster -------------------------------------------------------------------------- */ @@ -8524,17 +8273,17 @@ free unneeded component subrasters and return final result to caller * Notes: o sp returned unchanged if no super/subscript(s) follow it. * ======================================================================= */ /* --- entry point --- */ -subraster *rastdispmath ( char **expression, int size, subraster *sp ) +FUNCSCOPE subraster *rastdispmath (char **expression, int size, subraster *sp) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texscripts(), /* parse expression for scripts */ +char /**texscripts(),*/ /* parse expression for scripts */ subscript[512], supscript[512]; /* scripts parsed from expression */ int issub=0, issup=0; /* true if we have sub,sup */ -subraster *rasterize(), *subsp=NULL, *supsp=NULL, /* rasterize scripts */ - *rastack(), /* stack operator with scripts */ - *new_subraster(); /* for dummy base sp, if needed */ +subraster /**rasterize(),*/ *subsp=NULL, *supsp=NULL /* rasterize scripts */ + /*,*rastack(),*/ /* stack operator with scripts */ + /**new_subraster()*/; /* for dummy base sp, if needed */ int vspace = 1; /* vertical space between scripts */ /* ------------------------------------------------------------------------- Obtain subscript and/or superscript expressions, and rasterize them/it @@ -8603,30 +8352,30 @@ free unneeded component subrasters and return final result to caller * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastleft ( char **expression, int size, subraster *basesp, - int ildelim, int arg2, int arg3 ) +FUNCSCOPE subraster *rastleft ( char **expression, int size, subraster *basesp, + int ildelim, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *rasterize(), *sp=NULL; /*rasterize between \left...\right*/ -subraster *get_delim(), *lp=NULL, *rp=NULL; /* left and right delim chars */ -subraster *rastlimits(); /*handle sub/super scripts on lp,rp*/ -subraster *rastcat(); /* concat lp||sp||rp subrasters */ +subraster /**rasterize(),*/ *sp=NULL; /*rasterize between \left...\right*/ +subraster /**get_delim(),*/ *lp=NULL, *rp=NULL; /*left and right delim chars*/ +/*subraster *rastlimits();*/ /*handle sub/super scripts on lp,rp*/ +/*subraster *rastcat();*/ /* concat lp||sp||rp subrasters */ int family=CMSYEX, /* get_delim() family */ height=0, rheight=0, /* subexpr, right delim height */ margin=(size+1), /* delim height margin over subexpr*/ opmargin=(5); /* extra margin for \int,\sum,\etc */ char /* *texleft(),*/ subexpr[MAXSUBXSZ+1];/*chars between \left...\right*/ -char *texchar(), /* get delims after \left,\right */ +char /* *texchar(),*/ /* get delims after \left,\right */ ldelim[256]=".", rdelim[256]="."; /* delims following \left,\right */ -char *strtexchr(), *pleft, *pright; /*locate \right matching our \left*/ +char /**strtexchr(),*/ *pleft, *pright;/*locate \right matching our \left*/ int isleftdot=0, isrightdot=0; /* true if \left. or \right. */ -int isleftscript=0, isrightscript=0; /* true if delims are scripted */ +int isrightscript=0; /* true if delims are scripted */ int sublen=0; /* strlen(subexpr) */ int idelim=0; /* 1=left,2=right */ /* int gotldelim = 0; */ /* true if ildelim given by caller */ -int delete_subraster(); /* free subraster if rastleft fails*/ +/*int delete_subraster();*/ /* free subraster if rastleft fails*/ int wasdisplaystyle = isdisplaystyle; /* save current displaystyle */ int istextleft=0, istextright=0; /* true for non-displaystyle delims*/ /* --- recognized delimiters --- */ @@ -8793,7 +8542,7 @@ if ( !isleftdot ) /* if not \left. */ rheight = lheight-1; } /* make sure right delim matches */ /* --- then add on any sub/superscripts attached to \left( --- */ lp = rastlimits(&pleft,size,lp); /*\left(_a^b and push pleft past b*/ - isleftscript = isscripted; } /* check if left delim scripted */ +} isdisplaystyle = (istextright?0:9); /* force \displaystyle */ if ( !isrightdot ) /* and if not \right. */ { /* --- first get requested \right delimiter --- */ @@ -8830,43 +8579,6 @@ if ( sp != NULL ) /* succeeded or ignored \left. */ } /* --- end-of-function rastleft() --- */ -/* ========================================================================== - * Function: rastright ( expression, size, basesp, ildelim, arg2, arg3 ) - * Purpose: ...\right handler, intercepts an unexpected/unbalanced \right - * -------------------------------------------------------------------------- - * Arguments: expression (I) char ** to first char of null-terminated - * string beginning with a \right - * to be rasterized - * size (I) int containing 0-7 default font size - * basesp (I) subraster * to character (or subexpression) - * immediately preceding leading left{ - * (unused, but passed for consistency) - * ildelim (I) int containing rdelims[] index of - * right delimiter - * arg2 (I) int unused - * arg3 (I) int unused - * -------------------------------------------------------------------------- - * Returns: ( subraster * ) ptr to subraster corresponding to subexpr, - * or NULL for any parsing error - * -------------------------------------------------------------------------- - * Notes: o - * ======================================================================= */ -/* --- entry point --- */ -subraster *rastright ( char **expression, int size, subraster *basesp, - int ildelim, int arg2, int arg3 ) -{ -/* ------------------------------------------------------------------------- -Allocations and Declarations --------------------------------------------------------------------------- */ -subraster /* *rasterize(),*/ *sp=NULL; /*rasterize \right subexpr's*/ - if ( sp != NULL ) /* returning entire expression */ - { - isreplaceleft = 1; /* set flag to replace left half*/ - } -return ( sp ); -} /* --- end-of-function rastright() --- */ - - /* ========================================================================== * Function: rastmiddle ( expression, size, basesp, arg1, arg2, arg3 ) * Purpose: \middle handler, returns subraster corresponding to @@ -8891,24 +8603,24 @@ return ( sp ); * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastmiddle ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastmiddle(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *rasterize(), *sp=NULL, *subsp[32]; /*rasterize \middle subexpr's*/ +subraster /**rasterize(),*/ *sp=NULL, *subsp[32]; /*rasterize \middle subexpr*/ char *exprptr = *expression, /* local copy of ptr to expression */ - *texchar(), delim[32][132], /* delimiters following \middle's */ - *strtexchr(), /* locate \middle's */ - subexpr[MAXSUBXSZ+1], *subptr=NULL;/*subexpression between \middle's*/ + /**texchar(),*/ delim[32][132], /* delimiters following \middle's */ + /**strtexchr(),*/ /* locate \middle's */ + subexpr[MAXSUBXSZ+1], *subptr=NULL;/*subexpression between \middle's*/ int height=0, habove=0, hbelow=0; /* height, above & below baseline */ int idelim, ndelims=0, /* \middle count (max 32) */ family = CMSYEX; /* delims from CMSY10 or CMEX10 */ -subraster *subrastcpy(), /* copy subraster */ - *rastcat(), /* concatanate subraster */ - *get_delim(); /* get rasterized delimiter */ -int delete_subraster(); /* free work area subsp[]'s at eoj */ +/*subraster *subrastcpy(),*/ /* copy subraster */ +/* *rastcat(),*/ /* concatanate subraster */ +/* *get_delim();*/ /* get rasterized delimiter */ +/*int delete_subraster();*/ /* free work area subsp[]'s at eoj */ /* ------------------------------------------------------------------------- initialization -------------------------------------------------------------------------- */ @@ -8935,9 +8647,8 @@ while ( ndelims < 30 ) /* max of 31 \middle's */ subsp[ndelims] = NULL; /* no subexpresion yet */ if ( *exprptr == '\000' ) /* end-of-expression after \delim */ break; /* so we have all subexpressions */ - if ( (subptr = strtexchr(exprptr,"\\middle")) /* find next \middle */ - == NULL ) /* no more \middle's */ - { strncpy(subexpr,exprptr,MAXSUBXSZ); /*get entire remaining expression*/ + if ( (subptr = strtexchr(exprptr,"\\middle")) /* find next \middle */ + == NULL ) /* no more \middle's */ { strncpy(subexpr,exprptr,MAXSUBXSZ); /*get entire remaining expression*/ subexpr[MAXSUBXSZ] = '\000'; /* make sure it's null-terminated */ exprptr += strlen(exprptr); } /* push exprptr to terminating '\0'*/ else /* have another \middle */ @@ -9009,13 +8720,13 @@ for ( idelim=0; idelim<=ndelims; idelim++ ) * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastflags ( char **expression, int size, subraster *basesp, - int flag, int value, int arg3 ) +FUNCSCOPE subraster *rastflags(char **expression, int size, subraster *basesp, + int flag, int value, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), /* parse expression for... */ +char /**texsubexpr(),*/ /* parse expression for... */ valuearg[1024]="NOVALUE"; /* value from expression, if needed */ int argvalue=NOVALUE, /* atoi(valuearg) */ isdelta=0, /* true if + or - precedes valuearg */ @@ -9126,7 +8837,7 @@ switch ( flag ) else /* embed font size in expression */ { sprintf(valuearg,"%d",fontsize); /* convert size */ valuelen = strlen(valuearg); /* ought to be 1 */ - if ( *expression != '\000' ) /* ill-formed expression */ + if ( **expression != '\000' ) /* ill-formed expression */ { *expression = (char *)(*expression-valuelen); /*back up buff*/ memcpy(*expression,valuearg,valuelen); } } /*and put in size*/ break; @@ -9263,23 +8974,23 @@ return ( NULL ); /*just set value, nothing to display*/ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastspace ( char **expression, int size, subraster *basesp, - int width, int isfill, int isheight ) +FUNCSCOPE subraster *rastspace(char **expression, int size, subraster *basesp, + int width, int isfill, int isheight) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *new_subraster(), *spacesp=NULL; /* subraster for space */ -raster *bp=NULL, *backspace_raster(); /* for negative space */ -int delete_subraster(); /* if fail, free unneeded subraster*/ +subraster /**new_subraster(),*/ *spacesp=NULL; /* subraster for space */ +raster *bp=NULL /*, *backspace_raster()*/; /* for negative space */ +/*int delete_subraster();*/ /* if fail, free unneeded subraster*/ int baseht=1, baseln=0; /* height,baseline of base symbol */ int pixsz = 1; /*default #bits per pixel, 1=bitmap*/ int isstar=0, minspace=0; /* defaults for negative hspace */ int maxwidth = 2047; /* max width of expression in pixels*/ -char *texsubexpr(), widtharg[256]; /* parse for optional {width} */ -int evalterm(), evalue=0; /* evaluate [args], {args} */ -subraster *rasterize(), *rightsp=NULL; /*rasterize right half of expression*/ -subraster *rastcat(); /* cat rightsp after \hfill */ +char /**texsubexpr(),*/ widtharg[256]; /* parse for optional {width} */ +int /*evalterm(),*/ evalue=0; /* evaluate [args], {args} */ +subraster /**rasterize(),*/ *rightsp=NULL; /*rasterize right half of expresn*/ +/*subraster *rastcat();*/ /* cat rightsp after \hfill */ /* ------------------------------------------------------------------------- initialization -------------------------------------------------------------------------- */ @@ -9397,16 +9108,16 @@ if ( rightsp != NULL ) /* we have a right half after fill */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastnewline ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastnewline ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *rastack(), *newlsp=NULL; /* subraster for both lines */ -subraster *rasterize(), *rightsp=NULL; /*rasterize right half of expression*/ -char *texsubexpr(), spacexpr[129]/*, *xptr=spacexpr*/; /*for \\[vspace]*/ -int evalterm(), evalue=0; /* evaluate [arg], {arg} */ +subraster /**rastack(),*/ *newlsp=NULL; /* subraster for both lines */ +subraster /**rasterize(),*/ *rightsp=NULL; /*rasterize right half of expresn*/ +char /**texsubexpr(),*/ spacexpr[129]/*, *xptr=spacexpr*/; /*for\\[vspace]*/ +int /*evalterm(),*/ evalue=0; /* evaluate [arg], {arg} */ int vspace = size+2; /* #pixels between lines */ /* ------------------------------------------------------------------------- obtain optional [vspace] argument immediately following \\ command @@ -9472,19 +9183,19 @@ newlsp = rastack(rightsp,leftexpression,1,vspace,0,1); /*right under left*/ * In text mode use two spaces {\rm~[f]\longrightarrow~~[g]}. * ======================================================================= */ /* --- entry point --- */ -subraster *rastarrow ( char **expression, int size, subraster *basesp, - int drctn, int isBig, int arg3 ) +FUNCSCOPE subraster *rastarrow(char **expression, int size, subraster *basesp, + int drctn, int isBig, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *arrow_subraster(), *arrowsp=NULL; /* subraster for arrow */ -char *texsubexpr(), widtharg[256]; /* parse for optional [width] */ -char *texscripts(), sub[1024],super[1024]; /* and _^limits after [width]*/ -subraster *rasterize(), *subsp=NULL,*supsp=NULL; /*rasterize limits*/ -subraster *new_subraster(), *rastack(), *spacesp=NULL; /*space below arrow*/ -int delete_subraster(); /*free work areas in case of error*/ -int evalterm(); /* evaluate [arg], {arg} */ +subraster /**arrow_subraster(),*/ *arrowsp=NULL; /* subraster for arrow */ +char /**texsubexpr(),*/ widtharg[256]; /* parse for optional [width] */ +char /**texscripts(),*/ sub[1024],super[1024];/*and _^limits after [width]*/ +subraster /**rasterize(),*/ *subsp=NULL,*supsp=NULL; /*rasterize limits*/ +subraster /**new_subraster(), *rastack(),*/ *spacesp=NULL;/*space below arrow*/ +/*int delete_subraster();*/ /*free work areas in case of error*/ +/*int evalterm();*/ /* evaluate [arg], {arg} */ int width = 10 + 8*size, height; /* width, height for \longxxxarrow */ int maxwidth = 1024; /* max arrow width in pixels */ int islimits = 1; /*true to handle limits internally*/ @@ -9568,18 +9279,18 @@ if ( supsp != NULL ) /* stack superscript above arrow */ * In text use two spaces {\rm~[f]\longuparrow~~[g]}. * ======================================================================= */ /* --- entry point --- */ -subraster *rastuparrow ( char **expression, int size, subraster *basesp, - int drctn, int isBig, int arg3 ) +FUNCSCOPE subraster *rastuparrow ( char **expression, int size, + subraster *basesp, int drctn, int isBig, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -subraster *uparrow_subraster(), *arrowsp=NULL; /* subraster for arrow */ -char *texsubexpr(), heightarg[256]; /* parse for optional [height] */ -char *texscripts(), sub[1024],super[1024]; /* and _^limits after [width]*/ -subraster *rasterize(), *subsp=NULL,*supsp=NULL; /*rasterize limits*/ -subraster *rastcat(); /* cat superscript left, sub right */ -int evalterm(); /* evaluate [arg], {arg} */ +subraster /**uparrow_subraster(),*/ *arrowsp=NULL; /* subraster for arrow */ +char /**texsubexpr(),*/ heightarg[256]; /* parse for optional [height] */ +char /**texscripts(),*/ sub[1024],super[1024]; /*and _^limits after[width]*/ +subraster /**rasterize(),*/ *subsp=NULL,*supsp=NULL; /*rasterize limits*/ +/*subraster *rastcat();*/ /* cat superscript left, sub right */ +/*int evalterm();*/ /* evaluate [arg], {arg} */ int height = 8 + 2*size, width; /* height, width for \longxxxarrow */ int maxheight = 800; /* max arrow height in pixels */ int islimits = 1; /*true to handle limits internally*/ @@ -9665,20 +9376,20 @@ if ( subsp != NULL ) /* cat subscript to right of arrow */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastoverlay ( char **expression, int size, subraster *basesp, - int overlay, int offset2, int arg3 ) +FUNCSCOPE subraster *rastoverlay ( char **expression, int size, + subraster *basesp, int overlay, int offset2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), /*parse expression for base,overlay*/ +char /**texsubexpr(),*/ /*parse expression for base,overlay*/ expr1[512], expr2[512]; /* base, overlay */ -subraster *rasterize(), *sp1=NULL, *sp2=NULL, /*rasterize 1=base, 2=overlay*/ - *new_subraster(); /*explicitly alloc sp2 if necessary*/ -subraster *rastcompose(), *overlaysp=NULL; /*subraster for composite overlay*/ +subraster /**rasterize(),*/ *sp1=NULL, *sp2=NULL /*rasterize 1=base,2=overlay*/ + /*,*new_subraster()*/; /*explicitly alloc sp2 if necessary*/ +subraster /**rastcompose(),*/ *overlaysp=NULL;/*subrast for composite overlay*/ int isalign = 0; /* true to align baselines */ -int line_raster(); /* draw diagonal for \Not */ -int evalterm(); /* evaluate [arg], {arg} */ +/*int line_raster();*/ /* draw diagonal for \Not */ +/*int evalterm();*/ /* evaluate [arg], {arg} */ /* ------------------------------------------------------------------------- Obtain base, and maybe overlay, and rasterize them -------------------------------------------------------------------------- */ @@ -9779,26 +9490,25 @@ overlaysp = rastcompose(sp1,sp2,offset2,isalign,3); * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastfrac ( char **expression, int size, subraster *basesp, - int isfrac, int arg2, int arg3 ) +FUNCSCOPE subraster *rastfrac(char **expression, int size, subraster *basesp, + int isfrac, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), /*parse expression for numer,denom*/ +char /**texsubexpr(),*/ /*parse expression for numer,denom*/ numer[MAXSUBXSZ+1], denom[MAXSUBXSZ+1]; /* parsed numer, denom */ -subraster *rasterize(), *numsp=NULL, *densp=NULL; /*rasterize numer, denom*/ -subraster *rastack(), *fracsp=NULL; /* subraster for numer/denom */ -subraster *new_subraster()/*, *spacesp=NULL*/; /* space for num or den */ +subraster /**rasterize(),*/ *numsp=NULL, *densp=NULL;/*rasterize numer,denom*/ +subraster /**rastack(),*/ *fracsp=NULL; /* subraster for numer/denom */ +/*subraster *new_subraster(), *spacesp=NULL;*/ /* space for num or den */ int width=0, /* width of constructed raster */ numheight=0; /* height of numerator */ -int baseht=0, baseln=0; /* height,baseline of base symbol */ /*int istweak = 1;*/ /*true to tweak baseline alignment*/ -int rule_raster(), /* draw horizontal line for frac */ +int /*rule_raster(),*/ /* draw horizontal line for frac */ lineheight = (isfrac?1:0); /* thickness of fraction line */ int vspace = (size>2?2:1); /*vertical space between components*/ -int delete_subraster(); /*free work areas in case of error*/ -int type_raster(); /* display debugging output */ +/*int delete_subraster();*/ /*free work areas in case of error*/ +/*int type_raster();*/ /* display debugging output */ /* ------------------------------------------------------------------------- Obtain numerator and denominator, and rasterize them -------------------------------------------------------------------------- */ @@ -9868,10 +9578,6 @@ width = (fracsp->image)->width; /*just get width of embedded image*/ fracsp->size = size; /* propagate font size forward */ fracsp->baseline = (numheight+vspace+lineheight)+(size+2);/*default baseline*/ fracsp->type = FRACRASTER; /* signal \frac image */ -if ( basesp != (subraster *)NULL ) /* we have base symbol for frac */ - { baseht = (basesp->image)->height; /* height of base symbol */ - baseln = basesp->baseline; /* and its baseline */ - } /* --- end-of-if(basesp!=NULL) --- */ /* ------------------------------------------------------------------------- draw horizontal line between numerator and denominator -------------------------------------------------------------------------- */ @@ -9914,20 +9620,20 @@ return final result to caller * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastackrel ( char **expression, int size, subraster *basesp, - int base, int arg2, int arg3 ) +FUNCSCOPE subraster *rastackrel ( char **expression, int size, + subraster *basesp, int base, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), /*parse expression for upper,lower*/ +char /**texsubexpr(),*/ /*parse expression for upper,lower*/ upper[MAXSUBXSZ+1], lower[MAXSUBXSZ+1]; /* parsed upper, lower */ -subraster *rasterize(), *upsp=NULL, *lowsp=NULL; /* rasterize upper, lower */ -subraster *rastack(), *relsp=NULL; /* subraster for upper/lower */ +subraster /**rasterize(),*/ *upsp=NULL, *lowsp=NULL; /*rasterize upper,lower*/ +subraster /**rastack(),*/ *relsp=NULL; /* subraster for upper/lower */ int upsize = (base==1? size:size-1), /* font size for upper component */ lowsize = (base==2? size:size-1); /* font size for lower component */ int vspace = 1; /*vertical space between components*/ -int delete_subraster(); /*free work areas in case of error*/ +/*int delete_subraster();*/ /*free work areas in case of error*/ /* ------------------------------------------------------------------------- Obtain numerator and denominator, and rasterize them -------------------------------------------------------------------------- */ @@ -9986,21 +9692,21 @@ return final result to caller * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastmathfunc ( char **expression, int size, subraster *basesp, - int mathfunc, int islimits, int arg3 ) +FUNCSCOPE subraster *rastmathfunc ( char **expression, int size, + subraster *basesp, int mathfunc, int islimits, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texscripts(), /* parse expression for _limits */ +char /**texscripts(),*/ /* parse expression for _limits */ func[MAXTOKNSZ+1], limits[MAXSUBXSZ+1]; /*func as {\rm func}, limits*/ -char *texsubexpr(), /* parse expression for arg */ +char /**texsubexpr(),*/ /* parse expression for arg */ funcarg[MAXTOKNSZ+1]; /* optional func arg */ -subraster *rasterize(), *funcsp=NULL, *limsp=NULL; /*rasterize func,limits*/ -subraster *rastack(), *mathfuncsp=NULL; /* subraster for mathfunc/limits */ +subraster /**rasterize(),*/ *funcsp=NULL, *limsp=NULL;/*rasterize func,limits*/ +subraster /**rastack(),*/ *mathfuncsp=NULL; /*subraster for mathfunc/limits*/ int limsize = size-1; /* font size for limits */ int vspace = 1; /*vertical space between components*/ -int delete_subraster(); /*free work areas in case of error*/ +/*int delete_subraster();*/ /*free work areas in case of error*/ /* --- table of function names by mathfunc number --- */ static int numnames = 34; /* number of names in table */ static char *funcnames[] = { @@ -10093,23 +9799,23 @@ return final result to caller * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastsqrt ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastsqrt(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], /*parse subexpr to be sqrt-ed*/ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1],/*parse subexpr to be sqrt-ed*/ rootarg[MAXSUBXSZ+1]; /* optional \sqrt[rootarg]{...} */ -subraster *rasterize(), *subsp=NULL; /* rasterize subexpr */ -subraster *accent_subraster(), *sqrtsp=NULL, /* subraster with the sqrt */ - *new_subraster(), *rootsp=NULL; /* optionally preceded by [rootarg]*/ +subraster /**rasterize(),*/ *subsp=NULL; /* rasterize subexpr */ +subraster /**accent_subraster(),*/ *sqrtsp=NULL, /* subraster with the sqrt */ + /**new_subraster(),*/ *rootsp=NULL;/*optionally preceded by [rootarg]*/ int sqrtheight=0, sqrtwidth=0, surdwidth=0, /* height,width of sqrt */ rootheight=0, rootwidth=0, /* height,width of rootarg raster */ subheight=0, subwidth=0, pixsz=0; /* height,width,pixsz of subexpr */ -int rastput(); /* put subexpr in constructed sqrt */ +/*int rastput();*/ /* put subexpr in constructed sqrt */ int overspace = 2; /*space between subexpr and overbar*/ -int delete_subraster(); /* free work areas */ +/*int delete_subraster();*/ /* free work areas */ /* ------------------------------------------------------------------------- Obtain subexpression to be sqrt-ed, and rasterize it -------------------------------------------------------------------------- */ @@ -10138,7 +9844,7 @@ subwidth = (subsp->image)->width; /* and its width */ pixsz = (subsp->image)->pixsz; /* pixsz remains constant */ /* --- determine height and width of sqrt to contain subexpr --- */ sqrtheight = subheight + overspace; /* subexpr + blank line + overbar */ -surdwidth = SQRTWIDTH(sqrtheight,(rootheight<1?2:1)); /* width of surd */ +surdwidth = (int)(SQRTWIDTH(sqrtheight,(rootheight<1?2:1))); /* width of surd */ sqrtwidth = subwidth + surdwidth + 1; /* total width */ /* ------------------------------------------------------------------------- construct sqrt (with room to move in subexpr) and embed subexpr in it @@ -10210,21 +9916,21 @@ free unneeded component subrasters and return final result to caller * of isabove and isscript args. * ======================================================================= */ /* --- entry point --- */ -subraster *rastaccent ( char **expression, int size, subraster *basesp, - int accent, int isabove, int isscript ) +FUNCSCOPE subraster *rastaccent ( char **expression, int size, + subraster *basesp, int accent, int isabove, int isscript ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1]; /*parse subexpr to be accented*/ -char *texscripts(), *script=NULL, /* \under,overbrace allow scripts */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1];/*parse subexp to be accented*/ +char /**texscripts(),*/ *script=NULL, /* \under,overbrace allow scripts */ subscript[MAXTOKNSZ+1], supscript[MAXTOKNSZ+1]; /* parsed scripts */ -subraster *rasterize(), *subsp=NULL, *scrsp=NULL; /*rasterize subexpr,script*/ -subraster *rastack(), *accsubsp=NULL; /* stack accent, subexpr, script */ -subraster *accent_subraster(), *accsp=NULL; /*raster for the accent itself*/ +subraster /**rasterize(),*/ *subsp=NULL,*scrsp=NULL;/*rasterize subexp,script*/ +subraster /**rastack(),*/ *accsubsp=NULL; /* stack accent, subexpr, script */ +subraster /**accent_subraster(),*/ *accsp=NULL;/*raster for the accent itself*/ int accheight=0, accwidth=0, accdir=0,/*accent height, width, direction*/ subheight=0, subwidth=0, pixsz=0; /* height,width,pixsz of subexpr */ -int delete_subraster(); /*free work areas in case of error*/ +/*int delete_subraster();*/ /*free work areas in case of error*/ int vspace = 0; /*vertical space between accent,sub*/ /* ------------------------------------------------------------------------- Obtain subexpression to be accented, and rasterize it @@ -10255,6 +9961,7 @@ switch ( accent ) vspace = 1; /* set 1-pixel vertical space */ accdir = isscript; /* +1=right,-1=left,0=lr; +10for==>*/ isscript = 0; /* >>don't<< signal sub/supscript */ + /* FALLTHRU */ case HATACCENT: accheight = 7; /* default */ if ( subwidth < 10 ) accheight = 5; /* unless small width */ @@ -10323,21 +10030,20 @@ return final result to caller * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastfont ( char **expression, int size, subraster *basesp, - int ifontnum, int arg2, int arg3 ) +FUNCSCOPE subraster *rastfont(char **expression, int size, subraster *basesp, + int ifontnum, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), fontchars[MAXSUBXSZ+1], /* chars to render in font */ +char /**texsubexpr(),*/ fontchars[MAXSUBXSZ+1], /*chars to render in font*/ subexpr[MAXSUBXSZ+1]; /* turn \cal{AB} into \calA\calB */ char *pfchars=fontchars, fchar='\0'; /* run thru fontchars one at a time*/ char *name = NULL; /* fontinfo[ifontnum].name */ -int family = 0, /* fontinfo[ifontnum].family */ - istext = 0, /* fontinfo[ifontnum].istext */ +int istext = 0, /* fontinfo[ifontnum].istext */ class = 0; /* fontinfo[ifontnum].class */ -subraster *rasterize(), *fontsp=NULL, /* rasterize chars in font */ - *rastflags(); /* or just set flag to switch font */ +subraster /**rasterize(),*/ *fontsp=NULL /* rasterize chars in font */ + /*,*rastflags()*/; /* or just set flag to switch font */ int oldsmashmargin = smashmargin; /* turn off smash in text mode */ #if 0 /* --- fonts recognized by rastfont --- */ @@ -10365,7 +10071,6 @@ first get font name and class to determine type of conversion desired -------------------------------------------------------------------------- */ if (ifontnum<=0 || ifontnum>nfontinfo) ifontnum=0; /*math if out-of-bounds*/ name = fontinfo[ifontnum].name; /* font name */ -family = fontinfo[ifontnum].family; /* font family */ istext = fontinfo[ifontnum].istext; /*true in text mode (respect space)*/ class = fontinfo[ifontnum].class; /* font class */ if ( istext ) /* text (respect blanks) */ @@ -10487,19 +10192,19 @@ back to caller with chars rendered in font * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastbegin ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastbegin(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], /* \begin{} environment params*/ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1],/*\begin{} environment params*/ *exprptr=NULL,*begptr=NULL,*endptr=NULL,*braceptr=NULL; /* ptrs */ char *begtoken="\\begin{", *endtoken="\\end{"; /*tokens we're looking for*/ -int strreplace(); /* replace substring in string */ -char *strchange(); /*\begin...\end --> {\begin...\end}*/ +/*int strreplace();*/ /* replace substring in string */ +/*char *strchange();*/ /*\begin...\end --> {\begin...\end}*/ char *delims = (char *)NULL; /* mdelims[ienviron] */ -subraster *rasterize(), *sp=NULL; /* rasterize environment */ +subraster /**rasterize(),*/ *sp=NULL; /* rasterize environment */ int ienviron = 0; /* environs[] index */ int nbegins = 0; /* #\begins nested beneath this one*/ int envlen=0, sublen=0; /* #chars in environ, subexpr */ @@ -10732,16 +10437,16 @@ sp = rasterize(subexpr,size); /* rasterize subexpr */ * default justification is c(entered) and B(aseline). * ======================================================================= */ /* --- entry point --- */ -subraster *rastarray ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastarray(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], *exprptr, /*parse array subexpr*/ - subtok[MAXTOKNSZ+1], *subptr=subtok, /* &,\\ inside { } not a delim*/ +char /**texsubexpr(),*/subexpr[MAXSUBXSZ+1],*exprptr,/*parse array subexpr*/ + subtok[MAXTOKNSZ+1], /* &,\\ inside { } not a delim*/ token[MAXTOKNSZ+1], *tokptr=token, /* subexpr token to rasterize */ - *preamble(), *preptr=token; /*process optional size,lcr preamble*/ + /**preamble(),*/ *preptr=token; /*process optional size,lcr preamble*/ char *coldelim="&", *rowdelim="\\"; /* need escaped rowdelim */ int maxarraysz = 63; /* max #rows, cols */ int justify[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* -1,0,+1 = l,c,r */ @@ -10804,22 +10509,22 @@ int itoken, ntokens=0, /* index, total #tokens in array */ int isescape=0,wasescape=0, /* current,prev chars escape? */ ischarescaped=0, /* is current char escaped? */ nescapes=0; /* #consecutive escapes */ -subraster *rasterize(), *toksp[1025], /* rasterize tokens */ - *new_subraster(), *arraysp=NULL; /* subraster for entire array */ +subraster /**rasterize(),*/ *toksp[1025], /* rasterize tokens */ + /**new_subraster(),*/ *arraysp=NULL; /* subraster for entire array */ raster *arrayrp=NULL; /* raster for entire array */ -int delete_subraster(); /* free toksp[] workspace at eoj */ +/*int delete_subraster();*/ /* free toksp[] workspace at eoj */ int rowspace=2, colspace=4, /* blank space between rows, cols */ hspace=1, vspace=1; /*space to accommodate hline,vline*/ int width=0, height=0, /* width,height of array */ leftcol=0, toprow=0; /*upper-left corner for cell in it*/ int rastput(); /* embed tokens/cells in array */ -int rule_raster(); /* draw hlines and vlines in array */ +/*int rule_raster();*/ /* draw hlines and vlines in array */ char *hlchar="\\hline", *hdchar="\\hdash"; /* token signals hline */ -char *texchar(), hltoken[1025]; /* extract \hline from token */ +char /**texchar(),*/ hltoken[1025]; /* extract \hline from token */ int ishonly=0, hltoklen, minhltoklen=3; /*flag, token must be \hl or \hd*/ int isnewrow=1; /* true for new row */ int pixsz = 1; /*default #bits per pixel, 1=bitmap*/ -int evalterm(), evalue=0; /* evaluate [arg], {arg} */ +int /*evalterm(),*/ evalue=0; /* evaluate [arg], {arg} */ static int mydaemonlevel = 0; /* check against global daemonlevel*/ /* ------------------------------------------------------------------------- Macros to determine extra raster space required for vline/hline @@ -10876,18 +10581,22 @@ while ( *preptr != '\000' ) /* check preamble text for lcr */ switch ( /*tolower*/(prepchar) ) { default: break; /* just flush unrecognized chars */ case 'l': justify[icol] = (-1); /*left-justify this column*/ - if (colglobal) gjustify[irow] = justify[irow]; break; + if (colglobal) gjustify[irow] = justify[irow]; + break; case 'c': justify[icol] = (0); /* center this column */ - if (colglobal) gjustify[irow] = justify[irow]; break; + if (colglobal) gjustify[irow] = justify[irow]; + break; case 'r': justify[icol] = (+1); /* right-justify this col */ - if (colglobal) gjustify[irow] = justify[irow]; break; + if (colglobal) gjustify[irow] = justify[irow]; + break; case '|': vline[icol] += 1; break; /* solid vline left of col */ case '.': vline[icol] = (-1); break; /*dashed vline left of col */ case 'b': prepchar='B'; prepcase=2; /* alias for B */ case 'B': break; /* baseline-justify row */ - case 'v': prepchar='C'; prepcase=2; /* alias for C */ + case 'v': prepchar='C'; prepcase=2; /* FALLTHRU */ /* alias for C */ case 'C': rowcenter[irow] = 1; /* vertically center row */ - if (rowglobal) growcenter[irow] = rowcenter[irow]; break; + if (rowglobal) growcenter[irow] = rowcenter[irow]; + break; case 'g': colglobal=1; prepcase=0; break; /* set global col values */ case 'G': rowglobal=1; prepcase=0; break; /* set global row values */ case '#': colglobal=rowglobal=1; break; } /* set global col,row vals */ @@ -10973,7 +10682,7 @@ while ( 1 ) /* scan chars till end */ if ( *exprptr == '{' /* start of {...} subexpression */ && !ischarescaped ) /* if not escaped \{ */ { - subptr = texsubexpr(exprptr,subtok,4095,"{","}",1,1); /*entire subexpr*/ + texsubexpr(exprptr,subtok,4095,"{","}",1,1); /*entire subexpr*/ subtoklen = strlen(subtok); /* #chars in {...} */ memcpy(tokptr,exprptr,subtoklen); /* copy {...} to accumulated token */ tokptr += subtoklen; /* bump tokptr to end of token */ @@ -11245,21 +10954,21 @@ free workspace and return final result to caller * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastpicture ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastpicture ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), picexpr[2049], *picptr=picexpr, /* picture {expre} */ +char /**texsubexpr(),*/ picexpr[2049], *picptr=picexpr, /*picture {expre}*/ putexpr[256], *putptr,*multptr, /*[multi]put (x,y[;xinc,yinc;num])*/ pream[96], *preptr, /* optional put preamble */ picelem[1025]; /* picture element following put */ -subraster *rasterize(), *picelemsp=NULL, /* rasterize picture elements */ - *new_subraster(), *picturesp=NULL, /* subraster for entire picture */ +subraster /**rasterize(),*/ *picelemsp=NULL, /* rasterize picture elements */ + /**new_subraster(),*/ *picturesp=NULL, /*subraster for entire picture*/ *oldworkingbox = workingbox; /* save working box on entry */ raster *picturerp=NULL; /* raster for entire picture */ -int delete_subraster(); /* free picelemsp[] workspace */ +/*int delete_subraster();*/ /* free picelemsp[] workspace */ int pixsz = 1; /* pixels are one bit each */ double x=0.0,y=0.0, /* x,y-coords for put,multiput*/ xinc=0.0,yinc=0.0; /* x,y-incrementss for multiput*/ @@ -11268,12 +10977,12 @@ int width=0, height=0, /* #pixels width,height of picture */ maxwidth=1600, maxheight=1600, /* max width,height in pixels */ ix=0,xpos=0, iy=0,ypos=0, /* mimeTeX x,y pixel coords */ num=1, inum; /* number reps, index of element */ -int evalterm(); /* evaluate [arg] and {arg}'s */ +/*int evalterm();*/ /* evaluate [arg] and {arg}'s */ int iscenter=0; /* center or lowerleft put position*/ int *oldworkingparam = workingparam, /* save working param on entry */ origin = 0; /* x,yinc ++=00 +-=01 -+=10 --=11 */ -int rastput(); /* embed elements in picture */ -int type_raster(); /* display debugging output */ +/*int rastput();*/ /* embed elements in picture */ +/*int type_raster();*/ /* display debugging output */ /* ------------------------------------------------------------------------- First obtain (width,height) arguments immediately following \picture command -------------------------------------------------------------------------- */ @@ -11466,14 +11175,14 @@ return picture constructed from pic_elements to caller * o if {xlen} not given, then it's assumed xlen = |xinc| * ======================================================================= */ /* --- entry point --- */ -subraster *rastline ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastline(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(),linexpr[257], *xptr=linexpr; /*line(xinc,yinc){xlen}*/ -subraster *new_subraster(), *linesp=NULL; /* subraster for line */ +char /**texsubexpr(),*/linexpr[257], *xptr=linexpr;/*line(xinc,yinc){xlen}*/ +subraster /**new_subraster(),*/ *linesp=NULL; /* subraster for line */ /*char *origexpression = *expression;*/ /*original expression after \line*/ int pixsz = 1; /* pixels are one bit each */ int thickness = 1; /* line thickness */ @@ -11482,10 +11191,10 @@ double xinc=0.0, yinc=0.0, /* x,y-increments for line, */ int width=0, height=0, /* #pixels width,height of line */ maxwidth=1600, maxheight=1600, /* max width,height in pixels */ rwidth=0, rheight=0; /*alloc width,height plus thickness*/ -int evalterm(); /* evaluate [arg] and {arg}'s */ +/*int evalterm();*/ /* evaluate [arg] and {arg}'s */ int istop=0, isright=0, /* origin at bot-left if x,yinc>=0 */ origin = 0; /* x,yinc: ++=00 +-=01 -+=10 --=11 */ -int line_raster(); /* draw line in linesp->image */ +/*int line_raster();*/ /* draw line in linesp->image */ /* ------------------------------------------------------------------------- obtain (xinc,yinc) arguments immediately following \line command -------------------------------------------------------------------------- */ @@ -11596,21 +11305,21 @@ return constructed line to caller * o if width=0 then you get an invisible strut 1 (one) pixel wide * ======================================================================= */ /* --- entry point --- */ -subraster *rastrule ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastrule(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), rulexpr[257]; /* rule[lift]{wdth}{hgt} */ -subraster *new_subraster(), *rulesp=NULL; /* subraster for rule */ +char /**texsubexpr(),*/ rulexpr[257]; /* rule[lift]{wdth}{hgt} */ +subraster /**new_subraster(),*/ *rulesp=NULL; /* subraster for rule */ int pixsz = 1; /* pixels are one bit each */ int lift=0, width=0, height=0; /* default rule parameters */ double dval; /* convert ascii params to doubles */ int rwidth=0, rheight=0, /* alloc width, height plus lift */ maxwidth=1600, maxheight=1600; /* max width,height in pixels */ -int rule_raster(); /* draw rule in rulesp->image */ -int evalterm(); /* evaluate args */ +/*int rule_raster();*/ /* draw rule in rulesp->image */ +/*int evalterm();*/ /* evaluate args */ /* ------------------------------------------------------------------------- Obtain lift,width,height -------------------------------------------------------------------------- */ @@ -11692,25 +11401,25 @@ return constructed rule to caller * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastcircle ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastcircle ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), circexpr[512],*xptr=circexpr; /*circle(xdiam[,ydiam])*/ +char /**texsubexpr(),*/circexpr[512],*xptr=circexpr;/*circle(xdiam[,ydiam])*/ char *qptr=NULL, quads[256]="1234"; /* default to draw all quadrants */ double theta0=0.0, theta1=0.0; /* ;theta0,theta1 instead of ;quads*/ -subraster *new_subraster(), *circsp=NULL; /* subraster for ellipse */ +subraster /**new_subraster(),*/ *circsp=NULL; /* subraster for ellipse */ int pixsz = 1; /* pixels are one bit each */ double xdiam=0.0, ydiam=0.0; /* x,y major/minor axes/diameters */ int width=0, height=0, /* #pixels width,height of ellipse */ maxwidth=1600, maxheight=1600; /* max width,height in pixels */ int thickness = 1; /* drawn lines are one pixel thick */ -int evalterm(); /* evaluate [arg],{arg} expressions*/ +/*int evalterm();*/ /* evaluate [arg],{arg} expressions*/ int origin = 55; /* force origin centered */ -int circle_raster(), /* draw ellipse in circsp->image */ - circle_recurse(); /* for theta0,theta1 args */ +/*int circle_raster(),*/ /* draw ellipse in circsp->image */ +/* circle_recurse();*/ /* for theta0,theta1 args */ /* ------------------------------------------------------------------------- obtain (xdiam[,ydiam]) arguments immediately following \circle command -------------------------------------------------------------------------- */ @@ -11810,28 +11519,28 @@ return constructed ellipse to caller * \picture(){~(col0,row0){\bezier(col1,row1)(colt,rowt)}~} * ======================================================================= */ /* --- entry point --- */ -subraster *rastbezier ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastbezier ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ subraster *new_subraster(), *bezsp=NULL; /* subraster for bezier */ -char *texsubexpr(), bezexpr[129],*xptr=bezexpr; /*\bezier(r,c)(r,c)(r,c)*/ +char /**texsubexpr(),*/bezexpr[129],*xptr=bezexpr;/*\bezier(r,c)(r,c)(r,c)*/ double r0=0.0,c0=0.0, r1=0.0,c1=0.0, rt=0.0,ct=0.0, /* bezier points */ rmid=0.0, cmid=0.0, /* coords at parameterized midpoint*/ rmin=0.0, cmin=0.0, /* minimum r,c */ rmax=0.0, cmax=0.0, /* maximum r,c */ rdelta=0.0, cdelta=0.0, /* rmax-rmin, cmax-cmin */ r=0.0, c=0.0; /* some point */ -int evalterm(); /* evaluate [arg],{arg} expressions*/ +/*int evalterm();*/ /* evaluate [arg],{arg} expressions*/ int iarg=0; /* 0=r0,c0 1=r1,c1 2=rt,ct */ int width=0, height=0, /* dimensions of bezier raster */ maxwidth=1600, maxheight=1600; /* max width,height in pixels */ int pixsz = 1; /* pixels are one bit each */ /*int thickness = 1;*/ /* drawn lines are one pixel thick */ int origin = 0; /*c's,r's reset to lower-left origin*/ -int bezier_raster(); /* draw bezier in bezsp->image */ +/*int bezier_raster();*/ /* draw bezier in bezsp->image */ /* ------------------------------------------------------------------------- obtain (c1,r1)(ct,rt) args immediately following \bezier command -------------------------------------------------------------------------- */ @@ -11936,16 +11645,16 @@ return constructed bezier to caller * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastraise ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastraise(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], *liftexpr=subexpr; /* args */ -subraster *rasterize(), *raisesp=NULL; /* rasterize subexpr to be raised */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1], *liftexpr=subexpr; /*args*/ +subraster /**rasterize(),*/ *raisesp=NULL; /*rasterize subexpr to be raised*/ int lift=0; /* amount to raise/lower baseline */ -int evalterm(); /* evaluate [arg],{arg} expressions*/ +/*int evalterm();*/ /* evaluate [arg],{arg} expressions*/ /* ------------------------------------------------------------------------- obtain {lift} argument immediately following \raisebox command -------------------------------------------------------------------------- */ @@ -12001,21 +11710,21 @@ rastlift = lift; /* set global to signal adjustment */ * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastrotate ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastrotate ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], *degexpr=subexpr; /* args */ -subraster *rasterize(), *rotsp=NULL; /* subraster for rotated subexpr */ -raster *rastrot(), *rotrp=NULL; /* rotate subraster->image 90 degs */ -int delete_raster(); /* delete intermediate rasters */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1], *degexpr=subexpr; /*args*/ +subraster /**rasterize(),*/ *rotsp=NULL; /* subraster for rotated subexpr */ +raster /**rastrot(),*/ *rotrp=NULL; /* rotate subraster->image 90 degs */ +/*int delete_raster();*/ /* delete intermediate rasters */ int baseline=0; /* baseline of rasterized image */ double degrees=0.0, ipart,fpart; /* degrees to be rotated */ int idegrees=0, isneg=0; /* positive ipart, isneg=1 if neg */ int n90=0, isn90=1; /* degrees is n90 multiples of 90 */ -int evalterm(); /* evaluate [arg],{arg} expressions*/ +/*int evalterm();*/ /* evaluate [arg],{arg} expressions*/ /* ------------------------------------------------------------------------- obtain {degrees} argument immediately following \rotatebox command -------------------------------------------------------------------------- */ @@ -12113,17 +11822,17 @@ if ( rotrp != NULL ) /* rotated raster constructed okay */ * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastmagnify ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastmagnify ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], *magexpr=subexpr; /* args */ -subraster *rasterize(), *magsp=NULL; /* subraster for magnified subexpr */ -raster *rastmag(), *magrp=NULL; /* magnify subraster->image */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1], *magexpr=subexpr; /* args */ +subraster /**rasterize(),*/ *magsp=NULL; /* subraster for magnified subexpr */ +raster /**rastmag(),*/ *magrp=NULL; /* magnify subraster->image */ int magstep = 1; /* default magnification */ -int delete_raster(); /* delete intermediate raster */ +/*int delete_raster();*/ /* delete intermediate raster */ int baseline=0; /* baseline of rasterized image */ /* ------------------------------------------------------------------------- obtain {magstep} argument immediately following \magnify command @@ -12191,17 +11900,17 @@ magsp->baseline = baseline; /*reset baseline of magnified image*/ * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastreflect ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastreflect ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], *axisexpr=subexpr; /* args */ -subraster *rasterize(), *refsp=NULL; /* subraster for reflected subexpr */ -raster *rastref(), *refrp=NULL; /* reflect subraster->image */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1], *axisexpr=subexpr; /* args */ +subraster /**rasterize(),*/ *refsp=NULL; /* subraster for reflected subexpr */ +raster /**rastref(),*/ *refrp=NULL; /* reflect subraster->image */ int axis = 1; /* default horizontal reflection */ -int delete_raster(); /* delete intermediate raster */ +/*int delete_raster();*/ /* delete intermediate raster */ int baseline=0; /* baseline of rasterized image */ /* ------------------------------------------------------------------------- obtain [axis] argument immediately following \reflectbox command, if given @@ -12268,16 +11977,16 @@ refsp->baseline = baseline; /* reset baseline of reflected image*/ * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastfbox ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastfbox(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], widtharg[512]; /* args */ -subraster *rasterize(), *framesp=NULL; /* rasterize subexpr to be framed */ -raster *border_raster(), *bp=NULL; /* framed image raster */ -int evalterm(), evalue=0; /* interpret [width][height] */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1], widtharg[512]; /* args */ +subraster /**rasterize(),*/ *framesp=NULL; /*rasterize subexpr to be framed*/ +raster /**border_raster(),*/ *bp=NULL; /* framed image raster */ +int /*evalterm(),*/ evalue=0; /* interpret [width][height] */ int fwidth=6, fthick=1, /*extra frame width, line thickness*/ fsides=0; /* frame sides: 1=left,2=top,4=right,8=bot */ int width=(-1), height=(-1), /* optional [width][height] args */ @@ -12383,17 +12092,17 @@ else * for providing info about ellipse circumscribing a rectangle * ======================================================================= */ /* --- entry point --- */ -subraster *rastovalbox ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastovalbox ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1], narg[512], /* args */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ+1], narg[512], /* args */ composexpr[MAXSUBXSZ+2048], /* compose subexpr[] with ellipse(s)*/ - ovalexpr[2048]; /* nested \compose{}{}'s */ -subraster *rasterize(), *framesp=NULL; /* rasterize subexpr to be framed */ -int delete_subraster(); /* just need width,height */ + ovalexpr[2048 + 24]; /* nested \compose{}{}'s */ +subraster /**rasterize(),*/ *framesp=NULL; /*rasterize subexpr to be oval'ed*/ +/*int delete_subraster();*/ /* just need width,height */ int fwidth = 3+size/999; /* extra frame width */ int width=(-1), height=(-1), /* width,height of subexpr[] */ origheight = (-1), /* original subexpr[] height */ @@ -12459,7 +12168,7 @@ construct nested \compose{\compose{\circle(,)}{\circle(,)}}{\circle(,)} -------------------------------------------------------------------------- */ *ovalexpr = '\000'; /* init as empty string */ for ( ioval=0; iovalbaseline = baseline; /* reset baseline (I hope) */ * o * ======================================================================= */ /* --- entry point --- */ -subraster *rastinput ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastinput(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), tag[1024]="\000", filename[1024]="\000"; /* args */ -subraster *rasterize(), *inputsp=NULL, /* rasterized input image */ - *read_pbm(); /* read .pbm file and make subraster image */ -int status, rastreadfile(); /* read input file */ -FILE *fp=NULL, *rastopenfile(); /* reading .pbm files locally */ +char /**texsubexpr(),*/ tag[1024]="\000", filename[1024]="\000"; /*args*/ +subraster /**rasterize(),*/ *inputsp=NULL /* rasterized input image */ + /*,*read_pbm()*/; /* read .pbm file and make subraster image */ +FILE *fp=NULL /*, *rastopenfile()*/; /* reading .pbm files locally */ int format=0, npts=0, /* don't reformat (numerical) input */ ispbm = 0; /* set true for \input[pbm]{filename.pbm} */ double sf = 0.0; /* shrink factor (0 or 1 means don't shrink)*/ int isinput = (seclevel<=inputseclevel?1:0); /*true if \input permitted*/ /*int evalterm();*/ /* evaluate expressions */ char *inputpath = INPUTPATH; /* permitted \input{} paths for any user */ -int isstrstr(); /* search for valid inputpath in filename */ +/*int isstrstr();*/ /* search for valid inputpath in filename */ char subexpr[MAXFILESZ+1] = "\000", /*concatanated lines from input file*/ - *mimeprep(), /* preprocess inputted data */ - *dbltoa(), *reformat=NULL; /* reformat numerical input */ + /**mimeprep(),*/ /* preprocess inputted data */ + /**dbltoa(),*/ *reformat=NULL; /* reformat numerical input */ /* ------------------------------------------------------------------------- obtain [tag]{filename} argument -------------------------------------------------------------------------- */ @@ -12583,7 +12291,7 @@ if ( isinput ) { /* user permitted to use \input{} */ fclose(fp); } /* close file after reading */ goto end_of_job; /* all done, return inputsp to caller*/ } /* --- end-of-if(ispbm) --- */ - status = rastreadfile(filename,0,tag,subexpr); /* read file */ + rastreadfile(filename,0,tag,subexpr); /* read file */ if ( *subexpr == '\000' ) goto end_of_job; /* quit if problem */ /* --- rasterize input subexpression --- */ mimeprep(subexpr); /* preprocess subexpression */ @@ -12637,26 +12345,26 @@ inputsp = rasterize(subexpr,size); /* rasterize subexpression */ * o :tag is optional * ======================================================================= */ /* --- entry point --- */ -subraster *rastcounter ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastcounter ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), filename[1024]="\000", /* counter file */ +char /**texsubexpr(),*/ filename[1024]="\000", /* counter file */ logfile[1024]="\000", tag[1024]="\000"; /*optional log file and tag*/ -subraster *rasterize(), *countersp=NULL; /* rasterized counter image */ +subraster /**rasterize(),*/ *countersp=NULL; /* rasterized counter image */ FILE /* *fp=NULL,*/ *logfp=NULL; /* counter and log file pointers */ -int status=0,rastreadfile(),rastwritefile(), /*read,write counter file*/ +int status=0,/*rastreadfile(),rastwritefile(),*//*read,write counter file*/ iscounter = (seclevel<=counterseclevel?1:0), /*is \counter permitted*/ isstrict = 1; /* true to only write to existing files */ char text[MAXFILESZ] = "1_", /* only line in counter file without tags */ *delim = NULL, /* delimiter in text */ utext[128] = "1_", /* default delimiter */ *udelim = utext+1; /* underscore delimiter */ -char *rasteditfilename(), /* edit log file name */ - *timestamp(), /* timestamp for logging */ - *dbltoa(); /* double to comma-separated ascii */ +/*char *rasteditfilename(),*/ /* edit log file name */ +/* *timestamp(),*/ /* timestamp for logging */ +/* *dbltoa();*/ /* double to comma-separated ascii */ int counter = 1, /* atoi(text) (after _ removed, if present) */ value = 1, /* optional [value] argument */ gotvalue = 0, /* set true if [value] supplied */ @@ -12827,15 +12535,15 @@ if ( ordindex >= 0 ) /* need to tack on ordinal suffix */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rasteval ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rasteval(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ]; /* arg to be evaluated */ -subraster *rasterize(), *evalsp=NULL; /* rasterize evaluated expression */ -int evalterm(), value=0; /* evaluate expression */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ]; /* arg to be evaluated */ +subraster /**rasterize(),*/ *evalsp=NULL; /* rasterize evaluated expression */ +int /*evalterm(),*/ value=0; /* evaluate expression */ /* ------------------------------------------------------------------------- Parse for subexpr to be \eval-uated, and bump expression past it -------------------------------------------------------------------------- */ @@ -12888,15 +12596,15 @@ evalsp = rasterize(subexpr,size); /* rasterize evaluated expression */ /* --- * entry point * -------------- */ -subraster *rastmathtex ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastmathtex ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* --- * allocations and declarations * ------------------------------- */ /* --- for mimetex --- */ -char *texsubexpr(), subexpr[MAXSUBXSZ]; /* arg to be evaluated */ -subraster *read_pbm(), *mathtexsp=NULL; /* rasterize mathtex'ed expression */ +char /**texsubexpr(),*/ subexpr[MAXSUBXSZ]; /* arg to be evaluated */ +subraster /**read_pbm(),*/ *mathtexsp=NULL; /*rasterize mathtex'ed expression*/ /* --- for wget() pipe to mathtex --- */ char command[2048], /* complete popen(command,"r") */ execwget[1024]; /* wget either mimetex or mathtex */ @@ -12974,15 +12682,15 @@ mathtexsp = read_pbm(wget,0.0); * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rasttoday ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rasttoday(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), optarg[2050]; /* optional [+/-tzdelta,ifmt] args */ -char *timestamp(), *today=optarg; /* timestamp to be rasterized */ -subraster *rasterize(), *todaysp=NULL; /* rasterize timestamp */ +char /**texsubexpr(),*/ optarg[2050]; /* optional [+/-tzdelta,ifmt] args */ +char /**timestamp(),*/ *today=optarg; /* timestamp to be rasterized */ +subraster /**rasterize(),*/ *todaysp=NULL; /* rasterize timestamp */ int ifmt=1, tzdelta=0; /* default timestamp() args */ /* ------------------------------------------------------------------------- Get optional args \today[+/-tzdelta,ifmt] @@ -13035,15 +12743,15 @@ todaysp = rasterize(today,size); /* rasterize timestamp */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastcalendar ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastcalendar ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), optarg[2050]; /* optional [year,month] args */ -char *calendar(), *calstr=NULL; /* calendar to be rasterized */ -subraster *rasterize(), *calendarsp=NULL; /* rasterize calendar string */ +char /**texsubexpr(),*/ optarg[2050]; /* optional [year,month] args */ +char /**calendar(),*/ *calstr=NULL; /* calendar to be rasterized */ +subraster /**rasterize(),*/ *calendarsp=NULL; /* rasterize calendar string */ int year=0,month=0,day=0, argval=0; /* default calendar() args */ /* ------------------------------------------------------------------------- Get optional args \today[+/-tzdelta,ifmt] @@ -13105,26 +12813,26 @@ calendarsp = rasterize(calstr,size); /* rasterize calendar string */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastenviron ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastenviron ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), optarg[255]; /* optional [...] args (for future)*/ +char /**texsubexpr(),*/ optarg[255]; /* optional [...] args (for future)*/ char environstr[8192] = "\000", /* string for all environment vars */ environvar[1024] = "\000"; /* one environment variable */ -char *strwrap(), /* wrap long lines */ - *strdetex(), /* removes/replaces any math chars */ +char /**strwrap(),*/ /* wrap long lines */ + /**strdetex(),*/ /* removes/replaces any math chars */ *environptr = NULL; /* ptr to preprocessed environvar */ -char *mimeprep(); /* preprocess environvar string */ -int unescape_url(); /* convert all %xx's to chars */ +/*char *mimeprep();*/ /* preprocess environvar string */ +/*int unescape_url();*/ /* convert all %xx's to chars */ int isenviron = (seclevel<=environseclevel?1:0); /*is \environ permitted*/ int maxvarlen = 512, /* max chars in environment var */ maxenvlen = 6400, /* max chars in entire string */ wraplen = 48; /* strwrap() wrap lines at 48 chars*/ int ienv = 0; /* environ[] index */ -subraster *rasterize(), *environsp=NULL; /* rasterize environment string */ +subraster /**rasterize(),*/ *environsp=NULL; /*rasterize environment string*/ /* ------------------------------------------------------------------------- Get args -------------------------------------------------------------------------- */ @@ -13200,20 +12908,20 @@ strcat(environstr,"}}"); /* end {\text{...}} mode */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastmessage ( char **expression, int size, subraster *basesp, - int arg1, int arg2, int arg3 ) +FUNCSCOPE subraster *rastmessage ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), amsg[256]="\000"; /* message number text */ +char /**texsubexpr(),*/ amsg[256]="\000"; /* message number text */ int imsg = 0; /* default message number */ char msg[4096]; -subraster *rasterize(), *messagesp=NULL; /* rasterize requested message */ -int strreplace(); /*replace SERVER_NAME in refmsgnum*/ +subraster /**rasterize(),*/ *messagesp=NULL; /* rasterize requested message */ +/*int strreplace();*/ /*replace SERVER_NAME in refmsgnum*/ int reflevels = REFLEVELS; /* #topmost levels to match */ -char *urlprune(); /*prune referer_match in refmsgnum*/ -char *strdetex(); /* remove math chars from messages */ +/*char *urlprune();*/ /*prune referer_match in refmsgnum*/ +/*char *strdetex();*/ /* remove math chars from messages */ char *http_host = getenv("HTTP_HOST"), /* http host for mimeTeX */ *server_name = getenv("SERVER_NAME"), /* server hosting mimeTeX */ *referer_match = (!isempty(http_host)?http_host: /*match http_host*/ @@ -13267,14 +12975,14 @@ messagesp = rasterize(msg,size); /* rasterize message string */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -subraster *rastnoop ( char **expression, int size, subraster *basesp, - int nargs, int arg2, int arg3 ) +FUNCSCOPE subraster *rastnoop(char **expression, int size, subraster *basesp, + int nargs, int arg2, int arg3) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *texsubexpr(), subexpr[MAXSUBXSZ+1]; /*dummy args eaten by \escape*/ -subraster *rasterize(), *noopsp=NULL; /* rasterize subexpr */ +char /**texsubexpr(),*/subexpr[MAXSUBXSZ+1];/*dummy args eaten by \escape*/ +subraster /**rasterize(),*/ *noopsp=NULL; /* rasterize subexpr */ /* --- flush accompanying args if necessary --- */ if ( nargs != NOVALUE /* not unspecified */ && nargs > 0 ) /* and args to be flushed */ @@ -13282,7 +12990,7 @@ if ( nargs != NOVALUE /* not unspecified */ *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0); /*flush arg*/ /* --- return null ptr to caller --- */ /*end_of_job:*/ - return ( noopsp ); /* return NULL ptr to caller */ +return ( noopsp ); /* return NULL ptr to caller */ } /* --- end-of-function rastnoop() --- */ @@ -13303,14 +13011,14 @@ if ( nargs != NOVALUE /* not unspecified */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -FILE *rastopenfile ( char *filename, char *mode ) +FUNCSCOPE FILE *rastopenfile ( char *filename, char *mode ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ FILE *fp = (FILE *)NULL /*,*fopen()*/; /*file pointer to opened filename*/ char texfile[2050] = "\000", /* local, edited copy of filename */ - *rasteditfilename(), /* prepend pathprefix if necessary */ + /**rasteditfilename(),*/ /* prepend pathprefix if necessary */ amode[512] = "r"; /* test open mode if arg mode=NULL */ int ismode = 0; /* true of mode!=NULL */ /* -------------------------------------------------------------------------- @@ -13340,7 +13048,7 @@ if ( !ismode && fp!=NULL ) /* no mode, so just checking */ fclose(fp); /* close file, fp signals success */ /* --- return fp or NULL to caller --- */ /*end_of_job:*/ - if ( msglevel>=9 && msgfp!=NULL ) /* debuging */ +if ( msglevel>=9 && msgfp!=NULL ) /* debuging */ { fprintf(msgfp,"rastopenfile> returning fopen(%s,%s) = %s\n", filename,amode,(fp==NULL?"NULL":"Okay")); fflush(msgfp); } return ( fp ); /* return fp or NULL to caller */ @@ -13361,14 +13069,14 @@ if ( !ismode && fp!=NULL ) /* no mode, so just checking */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *rasteditfilename ( char *filename ) +FUNCSCOPE char *rasteditfilename ( char *filename ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ static char editname[2050]; /*edited filename returned to caller*/ -char *strchange(); /* prepend pathprefix if necessary */ -int strreplace(), /* remove ../'s and ..\'s */ +/*char *strchange();*/ /* prepend pathprefix if necessary */ +int /*strreplace(),*/ /* remove ../'s and ..\'s */ isprefix = (*pathprefix=='\000'?0:1); /* true if paths have prefix */ /* -------------------------------------------------------------------------- edit filename @@ -13421,12 +13129,12 @@ if ( isprefix && *editname!='\000' ) /* filename is preceded by prefix */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int rastreadfile ( char *filename, int islock, char *tag, char *value ) +FUNCSCOPE int rastreadfile(char *filename, int islock, char *tag, char *value) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -FILE *fp = (FILE *)NULL, *rastopenfile(); /* pointer to opened filename */ +FILE *fp = (FILE *)NULL /*, *rastopenfile()*/; /*ptr to opened filename*/ char texfile[1024] = "\000", /* local copy of input filename */ text[MAXLINESZ+1]; /* line from input file */ char *tagp, tag1[1024], tag2[1024]; /* left and right */ @@ -13472,6 +13180,7 @@ while ( fgets(text,MAXLINESZ-1,fp) != (char *)NULL ) { /*read input till eof*/ tagp += strlen(tag1); /* first char past tag */ strsqueezep(text,tagp); /*shift out preceding text and tag*/ tagnum = 2; /*now looking for closing right tag*/ + /* FALLTHRU */ case 2: /* looking for closing right */ if ( (tagp=strstr(text,tag2)) == NULL ) break; /*haven't found it yet*/ *tagp = '\000'; /* terminate line at tag */ @@ -13517,18 +13226,18 @@ fclose ( fp ); /* close input file after reading */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int rastwritefile( char *filename, char *tag, char *value, int isstrict ) +FUNCSCOPE int rastwritefile(char *filename,char *tag,char *value,int isstrict) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -FILE *fp = (FILE *)NULL, *rastopenfile(); /* pointer to opened filename */ +FILE *fp = (FILE *)NULL /*, *rastopenfile()*/; /*ptr to opened filename*/ char texfile[1024] = "\000", /* local copy of input filename */ filebuff[MAXFILESZ+1] = "\000", /* entire contents of file */ - tag1[1024], tag2[1024], /* left and right */ - *strchange(), /* put value between ...*/ - *timestamp(); /* log modification time */ -int istag=0, rastreadfile(), /* read file if tag!=NULL */ + tag1[1024], tag2[1024] /* left and right */ + /*,*strchange(),*/ /* put value between ...*/ + /**timestamp()*/; /* log modification time */ +int istag=0, /*rastreadfile(),*/ /* read file if tag!=NULL */ /*isstrict = (seclevel>5? 1:0),*/ /*true only writes existing files*/ isnewfile = 0, /* true if writing new file */ status = 0; /* status returned, 1=okay */ @@ -13656,7 +13365,7 @@ if ( status > 0 ) /*forget timestamp if write failed*/ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *calendar( int year, int month, int day ) +FUNCSCOPE char *calendar( int year, int month, int day ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -13755,7 +13464,7 @@ return ( calbuff ); /* back to caller with calendar */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *timestamp( int tzdelta, int ifmt ) +FUNCSCOPE char *timestamp( int tzdelta, int ifmt ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -13767,8 +13476,8 @@ struct tm *tmstruct=(struct tm *)NULL, *localtime(); /* interpret time_val */ int year=0, hour=0,ispm=1, /* adjust year, and set am/pm hour */ month=0, day=0, /* adjust day and month for delta */ minute=0,second=0; /* minute and second not adjusted */ -int tzadjust(); /* time zone adjustment function */ -int daynumber(); /* #days since Jan 1, 1973 */ +/*int tzadjust();*/ /* time zone adjustment function */ +/*int daynumber();*/ /* #days since Jan 1, 1973 */ static char *daynames[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" } ; static char *monthnames[] = { "?", "January", "February", "March", "April", @@ -13858,7 +13567,7 @@ switch ( ifmt ) * Notes: o * ======================================================================= */ /* --- entry point --- */ -int tzadjust ( int tzdelta, int *year, int *month, int *day, int *hour ) +FUNCSCOPE int tzadjust(int tzdelta, int *year, int *month, int *day, int *hour) { /* -------------------------------------------------------------------------- Allocations and Declarations @@ -13918,7 +13627,7 @@ return ( 1 ); * Notes: o * ======================================================================= */ /* --- entry point --- */ -int daynumber ( int year, int month, int day ) +FUNCSCOPE int daynumber ( int year, int month, int day ) { /* -------------------------------------------------------------------------- Allocations and Declarations @@ -13992,7 +13701,7 @@ return ( (int)(ndays) ); /* #days back to caller */ * produced linebreaks). * ======================================================================= */ /* --- entry point --- */ -char *strwrap ( char *s, int linelen, int tablen ) +FUNCSCOPE char *strwrap ( char *s, int linelen, int tablen ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14000,8 +13709,8 @@ Allocations and Declarations static char sbuff[4096]; /* line-wrapped copy of s */ char *sol = sbuff; /* ptr to start of current line*/ char tab[32] = " "; /* tab string */ -int strreplace(); /* remove \n's */ -char *strchange(); /* add \n's and indent space */ +/*int strreplace();*/ /* remove \n's */ +/*char *strchange();*/ /* add \n's and indent space */ int finalnewline = (lastchar(s)=='\n'?1:0); /*newline at end of string?*/ int istab = (tablen>0?1:0), /* init true to indent first line */ iswhite = 0; /* true if line break on whitespace*/ @@ -14049,7 +13758,7 @@ while ( 1 ) { /* till end-of-line */ fflush(msgfp); } /* --- look for last whitespace preceding linelen --- */ while ( 1 ) { /* till we exceed linelen */ - wordlen = strcspn(sol+thislen," \t\n\r\f\v :;.,"); /*ptr to next white/break*/ + wordlen = strcspn(sol+thislen," \t\n\r\f\v :;.,"); /*ptr next white/break*/ if ( sol[thislen+wordlen] == '\000' ) /* no more whitespace in string */ goto end_of_job; /* so nothing more we can do */ if ( thislen+thistab+wordlen >= linelen ) /* next word won't fit */ @@ -14085,7 +13794,7 @@ while ( 1 ) { /* till end-of-line */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *strnlower ( char *s, int n ) +FUNCSCOPE char *strnlower ( char *s, int n ) { /* ------------------------------------------------------------------------- lowercase s @@ -14124,7 +13833,7 @@ return ( s ); /* back to caller with s */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *urlprune ( char *url, int n ) +FUNCSCOPE char *urlprune ( char *url, int n ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14132,7 +13841,7 @@ Allocations and Declarations static char pruned[2048]; /* pruned url returned to caller */ char *purl = /*NULL*/pruned; /* ptr to pruned, init for error */ char *delim = NULL; /* delimiter separating components */ -char *strnlower(); /* lowercase a string */ +/*char *strnlower();*/ /* lowercase a string */ int istruncate = (n<0?1:0); /*true to truncate .com from pruned*/ int ndots = 0; /* number of dots found in url */ /* ------------------------------------------------------------------------- @@ -14201,12 +13910,12 @@ purl = pruned; /*completed okay, return pruned url*/ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int urlncmp ( char *url1, char *url2, int n ) +FUNCSCOPE int urlncmp ( char *url1, char *url2, int n ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -char *urlprune(), *prune=NULL, /* prune url's */ +char /**urlprune(),*/ *prune=NULL, /* prune url's */ prune1[4096], prune2[4096]; /* pruned copies of url1,url2 */ int ismatch = 0; /* true if url's match */ /* ------------------------------------------------------------------------- @@ -14244,7 +13953,7 @@ if ( strcmp(prune1,prune2) == 0 ) /* pruned url's are identical */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -char *dbltoa ( double dblval, int npts ) +FUNCSCOPE char *dbltoa ( double dblval, int npts ) /* double dblval; int npts; */ { @@ -14336,7 +14045,7 @@ return ( finval ); /* converted double back to caller */ * * ======================================================================= */ /* --- entry point --- */ -matrix3d *rotmatrix ( point3d *axis, double theta ) +FUNCSCOPE matrix3d *rotmatrix ( point3d *axis, double theta ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14392,7 +14101,7 @@ prot = &(rot); /* point return value to matrix */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -point3d *matmult ( matrix3d *mat, point3d *vec ) +FUNCSCOPE point3d *matmult ( matrix3d *mat, point3d *vec ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14446,7 +14155,7 @@ pmult = &(mult); /* point return value to product */ * as per the preceding note). * ======================================================================= */ /* --- entry point --- */ -int aalowpass (raster *rp, intbyte *bytemap, int grayscale) +FUNCSCOPE int aalowpass (raster *rp, intbyte *bytemap, int grayscale) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14479,7 +14188,7 @@ for ( irow=0; irowheight; irow++ ) iscenter = 0, /* set true if center pixel black */ nadjacent=0, wadjacent=0, /* #adjacent black pixels, their wts*/ ngaps = 0, /* #gaps in 8 pixels around center */ - iwt=(-1), sumwts=0; /* weights index, sum in-bound wts */ + iwt=(-1); /* weights index */ char adjmatrix[8]; /* adjacency "matrix" */ memset(adjmatrix,0,8); /* zero out adjacency matrix */ bytemap[ipixel] = 0; /* init pixel white */ @@ -14500,7 +14209,6 @@ for ( irow=0; irowheight; irow++ ) { nadjacent++; /* bump adjacent black count */ adjmatrix[adjindex[iwt]] = 1; } /*set "bit" in adjacency matrix*/ wadjacent += weights[iwt]; } /* sum weights for black pixels */ - sumwts += weights[iwt]; /* and sum weights for all pixels */ } /* --- end-of-for(jrow,jcol) --- */ /* --- count gaps --- */ ngaps = (adjmatrix[7]!=adjmatrix[0]?1:0); /* init count */ @@ -14558,7 +14266,7 @@ Back to caller with gray-scale anti-aliased bytemap * on sourceforge. * ======================================================================= */ /* --- entry point --- */ -int aapnm (raster *rp, intbyte *bytemap, int grayscale) +FUNCSCOPE int aapnm (raster *rp, intbyte *bytemap, int grayscale) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14732,7 +14440,7 @@ Back to caller with gray-scale anti-aliased bytemap * to interpret 3x3 lowpass pixel grids. * ======================================================================= */ /* --- entry point --- */ -int aapnmlookup (raster *rp, intbyte *bytemap, int grayscale) +FUNCSCOPE int aapnmlookup (raster *rp, intbyte *bytemap, int grayscale) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14748,8 +14456,8 @@ int isfgalias = fgalias, /*(1) true to antialias fg bits */ isfgonly = fgonly, /*(0) true to only antialias fg bits*/ isbgalias = bgalias, /*(0) true to antialias bg bits */ isbgonly = bgonly; /*(0) true to only antialias bg bits*/ -int gridnum=(-1), aagridnum(), /* grid# for 3x3 grid at irow,icol */ - patternum=(-1), aapatternnum(); /*pattern#, 1-51, for input gridnum*/ +int gridnum=(-1), /*aagridnum(),*/ /* grid# for 3x3 grid at irow,icol */ + patternum=(-1) /*, aapatternnum()*/; /*pattern#1-51 for input gridnum*/ int aapatterns(); /* to antialias special patterns */ /* --- * pattern number data @@ -14913,19 +14621,19 @@ Back to caller with gray-scale anti-aliased bytemap * Notes: o * ======================================================================= */ /* --- entry point --- */ -int aapatterns (raster *rp, int irow, int icol, - int gridnum, int patternum, int grayscale) +FUNCSCOPE int aapatterns ( raster *rp, int irow, int icol, + int gridnum, int patternum, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ int aaval = (-1); /* antialiased value returned */ int iscenter = (gridnum&1); /* true if center pixel set/black */ -int aapatternnum(), /* if patternum not supplied */ - aapattern1124(), /* routine for patterns #11,24 */ - aapattern19(), /* special routine for pattern #19 */ - aapattern20(), /* special routine for pattern #20 */ - aapattern39(); /* special routine for pattern #39 */ +/*int aapatternnum(),*/ /* if patternum not supplied */ +/* aapattern1124(),*/ /* routine for patterns #11,24 */ +/* aapattern19(),*/ /* special routine for pattern #19 */ +/* aapattern20(),*/ /* special routine for pattern #20 */ +/* aapattern39();*/ /* special routine for pattern #39 */ /* ------------------------------------------------------------------------- special pattern number processing -------------------------------------------------------------------------- */ @@ -14983,8 +14691,8 @@ return ( aaval ); /* return antialiased val to caller*/ * corner, eg, * line, eg, * * ======================================================================= */ /* --- entry point --- */ -int aapattern1124 (raster *rp, int irow, int icol, - int gridnum, int grayscale) +FUNCSCOPE int aapattern1124 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -14997,16 +14705,17 @@ int width=rp->width, height=rp->height; /* width, height of raster */ int jrow=irow, jcol=icol; /* corner or diagonal row,col */ int vertcornval=0, horzcornval=0, /* vertical, horizontal corner bits*/ topdiagval=0, botdiagval=0, /* upper,lower diagonal pixel bits */ - cornval=0, diagval=0; /* vert+horzcorn, top+botdiag */ + diagval=0; /* vert+horzcorn, top+botdiag */ int hdirection=99, vdirection=99, /* horz,vert corner direction */ - hturn=99,vturn=99, aafollowline(); /* follow corner till turns */ + hturn=99,vturn=99 /*, aafollowline()*/; /*follow corner till turns*/ /* ------------------------------------------------------------------------- Check corner and diagonal pixels -------------------------------------------------------------------------- */ if ( 0 ) goto end_of_job; /* true to turn off pattern1124 */ switch ( gridnum/2 ) { /* check pattern#11,24 corner, diag*/ default: goto end_of_job; /* not a pattern#11,24 gridnum */ - case 10: patternum=11; case 11: + case 10: patternum=11; /* FALLTHRU */ + case 11: hdirection = 2; vdirection = -1; /* directions to follow corner */ if ( (jrow=irow+2) < height ) { /* vert corner below center pixel */ vertcornval = getlongbit(bitmap,(icol+jrow*width)); @@ -15017,7 +14726,8 @@ switch ( gridnum/2 ) { /* check pattern#11,24 corner, diag*/ if ( (irow-1) >= 0 ) /* upper diag above center */ topdiagval = getlongbit(bitmap,(jcol+(irow-1)*width)); } break; - case 18: patternum=11; case 22: + case 18: patternum=11; /* FALLTHRU */ + case 22: hdirection = -2; vdirection = -1; /* directions to follow corner */ if ( (jrow=irow+2) < height ) { /* vert corner below center pixel */ vertcornval = getlongbit(bitmap,(icol+jrow*width)); @@ -15028,7 +14738,8 @@ switch ( gridnum/2 ) { /* check pattern#11,24 corner, diag*/ if ( (irow-1) >= 0 ) /* upper diag above center */ topdiagval = getlongbit(bitmap,(jcol+(irow-1)*width)); } break; - case 72: patternum=11; case 104: + case 72: patternum=11; /* FALLTHRU */ + case 104: hdirection = 2; vdirection = 1; /* directions to follow corner */ if ( (jrow=irow-2) >= 0 ) { /* vert corner above center pixel */ vertcornval = getlongbit(bitmap,(icol+jrow*width)); @@ -15039,7 +14750,8 @@ switch ( gridnum/2 ) { /* check pattern#11,24 corner, diag*/ if ( (irow+1) < height ) /* lower diag below center */ botdiagval = getlongbit(bitmap,(jcol+(irow+1)*width)); } break; - case 80: patternum=11; case 208: + case 80: patternum=11; /* FALLTHRU */ + case 208: hdirection = -2; vdirection = 1; /* directions to follow corner */ if ( (jrow=irow-2) >= 0 ) { /* vert corner above center pixel */ vertcornval = getlongbit(bitmap,(icol+jrow*width)); @@ -15051,7 +14763,6 @@ switch ( gridnum/2 ) { /* check pattern#11,24 corner, diag*/ botdiagval = getlongbit(bitmap,(jcol+(irow+1)*width)); } break; } /* --- end-of-switch(gridnum/2) --- */ -cornval = vertcornval+horzcornval; /* 0=no corner bits, 1, 2=both */ diagval = topdiagval+botdiagval; /* 0=no diag bits, 1, 2=both */ /* ------------------------------------------------------------------------- Handle white center @@ -15108,8 +14819,8 @@ Back to caller with grayscale antialiased value for pixel at irow,icol * *** --* *-- --- * ======================================================================= */ /* --- entry point --- */ -int aapattern19 (raster *rp, int irow, int icol, - int gridnum, int grayscale) +FUNCSCOPE int aapattern19 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15118,7 +14829,7 @@ int aaval = (-1); /* antialiased value returned */ int iscenter = gridnum&1; /* true if pixel at irow,icol black*/ int orientation = 1, /* 1=vertical, 2=horizontal */ jrow=irow, jcol=icol; /* middle pixel of *** line */ -int turn1=0,turn2=0, aafollowline(); /* follow *** line till it turns */ +int turn1=0,turn2=0 /*, aafollowline()*/; /*follow *** line till it turns*/ /* ------------------------------------------------------------------------- Initialization and calculation of antialiased value -------------------------------------------------------------------------- */ @@ -15181,8 +14892,8 @@ Back to caller with grayscale antialiased value for pixel at irow,icol * *-- --- -*- --- * ======================================================================= */ /* --- entry point --- */ -int aapattern20 (raster *rp, int irow, int icol, - int gridnum, int grayscale) +FUNCSCOPE int aapattern20 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15192,7 +14903,7 @@ int iscenter = gridnum&1; /* true if pixel at irow,icol black*/ int direction = 1, /* direction to follow ** line */ jrow1=irow, jcol1=icol, /* coords of * */ jrow2=irow, jcol2=icol; /* coords of adjacent ** pixel */ -int turn1=0,turn2=0, aafollowline(); /* follow *,** lines till turns */ +int turn1=0,turn2=0 /*, aafollowline()*/; /*follow *,** lines till turns*/ /* ------------------------------------------------------------------------- Initialization and calculation of antialiased value -------------------------------------------------------------------------- */ @@ -15260,8 +14971,8 @@ Back to caller with grayscale antialiased value for pixel at irow,icol * *-- --- **- --- * ======================================================================= */ /* --- entry point --- */ -int aapattern39 (raster *rp, int irow, int icol, - int gridnum, int grayscale) +FUNCSCOPE int aapattern39 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15271,7 +14982,7 @@ int iscenter = gridnum&1; /* true if pixel at irow,icol black*/ int direction = 1, /* direction to follow ** line */ jrow1=irow, jcol1=icol, /* coords of * */ jrow2=irow, jcol2=icol; /* coords of adjacent ** pixel */ -int turn1=0,turn2=0, aafollowline(); /* follow *,** lines till turns */ +int turn1=0,turn2=0 /*, aafollowline()*/; /*follow *,** lines till turns*/ /* ------------------------------------------------------------------------- Initialization and calculation of antialiased value -------------------------------------------------------------------------- */ @@ -15362,7 +15073,7 @@ Back to caller with grayscale antialiased value for pixel at irow,icol * ----- ----- * ======================================================================= */ /* --- entry point --- */ -int aafollowline (raster *rp, int irow, int icol, int direction) +FUNCSCOPE int aafollowline ( raster *rp, int irow, int icol, int direction ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15514,7 +15225,7 @@ Back to caller with #rows or #cols traversed, and direction of detected turn * white. * ======================================================================= */ /* --- entry point --- */ -int aagridnum (raster *rp, int irow, int icol) +FUNCSCOPE int aagridnum ( raster *rp, int irow, int icol ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15663,7 +15374,7 @@ Back to caller with gridnum coding 3x3 grid centered at irow,icol * **- *-* **- *-* -*- * ======================================================================= */ /* --- entry point --- */ -int aapatternnum ( int gridnum ) +FUNCSCOPE int aapatternnum ( int gridnum ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15724,13 +15435,13 @@ if ( pattern<1 || pattern>51 ) pattern = (-1); /* some internal error */ * for the center pixel (gridnum bit 0) of the grid. * ======================================================================= */ /* --- entry point --- */ -int aalookup ( int gridnum ) +FUNCSCOPE int aalookup ( int gridnum ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ int grayscale = (-1); /*returned grayscale, init for error*/ -int pattern = (-1), aapatternnum(); /*pattern#, 1-51, for input gridnum*/ +int pattern = (-1) /*, aapatternnum()*/;/*pattern#1-51 for input gridnum*/ int iscenter = gridnum&1; /*low-order bit set for center pixel*/ /* --- gray scales --- */ #define WHT 0 @@ -15848,7 +15559,7 @@ grayscale = ( iscenter? grayscale1[pattern] : grayscale0[pattern] ); * Notes: o * ======================================================================= */ /* --- entry point --- */ -int aalowpasslookup (raster *rp, intbyte *bytemap, int grayscale) +FUNCSCOPE int aalowpasslookup ( raster *rp, intbyte *bytemap, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15858,8 +15569,8 @@ int width=rp->width, height=rp->height, /* width, height of raster */ int bgbitval=0 /*, fgbitval=1*/; /* background, foreground bitval */ int bitval=0, /* value of rp bit at irow,icol */ aabyteval=0; /* antialiased (or unchanged) value*/ -int gridnum=0, aagridnum(), /* grid# for 3x3 grid at irow,icol */ - aalookup(); /* table look up antialiased value*/ +int gridnum=0 /*, aagridnum(),*/ /* grid# for 3x3 grid at irow,icol */ + /*aalookup()*/; /* table look up antialiased value*/ /* ------------------------------------------------------------------------- generate bytemap by table lookup for each pixel of bitmap -------------------------------------------------------------------------- */ @@ -15909,7 +15620,7 @@ Back to caller with gray-scale anti-aliased bytemap * lines, which would otherwise turn from black to a gray shade. * ======================================================================= */ /* --- entry point --- */ -int aasupsamp (raster *rp, raster **aa, int sf, int grayscale) +FUNCSCOPE int aasupsamp ( raster *rp, raster **aa, int sf, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -15922,8 +15633,8 @@ int rpheight=rp->height, rpwidth=rp->width, /*bitmap raster dimensions*/ int maxaaval=(-9999), /* max grayscale val set in matrix */ isrescalemax=1; /* 1=rescale maxaaval to grayscale */ int irp=0,jrp=0, iaa=0,jaa=0, iwt=0,jwt=0; /*indexes, i=width j=height*/ -raster *aap=NULL, *new_raster(); /* raster for supersampled image */ -raster *aaweights(); /* get weight matrix applied to rp */ +raster *aap=NULL /*, *new_raster()*/; /* raster for supersampled image */ +/*raster *aaweights();*/ /* get weight matrix applied to rp */ static raster *aawts = NULL; /* aaweights() resultant matrix */ static int prevshrink = NOVALUE, /* shrinkfactor from previous call */ sumwts = 0; /* sum of weights */ @@ -15931,8 +15642,8 @@ static int blackfrac = 40, /* force black if this many pts are */ /*grayfrac = 20,*/ maxwt = 10, /* max weight in weight matrix */ minwtfrac=10, maxwtfrac=70; /* force light pts white, dark black*/ -int type_raster(), type_bytemap(); /* debugging display routines */ -int delete_raster(); /* delete old rasters */ +/*int type_raster(), type_bytemap();*/ /* debugging display routines */ +/*int delete_raster();*/ /* delete old rasters */ /* ------------------------------------------------------------------------- Initialization -------------------------------------------------------------------------- */ @@ -16068,18 +15779,18 @@ Back to caller with gray-scale anti-aliased bytemap * lines, which would otherwise turn from black to a gray shade. * ======================================================================= */ /* --- entry point --- */ -raster *imgsupsamp (raster *rp, double sf, int grayscale) +FUNCSCOPE raster *imgsupsamp ( raster *rp, double sf, int grayscale ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -raster *ssp=NULL, *new_raster(); /* new raster for returned ss */ +raster *ssp=NULL /*, *new_raster()*/; /* new raster for returned ss */ int rpheight=rp->height, rpwidth=rp->width, /* rp raster dimensions */ ssheight=0, sswidth=0, /* supersampled dimensions */ wtheight=0, wtwidth=0; /* weight matrix dimensions */ int iss=0, jss=0; /* ss indexes, i=width j=height */ -int delete_raster(); /* delete stale sswts rasters */ -int maxwt=10, ssweights(); /* weight matrix applied to rp */ +/*int delete_raster();*/ /* delete stale sswts rasters */ +int maxwt=10 /*, ssweights()*/; /* weight matrix applied to rp */ static raster *sswts = NULL; /* ssweights() resultant matrix */ static double prevsf = 0.0; /* shrinkfactor from previous call */ static int sumwts = 0; /* sum of weights */ @@ -16102,7 +15813,7 @@ ssheight = (int)(((double)rpheight)*sf + 0.5); /* shrink height by sf */ sswidth = (int)(((double)rpwidth)*sf + 0.5); /* shrink width by sf */ if ( ssheight<1 || sswidth<1 ) goto end_of_job; /* shrunk too much */ /* --- weight matrix dimensions --- */ -wtheight = max2(3.0,(1.0/sf)); /* at least 3x3-point averaging */ +wtheight = (int)(max2(3.0,(1.0/sf))); /* at least 3x3-point averaging */ wtheight = 1 + (wtheight/2)*2; /* and always an odd number */ wtwidth = wtheight; /* same (for now) */ /* --- get weight matrix (or use current one) --- */ @@ -16210,7 +15921,7 @@ Back to caller with supersampled image * tries to grow beyond 255 is held constant at 255. * ======================================================================= */ /* --- entry point --- */ -int ssweights ( int width, int height, int maxwt, raster **wts ) +FUNCSCOPE int ssweights ( int width, int height, int maxwt, raster **wts ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -16219,7 +15930,7 @@ int irow=0, icol=0, /* height, width indexes */ weight = 0, /*running weight, as per Notes above*/ totwt = (-1); /* sum of weights in wts */ int ssalgorithm = 99; /* maybe for later use */ -raster *new_raster(); /* if caller wants wts allocated */ +/*raster *new_raster();*/ /* if caller wants wts allocated */ /* ------------------------------------------------------------------------- Initialization -------------------------------------------------------------------------- */ @@ -16276,8 +15987,8 @@ for ( irow=0; irowpixsz, /* #bits per image pixel */ - black1=1, black8=255, /* black for 1-bit, 8-bit pixels */ - black = (pixsz==1? black1:black8), /* black value for our image */ - scalefactor = (black1+black8-black), /* only scale 1-bit images */ - iscenter = 0; /* set true if center pixel black */ -/* --- grid dimensions and indexes --- */ -int wtheight = weights->height, /* #rows in weight matrix */ - wtwidth = weights->width, /* #cols in weight matrix */ - imgheight = image->height, /* #rows in image */ - imgwidth = image->width; /* #cols in image */ -int wtrow, wtrow0 = wtheight/2, /* center row index for weights */ - wtcol, wtcol0 = wtwidth/2, /* center col index for weights */ - imgrow, imgrow0= ipixel/imgwidth, /* center row index for ipixel */ - imgcol, imgcol0= ipixel-(imgrow0*imgwidth); /*center col for ipixel*/ -/* --- rotated grid variables --- */ -static int prevrotate = 0; /* rotate from previous call */ -static double costheta = 1.0, /* cosine for previous rotate */ - sintheta = 0.0; /* and sine for previous rotate */ -double a = 1.0; /* default aspect ratio */ -/* ------------------------------------------------------------------------- -Initialization --------------------------------------------------------------------------- */ -/* --- refresh trig functions for rotate when it changes --- */ -if ( rotate != prevrotate ) /* need new sine/cosine */ - { costheta = cos(((double)rotate)/57.29578); /*cos of rotate in radians*/ - sintheta = sin(((double)rotate)/57.29578); /*sin of rotate in radians*/ - prevrotate = rotate; } /* save current rotate as prev */ -/* ------------------------------------------------------------------------- -Calculate aapixel as weighted average over image points around ipixel --------------------------------------------------------------------------- */ -for ( wtrow=0; wtrow=0 && imgrow=0 && imgcolimage returned by rasterize()*/ +int nwide=0, nhigh=0, npixels=nwide*nhigh, /* raster dimensions */ + icol =0, irow =0, ipixel =0; /* col,row,pixel indexes */ +/*int delete_subraster();*/ /* free raster after making bytemap */ +char exprbuffer[4096]; /* local copy of expression */ +/* --- + * initialization + * ----------------- */ +/* --- check args --- */ +if ( width != NULL ) *width =0; /* init width (in case of error) */ +if ( height != NULL ) *height=0; /* init height */ +if ( isempty(expression) ) goto end_of_job; /* nothing to do */ +/* --- preprocess a local copy of caller's expression --- */ +strninit(exprbuffer,expression,2048); /* local copy of expression */ +mimeprep(exprbuffer); /* preprocess expression */ +/* --- + * rasterize expression + * ----------------------- */ +if ( (sp = rasterize(exprbuffer,NORMALSIZE)) /* rasterize expression */ +== NULL ) goto end_of_job; /* quit if failed to rasterize */ +/* --- apply any 'magstep' to magnify entire rasterized >>bit< 1 && magstep <= 10 ) { /* magnify entire bitmap image */ + raster /**rastmag(),*/ *magrp=NULL; /* bitmap magnify function */ + int baseline = sp->baseline; /* original image baseline */ + magrp = rastmag(sp->image,magstep); /* magnify raster image */ + if ( magrp != NULL ) { /* succeeded to magnify image */ + delete_raster(sp->image); /* free original raster image */ + sp->image = magrp; /*and replace it with magnified one*/ + /* --- adjust parameters --- */ + baseline *= magstep; /* scale baseline */ + if ( baseline > 0 ) baseline += 1; /* adjust for no descenders */ + sp->baseline = baseline; } /*reset baseline of magnified image*/ + } /* --- end-of-if(magstep) --- */ +/* --- finally, adjust bitmap width to multiple of eight bits --- */ +if ( 1 ) { + rp = border_raster(sp->image,0,0,0,1); /* image width multiple of 8 bits */ + if ( rp != NULL ) sp->image = rp; } /* save successfully bordred image */ +/* --- + * get pixels for returned bytemap + * ---------------------------------- */ +if ( (rp = sp->image) /* raster image in returned subraster*/ +== NULL ) goto end_of_job; /* shouldn't happen, probably a bug */ +/* --- raster dimensions --- */ +nwide=rp->width; nhigh=rp->height; npixels=nwide*nhigh; /* width and height */ +if ( width != NULL ) *width =nwide; /* set actual image width in pixels */ +if ( height != NULL ) *height=nhigh; /* and height */ +if ( npixels < 1 ) goto end_of_job; /* some kind of problem */ +/* --- allocate bytemap ... --- */ +if ( (bytemap = (unsigned char *)malloc(npixels+nwide)) /*plus one extra row*/ +== NULL ) goto end_of_job; /* malloc() failed */ +/* --- ...and transfer pixels to it --- */ +for ( irow=0; irow= 0 ) msglevel = newmsglevel; if ( newmsgfp != NULL ) msgfp = newmsgfp; return ( 1 ); } /* --- end-of-function mimetexsetmsg() --- */ + #endif /* PART3 */ /* --- @@ -16646,17 +16372,22 @@ GLOBAL(int,isaa,ISAAVALUE); /* set anti-aliasing flag */ /* ------------------------------------------------------------------------- logging data structure, and default data to be logged -------------------------------------------------------------------------- */ -/* --- logging data structure --- */ -#define logdata struct logdata_struct /* "typedef" for logdata_struct*/ -logdata - { - /* ----------------------------------------------------------------------- - environment variable name, max #chars to display, min msglevel to display - ------------------------------------------------------------------------ */ - char *name; /* environment variable name */ - int maxlen; /* max #chars to display */ - int msglevel; /* min msglevel to display data */ - } ; /* --- end-of-logdata_struct --- */ +#if 0 + /* --- + * >> Note: logdata now defined in mimetex.h << + * (it's temporarily left here only as comments) + * ------------------------------------------------ */ + /* --- logging data structure --- */ + #define logdata struct logdata_struct /* "typedef" for logdata_struct*/ + logdata { + /* ----------------------------------------------------------------------- + environment variable name, max #chars to display, min msglevel to display + ------------------------------------------------------------------------ */ + char *name; /* environment variable name */ + int maxlen; /* max #chars to display */ + int msglevel; /* min msglevel to display data */ + } ; /* --- end-of-logdata_struct --- */ +#endif /* --- data logged by mimeTeX --- */ STATIC logdata mimelog[] #ifdef INITVALS @@ -16675,7 +16406,9 @@ STATIC logdata mimelog[] ; -/* --- entry point --- */ +/* --- + * entry point + * -------------- */ int main ( int argc, char *argv[] #ifdef DUMPENVP , char *envp[] @@ -16690,31 +16423,28 @@ static char exprbuffer[MAXEXPRSZ+1] = "f(x)=x^2"; /* input TeX expression */ char *expression = exprbuffer; /* ptr to expression */ int size = NORMALSIZE; /* default font size */ char *query = getenv("QUERY_STRING"); /* getenv("QUERY_STRING") result */ -char *mimeprep(); /* preprocess expression */ -int unescape_url(); /* convert %xx's to ascii chars */ -int emitcache(); /* emit cached image if it exists */ +/*char *mimeprep();*/ /* preprocess expression */ +/*int unescape_url();*/ /* convert %xx's to ascii chars */ +/*int emitcache();*/ /* emit cached image if it exists */ int /*isquery = 0, (now global)*/ /* true if input from QUERY_STRING */ - isqempty = 0, /* true if query string empty */ isqforce = 0, /* true to force query emulation */ isqlogging = 0, /* true if logging in query mode */ isformdata = 0, /* true if input from html form */ isinmemory = 1, /* true to generate image in memory*/ isdumpimage = 0, /* true to dump image on stdout */ isdumpbuffer = 0; /* true to dump to memory buffer */ -char *getdirective(), argstring[256],/*look for control \directive's, etc*/ - *pdirective = NULL; /* ptr to char after \directive */ +char /**getdirective(),*/ argstring[256]; /*look for \directive's, etc*/ /* --- rasterization --- */ -subraster *rasterize(), *sp=NULL; /* rasterize expression */ -raster *border_raster(), *bp=NULL; /* put a border around raster */ -int delete_subraster(); /* for clean-up at end-of-job */ -int type_raster(), type_bytemap(), /* screen dump function prototypes */ - xbitmap_raster(); /* mime xbitmap output function */ +subraster /**rasterize(),*/ *sp=NULL; /* rasterize expression */ +raster /**border_raster(),*/ *bp=NULL; /* put a border around raster */ +/*int delete_subraster();*/ /* for clean-up at end-of-job */ +/*int type_raster(), type_bytemap(),*/ /* screen dump function prototypes */ /* --- http_referer --- */ char *referer = REFERER; /* http_referer must contain this */ char *inputreferer = INPUTREFERER; /*http_referer's permitted to \input*/ -int reflevels = REFLEVELS, urlncmp(); /* cmp http_referer,server_name */ -int strreplace(); /* replace SERVER_NAME in errmsg */ -char *urlprune(); /* prune referer_match */ +int reflevels = REFLEVELS /*, urlncmp()*/; /*cmp http_referer,server_name*/ +/*int strreplace();*/ /* replace SERVER_NAME in errmsg */ +/*char *urlprune();*/ /* prune referer_match */ struct { char *referer; int msgnum; } /* http_referer can't contain this */ denyreferer[] = { /* referer table to deny access to */ #ifdef DENYREFERER @@ -16728,7 +16458,7 @@ char *http_referer = getenv("HTTP_REFERER"), /* referer using mimeTeX */ *referer_match = (!isempty(http_host)?http_host: /*match http_host*/ (!isempty(server_name)?server_name:(NULL))); /* or server_name */ int ishttpreferer = (isempty(http_referer)?0:1); -int isstrstr(); /* search http_referer for referer */ +/*int isstrstr();*/ /* search http_referer for referer */ int isinvalidreferer = 0; /* true for inavlid referer */ int norefmaxlen = NOREFMAXLEN; /*max query_string len if no referer*/ /* --- gif --- */ @@ -16740,32 +16470,32 @@ int norefmaxlen = NOREFMAXLEN; /*max query_string len if no referer*/ char *gif_outfile = (char *)NULL, /* gif output defaults to stdout */ gif_buffer[MAXGIFSZ] = "\000", /* or gif written in memory buffer */ cachefile[256] = "\000", /* full path and name to cache file*/ - *md5hash=NULL, *md5str(); /* md5 hash of expression */ + *md5hash=NULL /*, *md5str()*/; /* md5 hash of expression */ int maxage = 7200; /* max-age is two hours */ int valign = (-9999); /*Vertical-Align:baseline-(height-1)*/ /* --- pbm/pgm (-g switch) --- */ /*int ispbmpgm = 0; (now global)*/ /* true to write pbm/pgm file */ -int type_pbmpgm(); /* entry point, graphic format */ +/*int type_pbmpgm();*/ /* entry point, graphic format */ char *pbm_outfile = (char *)NULL; /* output file defaults to stdout */ /* --- anti-aliasing --- */ intbyte *bytemap_raster = NULL, /* anti-aliased bitmap */ colors[256]; /* grayscale vals in bytemap */ -int aalowpass(), aapnm(), /*lowpass filters for anti-aliasing*/ +int /*aalowpass(), aapnm(),*/ /*lowpass filters for anti-aliasing*/ grayscale = 256; /* 0-255 grayscales in 8-bit bytes */ -int ncolors=2, /* #colors (2=b&w) */ - aacolormap(); /* build colormap from bytemap */ +int ncolors=2 /* #colors (2=b&w) */ + /*,aacolormap()*/; /* build colormap from bytemap */ int ipattern; /*patternnumcount[] index diagnostic*/ /* --- advertisement preprocessing --- */ -int advertisement(), crc16(); /*wrap expression in advertisement*/ +/*int advertisement(), crc16();*/ /*wrap expression in advertisement*/ char *adtemplate = NULL; /* usually use default message */ char *host_showad = HOST_SHOWAD; /* show ads only on this host */ /* --- messages --- */ char logfile[256] = LOGFILE, /*log queries if msglevel>=LOGLEVEL*/ cachelog[256] = CACHELOG; /* cached image log in cachepath/ */ -char *timestamp(); /* time stamp for logged messages */ -char *strdetex(); /* remove math chars from messages */ -int logger(); /* logs environ variables */ -int ismonth(); /* check argv[0] for current month */ +/*char *timestamp();*/ /* time stamp for logged messages */ +/*char *strdetex();*/ /* remove math chars from messages */ +/*int logger();*/ /* logs environ variables */ +/*int ismonth();*/ /* check argv[0] for current month */ char *progname = (argc>0?argv[0]:"noname"); /* name program executed as */ char *dashes = /* separates logfile entries */ "--------------------------------------------------------------------------"; @@ -16824,13 +16554,11 @@ if ( !isquery ) { /* empty query string */ strcpy(expression, /* and give user an error message */ "\\red\\small\\rm\\fbox{\\begin{gather}\\LaTeX~expression~not~supplied" "\\\\i.e.,~no~?query\\_string~given~to~mimetex.cgi\\end{gather}}"); } - isqempty = 1; /* signal empty query string */ } /* --- end-of-if(!isquery) --- */ /* --- * process command-line input args (if not a query) * ------------------------------------------------ */ -if ( !isquery /* don't have an html query string */ -|| ( /*isqempty &&*/ argc>1) ) /* or have command-line args */ +if ( !isquery || argc>1 ) { char *argsignal = ARGSIGNAL, /* signals start of mimeTeX args */ stopsignal[32] = "--"; /* default Unix end-of-args signal */ @@ -16878,7 +16606,8 @@ if ( !isquery /* don't have an html query string */ case 'g': ispbmpgm++; if ( arglen > 1 ) pbmpgmtype = atoi(field+1); /* -g2==>type=2 */ if ( 1 || *argv[argnum]=='-' ) argnum--; /*next arg is -switch*/ - else pbm_outfile = argv[argnum]; break; /*next arg is filename*/ + else pbm_outfile = argv[argnum]; /*next arg is filename*/ + break; case 'm': if ( argnum < argc ) msglevel = atoi(argv[argnum]); break; case 'o': istransparent = (istransparent?0:1); argnum--; break; case 'q': isqforce = 1; argnum--; break; @@ -17157,8 +16886,7 @@ if ( isquery /* not relevant if "interactive" */ if ( isquery /* not relevant if "interactive" */ && !ispassword ) /* nor if user supplied password */ if ( !isinvalidreferer ) /* nor if already invalid referer */ - { int iref=0, msgnum=(-999), /* denyreferer index, message# */ - whundredths = 0; /* or wait hundredths of a sec */ + { int iref=0, msgnum=(-999); /* denyreferer index, message# */ for ( iref=0; msgnum<0; iref++ ) { /* run through denyreferer[] table */ char *deny = denyreferer[iref].referer; /* referer to be denied */ if ( deny == NULL ) break; /* null signals end-of-table */ @@ -17174,7 +16902,6 @@ if ( isquery /* not relevant if "interactive" */ msgnum = denyreferer[iref].msgnum; /* so set message# */ } /* --- end-of-for(iref) --- */ if ( msgnum >= 100 ) { /* wait but don't deny */ - whundredths = 10*(msgnum-100); /* hundredths=10*tenths */ msgnum = (-999); } /* reset valid referer */ if ( msgnum >= 0 ) { /* deny access to this referer */ if ( msgnum > maxmsgnum ) msgnum = 0; /* keep index within bounds */ @@ -17329,7 +17056,7 @@ if ( (sp = rasterize(expression,size)) == NULL ) { /* failed to rasterize */ /* --- magnify entire image here if we need >>bit< 1 && magstep <= 10 ) { /* magnify entire bitmap image */ - raster *rastmag(), *magrp=NULL; /* bitmap magnify function */ + raster /**rastmag(),*/ *magrp=NULL; /* bitmap magnify function */ int baseline = sp->baseline; /* original image baseline */ magrp = rastmag(sp->image,magstep); /* magnify raster image */ if ( magrp != NULL ) { /* succeeded to magnify image */ @@ -17432,7 +17159,7 @@ if ( isaa ) /* we want anti-aliased bitmap */ * --------------------------------------------------------------- */ if ( 1 ) { /* or use rastmag() above instead */ if ( magstep > 1 && magstep <= 10 ) { /*magnify entire bytemap image*/ - intbyte *bytemapmag(), *magmap=NULL; /* bytemap magnify function */ + intbyte /**bytemapmag(),*/ *magmap=NULL; /*bytemap magnify function*/ magmap=bytemapmag(bytemap_raster,raster_width,raster_height,magstep); if ( magmap != NULL ) { /* succeeded to magnify image */ free(bytemap_raster); /* free original bytemap image */ @@ -17614,14 +17341,13 @@ if ( (isquery && !ispbmpgm) /* called from browser (usual) */ emit mime XBITMAP image ------------------------------------------------------------------------- */ xbitmap_raster(bp,stdout); /* default emits mime xbitmap */ - #endif + #endif /*GIF*/ } /* --- end-of-if(isquery) --- */ /* --- exit --- */ end_of_job: if ( !isss ) /*bytemap raster in sp for supersamp*/ if ( bytemap_raster != NULL ) free(bytemap_raster);/*free bytemap_raster*/ if (colormap_raster != NULL )free(colormap_raster); /*and colormap_raster*/ - if ( 0 && gif_buffer != NULL ) free(gif_buffer); /* free malloced buffer */ if ( 1 && sp != NULL ) delete_subraster(sp); /* and free expression */ if ( msgfp != NULL /* have message/log file open */ && msgfp != stdout ) /* and it's not stdout */ @@ -17707,7 +17433,7 @@ return main ( argc, argv * Notes: o There's a three day "grace period", e.g., Dec 3 mtaches Nov. * ======================================================================= */ /* --- entry point --- */ -int ismonth ( char *month ) +FUNCSCOPE int ismonth ( char *month ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -17768,14 +17494,15 @@ if ( mday >= 31-ngrace ) /* 28-31 within grace period */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int logger ( FILE *logfp, int msglevel, char *message, logdata *logvars ) +FUNCSCOPE int logger ( FILE *logfp, int msglevel, + char *message, logdata *logvars ) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ FILE *fp = (logfp!=NULL?logfp:msgfp); /* use caller's logfp, or msgfp */ int ilog=0, nlogged=0; /* logvars[] index, #vars logged */ -char *timestamp(); /* timestamp logged */ +/*char *timestamp();*/ /* timestamp logged */ char *value = NULL; /* getenv(name) to be logged */ static int ncalls = 0; /* #calls (headers on 1st call) */ static char *dashes = @@ -17822,12 +17549,12 @@ end_of_job: return ( nlogged ); /* back to caller */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int emitcache ( char *cachefile, int maxage, int valign, int isbuffer ) +FUNCSCOPE int emitcache(char *cachefile, int maxage, int valign, int isbuffer) { /* ------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ -int nbytes=gifSize, readcachefile(); /* read cache file */ +int nbytes=gifSize /*, readcachefile()*/; /* read cache file */ FILE *emitptr = stdout; /* emit cachefile to stdout */ unsigned char buffer[MAXGIFSZ+1]; /* bytes from cachefile */ unsigned char *buffptr = buffer; /* ptr to buffer */ @@ -17907,7 +17634,7 @@ if ( isdumpgif && (0 || !isbuffer) ) { /* **debug** dump gif */ * Notes: o * ======================================================================= */ /* --- entry point --- */ -int readcachefile ( char *cachefile, unsigned char *buffer ) +FUNCSCOPE int readcachefile ( char *cachefile, unsigned char *buffer ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -17964,7 +17691,7 @@ while ( 1 ) * Notes: o * ======================================================================= */ /* --- entry point --- */ -int advertisement ( char *expression, char *message ) +FUNCSCOPE int advertisement ( char *expression, char *message ) { /* ------------------------------------------------------------------------- Allocations and Declarations @@ -17984,7 +17711,7 @@ char *adtemplate = char adbuffer[MAXEXPRSZ+2048]; /*construct wrapped expression here*/ char *beginmath = " ", /* start math mode */ *endmath = " "; /* end math mode */ -int strreplace(); /* replace %%keywords%% with values*/ +/*int strreplace();*/ /* replace %%keywords%% with values*/ /* ------------------------------------------------------------------------- wrap expression in advertisement -------------------------------------------------------------------------- */ @@ -18015,7 +17742,7 @@ return ( 1 ); /* always just return 1 */ * Notes: o From Numerical Recipes in C, 2nd ed, page 900. * ======================================================================= */ /* --- entry point --- */ -int crc16 ( char *s ) +FUNCSCOPE int crc16 ( char *s ) { /* ------------------------------------------------------------------------- Compute the crc @@ -18053,21 +17780,27 @@ return ( (int)crc ); /* back to caller with crc */ * by four functions P1()...P4() to accommodate a problem * with Compaq's vax/vms C compiler. * ======================================================================= */ -/* --- #include "md5.h" --- */ -#ifndef uint8 - #define uint8 unsigned char -#endif -#ifndef uint32 - #define uint32 unsigned long int +#if 0 + /* --- + * >> Note: uint8, uint32 and md5_context now defined in mimetex.h << + * (they're temporarily left here only as comments) + * --------------------------------------------------------------------- */ + /* --- #include "md5.h" --- */ + #ifndef uint8 + #define uint8 unsigned char + #endif + #ifndef uint32 + #define uint32 unsigned long int + #endif + typedef struct + { uint32 total[2]; + uint32 state[4]; + uint8 buffer[64]; + } md5_context; #endif -typedef struct - { uint32 total[2]; - uint32 state[4]; - uint8 buffer[64]; - } md5_context; -void md5_starts( md5_context *ctx ); -void md5_update( md5_context *ctx, uint8 *input, uint32 length ); -void md5_finish( md5_context *ctx, uint8 digest[16] ); +FUNCSCOPE void md5_starts( md5_context *ctx ); +FUNCSCOPE void md5_update( md5_context *ctx, uint8 *input, uint32 length ); +FUNCSCOPE void md5_finish( md5_context *ctx, uint8 digest[16] ); /* --- md5.h --- */ #define GET_UINT32(n,b,i) \ { (n) = ( (uint32) (b)[(i) ] ) \ @@ -18080,25 +17813,29 @@ void md5_finish( md5_context *ctx, uint8 digest[16] ); (b)[(i) + 2] = (uint8) ( (n) >> 16 ); \ (b)[(i) + 3] = (uint8) ( (n) >> 24 ); } /* --- P,S,F macros defined as functions --- */ +FUNCSCOPE void P1(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t) { *a += (uint32)(d ^ (b & (c ^ d))) + X[k] + t; *a = ((*a<> (32-s))) + b; return; } +FUNCSCOPE void P2(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t) { *a += (uint32)(c ^ (d & (b ^ c))) + X[k] + t; *a = ((*a<> (32-s))) + b; return; } +FUNCSCOPE void P3(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t) { *a += (uint32)(b ^ c ^ d) + X[k] + t; *a = ((*a<> (32-s))) + b; return; } +FUNCSCOPE void P4(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t) { *a += (uint32)(c ^ (b | ~d)) + X[k] + t; *a = ((*a<> (32-s))) + b; return; } /* --- entry point (this one little stub written by me)--- */ -char *md5str( char *instr ) +FUNCSCOPE char *md5str( char *instr ) { static char outstr[64]; unsigned char md5sum[16]; md5_context ctx; @@ -18112,7 +17849,7 @@ char *md5str( char *instr ) return ( outstr ); } /* --- entry point (all md5 functions below by Christophe Devine) --- */ -void md5_starts( md5_context *ctx ) +FUNCSCOPE void md5_starts( md5_context *ctx ) { ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; @@ -18120,7 +17857,7 @@ void md5_starts( md5_context *ctx ) ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; } -void md5_process( md5_context *ctx, uint8 data[64] ) +FUNCSCOPE void md5_process( md5_context *ctx, uint8 data[64] ) { uint32 X[16], A, B, C, D; GET_UINT32( X[0], data, 0 ); GET_UINT32( X[1], data, 4 ); @@ -18211,7 +17948,7 @@ void md5_process( md5_context *ctx, uint8 data[64] ) ctx->state[2] += C; ctx->state[3] += D; } -void md5_update( md5_context *ctx, uint8 *input, uint32 length ) +FUNCSCOPE void md5_update( md5_context *ctx, uint8 *input, uint32 length ) { uint32 left, fill; if( length < 1 ) return; left = ctx->total[0] & 0x3F; @@ -18235,7 +17972,7 @@ void md5_update( md5_context *ctx, uint8 *input, uint32 length ) memcpy( (void *) (ctx->buffer + left), (void *) input, length ); } -void md5_finish( md5_context *ctx, uint8 digest[16] ) +FUNCSCOPE void md5_finish( md5_context *ctx, uint8 digest[16] ) { static uint8 md5_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -18292,36 +18029,4 @@ return pixval; #endif /* gif */ #endif /* driver */ #endif /* PART1 */ - - -int mystrncmpi(const char* s1, const char* s2,int n) -{ - int i=0; - while((s1[i]!='\0' || s2[i]!='\0') && ipixsz==1? getlongbit((rp)->pixmap,PIXDEX(rp,(irow),(icol))) :\ ((rp)->pixsz==8? ((rp)->pixmap)[PIXDEX(rp,(irow),(icol))] : (-1)) ) /* --- set value of pixel, either one bit or one byte, at (irow,icol) --- */ -#define setpixel(rp,irow,icol,value) /*set bit or byte based on pixsz*/ \ - if ( (rp)->pixsz == 1 ) /*set pixel to 1 or 0 for bitmap*/ \ - if ( (value) != 0 ) /* turn bit pixel on */ \ - { setlongbit((rp)->pixmap,PIXDEX(rp,(irow),(icol))); } \ - else /* or turn bit pixel 0ff */ \ - { unsetlongbit((rp)->pixmap,PIXDEX(rp,(irow),(icol))); } \ - else /* set 8-bit bytemap pixel value */ \ - if ( (rp)->pixsz == 8 ) /* check pixsz=8 for bytemap */ \ - ((rp)->pixmap)[PIXDEX(rp,(irow),(icol))]=(pixbyte)(value); \ - else /* let user supply final ; */ + +/*set bit or byte based on pixsz*/ +static inline void setpixel(raster * rp, int irow, int icol, int value) { + if ( rp->pixsz == 1 ) { /*set pixel to 1 or 0 for bitmap*/ + if ( value != 0 ) /* turn bit pixel on */ + { setlongbit(rp->pixmap,PIXDEX(rp,irow,icol)); } + else /* or turn bit pixel 0ff */ + { unsetlongbit(rp->pixmap,PIXDEX(rp,irow,icol)); } + } else /* set 8-bit bytemap pixel value */ + if ( rp->pixsz == 8 ) /* check pixsz=8 for bytemap */ + (rp->pixmap)[PIXDEX(rp,irow,icol)]=(pixbyte)value; +} /* -------------------------------------------------------------------------- some char classes tokenizer needs to recognize, and macros to check for them @@ -413,11 +440,315 @@ subraster #define FRACRASTER (4) /* image of \frac{}{} */ #define ASCIISTRING (5) /* ascii string (not a raster) */ + +/* --- + * note: point3d.x,y,z are relative to the origin 0.,0.,0. of an abstract + * coordinate system, calculated to be at the center pixel of a raster. + * point3d and matrix3d are used for rotations, as per + * https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions + * in function rotrast3d() + * ------------------------------------------------------------------------ */ +/* --- 3d-point --- */ +#define point3d struct point3d_struct /* "typedef" for point3d_struct */ +point3d { + /* --- x,y,z-coords relative to 0.,0.,0. origin of abstract coord axes --- */ + double x; /* x-coord */ + double y; /* y-coord */ + double z; /* z-coord */ + } ; /* --- end-of-point3d_struct --- */ +/* --- 3d-matrix (rotation matrix) stored row-wise --- */ +#define matrix3d struct matrix3d_struct /* "typedef" for matrix3d_struct */ +matrix3d { + /* --- 3x3 matrix stored row-wise --- */ + point3d xrow; /* x-row */ + point3d yrow; /* y-row */ + point3d zrow; /* z-row */ + } ; /* --- end-of-matrix3d_struct --- */ + +/* ------------------------------------------------------------------------- +store for evalterm() [n.b., these are stripped-down funcs from nutshell] +-------------------------------------------------------------------------- */ +#define STORE struct store_struct /* "typedef" for store struct */ +#define MAXSTORE 100 /* max 100 identifiers */ +STORE { + char *identifier; /* identifier */ + int *value; /* address of corresponding value */ + } ; /* --- end-of-store_struct --- */ + +/* ------------------------------------------------------------------------- +logging data structure (default data to be logged remains in mimetex.c) +-------------------------------------------------------------------------- */ +/* --- logging data structure --- */ +#define logdata struct logdata_struct /* "typedef" for logdata_struct*/ +logdata { + /* ----------------------------------------------------------------------- + environment variable name, max #chars to display, min msglevel to display + ------------------------------------------------------------------------ */ + char *name; /* environment variable name */ + int maxlen; /* max #chars to display */ + int msglevel; /* min msglevel to display data */ + } ; /* --- end-of-logdata_struct --- */ + +/* --- + * from #include "md5.h" (for md5 functions) + * -------------------------------------------- */ +#ifndef uint8 + #define uint8 unsigned char +#endif +#ifndef uint32 + #define uint32 unsigned long int +#endif +typedef struct + { uint32 total[2]; + uint32 state[4]; + uint8 buffer[64]; + } md5_context; + /* --- - * issue rasterize() call end extract embedded raster from returned subraster - * -------------------------------------------------------------------------- */ -subraster *rasterize(); /* declare rasterize */ -#define make_raster(expression,size) ((rasterize(expression,size))->image) + * Function Prototypes and Scope (to enable static function scope, + * avoiding function name collisions when compiling together with + * other modules) + * ----------------------------------------------------------------- */ +FUNCSCOPE raster *new_raster ( int width, int height, int pixsz ); +FUNCSCOPE subraster *new_subraster ( int width, int height, int pixsz ); +FUNCSCOPE int delete_raster ( raster *rp ); +FUNCSCOPE int delete_subraster ( subraster *sp ); +FUNCSCOPE raster *rastcpy ( raster *rp ); +FUNCSCOPE subraster *subrastcpy ( subraster *sp ); +FUNCSCOPE raster *rastrot ( raster *rp ); +FUNCSCOPE raster *rastrot3d ( raster *rp, point3d *axis, double theta ); +FUNCSCOPE raster *rastmag ( raster *rp, int magstep ); +FUNCSCOPE intbyte *bytemapmag ( intbyte *bytemap, + int width, int height, int magstep ); +FUNCSCOPE raster *rastref ( raster *rp, int axis ); +FUNCSCOPE int rastput ( raster *target, raster *source, + int top, int left, int isopaque ); +FUNCSCOPE subraster *rastcompose ( subraster *sp1, subraster *sp2, + int offset2, int isalign, int isfree ); +FUNCSCOPE subraster *rastcat ( subraster *sp1, subraster *sp2, int isfree ); +FUNCSCOPE subraster *rastack ( subraster *sp1, subraster *sp2, int base, + int space, int iscenter, int isfree ); +FUNCSCOPE int rastsmash ( subraster *sp1, subraster *sp2 ); +FUNCSCOPE int rastsmashcheck ( char *term ); +FUNCSCOPE subraster *accent_subraster ( int accent, int width, int height, + int direction, int pixsz ); +FUNCSCOPE subraster *arrow_subraster ( int width, int height, int pixsz, + int drctn, int isBig ); +FUNCSCOPE subraster *uparrow_subraster ( int width, int height, int pixsz, + int drctn, int isBig ); +FUNCSCOPE int rule_raster ( raster *rp, int top, int left, + int width, int height, int type ); +FUNCSCOPE int line_raster ( raster *rp, int row0, int col0, + int row1, int col1, int thickness ); +FUNCSCOPE int line_recurse ( raster *rp, double row0, double col0, + double row1, double col1, int thickness ); +FUNCSCOPE int circle_raster ( raster *rp, int row0, int col0, + int row1, int col1, int thickness, char *quads ); +FUNCSCOPE int circle_recurse ( raster *rp, int row0, int col0, int row1, + int col1, int thickness, double theta0, double theta1 ); +FUNCSCOPE int bezier_raster ( raster *rp, double r0, double c0, + double r1, double c1, double rt, double ct ); +FUNCSCOPE raster *border_raster ( raster *rp, int ntop, int nbot, + int isline, int isfree ); +FUNCSCOPE raster *backspace_raster ( raster *rp, int nback, int *pback, + int minspace, int isfree ); +FUNCSCOPE int type_raster ( raster *rp, FILE *fp ); +FUNCSCOPE int type_bytemap ( intbyte *bp, int grayscale, + int width, int height, FILE *fp ); +#if !defined (GIF) +FUNCSCOPE int xbitmap_raster ( raster *rp, FILE *fp ); +FUNCSCOPE int hex_bitmap ( raster *rp, FILE *fp, int col1, int isstr ); +#endif +FUNCSCOPE int type_pbmpgm ( raster *rp, int ptype, char *file ); +FUNCSCOPE subraster *read_pbm ( FILE *fp, double sf ); +FUNCSCOPE raster *gftobitmap ( raster *gf ); +FUNCSCOPE mathchardef *get_symdef ( char *symbol ); +FUNCSCOPE int get_ligature ( char *expression, int family ); +FUNCSCOPE chardef *get_chardef ( mathchardef *symdef, int size ); +FUNCSCOPE subraster *get_charsubraster ( mathchardef *symdef, int size ); +FUNCSCOPE subraster *get_symsubraster ( char *symbol, int size ); +FUNCSCOPE int get_baseline ( chardef *gfdata ); +FUNCSCOPE subraster *get_delim ( char *symbol, int height, int family ); +FUNCSCOPE subraster *make_delim ( char *symbol, int height ); +FUNCSCOPE char *texchar ( char *expression, char *chartoken ); +FUNCSCOPE char *texsubexpr ( char *expression, char *subexpr, + int maxsubsz, char *left, char *right, + int isescape, int isdelim ); +FUNCSCOPE char *texleft ( char *expression, char *subexpr, int maxsubsz, + char *ldelim, char *rdelim ); +FUNCSCOPE char *texscripts ( char *expression, char *subscript, + char *superscript, int which ); +FUNCSCOPE int isbrace ( char *expression, char *braces, int isescape ); +FUNCSCOPE char *preamble ( char *expression, int *size, char *subexpr ); +FUNCSCOPE char *mimeprep ( char *expression ); +FUNCSCOPE char *strchange ( int nfirst, char *from, char *to ); +FUNCSCOPE int strreplace(char *string,char *from,char *to,int nreplace); +FUNCSCOPE char *strwstr(char *string,char *substr,char *white,int *sublen); +FUNCSCOPE char *strdetex ( char *s, int mode ); +FUNCSCOPE char *strtexchr ( char *string, char *texchr ); +FUNCSCOPE char *findbraces ( char *expression, char *command ); +/*FUNCSCOPE char *strpspn ( char *s, char *reject, char *segment );*/ +FUNCSCOPE int isstrstr ( char *string, char *snippets, int iscase ); +FUNCSCOPE int isnumeric ( char *s ); +FUNCSCOPE int evalterm ( STORE *store, char *term ); +FUNCSCOPE int getstore ( STORE *store, char *identifier ); +FUNCSCOPE char *getdirective ( char *string, char *directive, + int iscase, int isvalid, int nargs, void *args ); +FUNCSCOPE char *strpspn ( char *s, char *reject, char *segment ); +FUNCSCOPE char *strqspn ( char *s, char *q, int isunescape ); +FUNCSCOPE int unescape_url(char *url, int isescape); +FUNCSCOPE char x2c(char *what); +FUNCSCOPE subraster *rasterize ( char *expression, int size ); +FUNCSCOPE subraster *rastparen ( char **subexpr, int size, subraster *basesp ); +FUNCSCOPE subraster *rastlimits ( char **expression, int size, + subraster *basesp ); +FUNCSCOPE subraster *rastscripts ( char **expression, int size, + subraster *basesp ); +FUNCSCOPE subraster *rastdispmath (char **expression, int size, subraster *sp); +/* --- + * handler functions for math operations + * ---------------------------------------- */ +FUNCSCOPE subraster *rastleft ( char **expression, int size, subraster *basesp, + int ildelim, int arg2, int arg3 ); +FUNCSCOPE subraster *rastmiddle(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastflags(char **expression, int size, subraster *basesp, + int flag, int value, int arg3); +FUNCSCOPE subraster *rastspace(char **expression, int size, subraster *basesp, + int width, int isfill, int isheight); +FUNCSCOPE subraster *rastnewline ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastarrow(char **expression, int size, subraster *basesp, + int drctn, int isBig, int arg3); +FUNCSCOPE subraster *rastuparrow ( char **expression, int size, + subraster *basesp, int drctn, int isBig, int arg3 ); +FUNCSCOPE subraster *rastoverlay ( char **expression, int size, + subraster *basesp, int overlay, int offset2, int arg3 ); +FUNCSCOPE subraster *rastfrac(char **expression, int size, subraster *basesp, + int isfrac, int arg2, int arg3); +FUNCSCOPE subraster *rastackrel ( char **expression, int size, + subraster *basesp, int base, int arg2, int arg3 ); +FUNCSCOPE subraster *rastmathfunc ( char **expression, int size, + subraster *basesp, int mathfunc, int islimits, int arg3 ); +FUNCSCOPE subraster *rastsqrt(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastaccent ( char **expression, int size, + subraster *basesp, int accent, int isabove, int isscript ); +FUNCSCOPE subraster *rastfont(char **expression, int size, subraster *basesp, + int ifontnum, int arg2, int arg3); +FUNCSCOPE subraster *rastbegin(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastarray(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastpicture ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastline(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastrule(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastcircle ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastbezier ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastraise(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastrotate ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastmagnify ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastreflect ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastfbox(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastovalbox ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastinput(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastcounter ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rasteval(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastmathtex ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rasttoday(char **expression, int size, subraster *basesp, + int arg1, int arg2, int arg3); +FUNCSCOPE subraster *rastcalendar ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastenviron ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastmessage ( char **expression, int size, + subraster *basesp, int arg1, int arg2, int arg3 ); +FUNCSCOPE subraster *rastnoop(char **expression, int size, subraster *basesp, + int nargs, int arg2, int arg3); +/* --- end-of-handler-functions-for-math-operations --- */ +FUNCSCOPE FILE *rastopenfile ( char *filename, char *mode ); +FUNCSCOPE char *rasteditfilename ( char *filename ); +FUNCSCOPE int rastreadfile ( char *filename, int islock, + char *tag, char *value ); +FUNCSCOPE int rastwritefile ( char *filename,char *tag, + char *value, int isstrict ); +FUNCSCOPE char *calendar( int year, int month, int day ); +FUNCSCOPE char *timestamp( int tzdelta, int ifmt ); +FUNCSCOPE int tzadjust ( int tzdelta, + int *year, int *month, int *day, int *hour ); +FUNCSCOPE int daynumber ( int year, int month, int day ); +FUNCSCOPE char *strwrap ( char *s, int linelen, int tablen ); +FUNCSCOPE char *strnlower ( char *s, int n ); +FUNCSCOPE char *urlprune ( char *url, int n ); +FUNCSCOPE int urlncmp ( char *url1, char *url2, int n ); +FUNCSCOPE char *dbltoa ( double dblval, int npts ); +FUNCSCOPE matrix3d *rotmatrix ( point3d *axis, double theta ); +FUNCSCOPE point3d *matmult ( matrix3d *mat, point3d *vec ); +FUNCSCOPE int aalowpass (raster *rp, intbyte *bytemap, int grayscale); +FUNCSCOPE int aapnm (raster *rp, intbyte *bytemap, int grayscale); +FUNCSCOPE int aapnmlookup (raster *rp, intbyte *bytemap, int grayscale); +FUNCSCOPE int aapatterns ( raster *rp, int irow, int icol, + int gridnum, int patternum, int grayscale ); +FUNCSCOPE int aapattern1124 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ); +FUNCSCOPE int aapattern19 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ); +FUNCSCOPE int aapattern20 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ); +FUNCSCOPE int aapattern39 ( raster *rp, int irow, int icol, + int gridnum, int grayscale ); +FUNCSCOPE int aafollowline ( raster *rp, int irow, int icol, + int direction ); +FUNCSCOPE int aagridnum ( raster *rp, int irow, int icol ); +FUNCSCOPE int aapatternnum ( int gridnum ); +FUNCSCOPE int aalookup ( int gridnum ); +FUNCSCOPE int aalowpasslookup ( raster *rp, intbyte *bytemap, + int grayscale ); +FUNCSCOPE int aasupsamp(raster *rp, raster **aa, int sf, int grayscale); +FUNCSCOPE raster *imgsupsamp ( raster *rp, double sf, int grayscale ); +FUNCSCOPE int ssweights(int width, int height, int maxwt, raster **wts); +FUNCSCOPE int aacolormap ( intbyte *bytemap, int nbytes, + intbyte *colors, intbyte *colormap ); +FUNCSCOPE raster *aaweights ( int width, int height ); +FUNCSHARED int mimetexsetmsg ( int newmsglevel, FILE *newmsgfp ); +FUNCSHARED unsigned char *mimetexgetbytemap ( char *expression, + int *width, int *height ); + /* int main ( int argc, char *argv[] ); */ + /* int CreateGifFromEq ( char *expression, char *gifFileName ); */ +FUNCSCOPE int ismonth ( char *month ); +FUNCSCOPE int logger ( FILE *logfp, int msglevel, + char *message, logdata *logvars ); +FUNCSCOPE int emitcache(char *cachefile, int maxage, int valign, + int isbuffer); +FUNCSCOPE int readcachefile ( char *cachefile, unsigned char *buffer ); +FUNCSCOPE int advertisement ( char *expression, char *message ); +FUNCSCOPE int crc16 ( char *s ); +FUNCSCOPE void + P1(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t), + P2(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t), + P3(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t), + P4(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t); +FUNCSCOPE char *md5str( char *instr ); +FUNCSCOPE void md5_starts(md5_context *ctx); +FUNCSCOPE void md5_process(md5_context *ctx, uint8 data[64]); +FUNCSCOPE void md5_update(md5_context *ctx, uint8 *input, uint32 length); +FUNCSCOPE void md5_finish(md5_context *ctx, uint8 digest[16]); + /* int GetPixel ( int x, int y ); */ /* ------------------------------------------------------------------------- @@ -570,43 +901,47 @@ STATIC int shrinkfactors[] /*supersampling shrinkfactor by size*/ /* --- * handler functions for math operations - * ------------------------------------- */ -subraster *rastflags(); /* set flags, e.g., for \rm */ -subraster *rastfrac(); /* handle \frac \atop expressions */ -subraster *rastackrel(); /* handle \stackrel expressions */ -subraster *rastmathfunc(); /* handle \lim,\log,etc expressions*/ -subraster *rastoverlay(); /* handle \not */ -subraster *rastspace(); /* handle math space, \hspace,\hfill*/ -subraster *rastnewline(); /* handle \\ newline */ -subraster *rastarrow(); /* handle \longrightarrow, etc */ -subraster *rastuparrow(); /* handle \longuparrow, etc */ -subraster *rastsqrt(); /* handle \sqrt */ -subraster *rastaccent(); /* handle \hat \vec \braces, etc */ -subraster *rastfont(); /* handle \cal{} \scr{}, etc */ -subraster *rastbegin(); /* handle \begin{}...\end{} */ -subraster *rastleft(); /* handle \left...\right */ -subraster *rastmiddle(); /* handle \left...\middle...\right */ -subraster *rastarray(); /* handle \array{...} */ -subraster *rastpicture(); /* handle \picture(,){...} */ -subraster *rastline(); /* handle \line(xinc,yinc){xlen} */ -subraster *rastrule(); /* handle \rule[lift]{width}{height}*/ -subraster *rastcircle(); /* handle \circle(xdiam[,ydiam]) */ -subraster *rastbezier(); /*handle\bezier(c0,r0)(c1,r1)(ct,rt)*/ -subraster *rastraise(); /* handle \raisebox{lift}{expr} */ -subraster *rastrotate(); /* handle \rotatebox{degs}{expr} */ -subraster *rastmagnify(); /* handle \magnify{magstep}{expr} */ -subraster *rastreflect(); /* handle \reflectbox[axis]{expr} */ -subraster *rastfbox(); /* handle \fbox{expr} */ -subraster *rastovalbox(); /* handle \ovalbox{expr} */ -subraster *rastinput(); /* handle \input{filename} */ -subraster *rastcounter(); /* handle \counter{filename} */ -subraster *rasteval(); /* handle \eval{expression} */ -subraster *rastmathtex(); /* handle \mathtex{expression} */ -subraster *rasttoday(); /* handle \today[+/-tzdelta,ifmt] */ -subraster *rastcalendar(); /* handle \calendar[yaer,month] */ -subraster *rastenviron(); /* handle \environment */ -subraster *rastmessage(); /* handle \message */ -subraster *rastnoop(); /* handle \escape's to be flushed */ + * ---------------------------------------- */ +#if 0 /* --- now declared above --- */ + FUNCSCOPE subraster + *rastflags(), /* set flags, e.g., for \rm */ + *rastfrac(), /* handle \frac \atop expressions */ + *rastackrel(), /* handle \stackrel expressions */ + *rastmathfunc(), /* handle \lim,\log,etc expressions*/ + *rastoverlay(), /* handle \not */ + *rastspace(), /* handle math space, \hspace,\hfill*/ + *rastnewline(), /* handle \\ newline */ + *rastarrow(), /* handle \longrightarrow, etc */ + *rastuparrow(), /* handle \longuparrow, etc */ + *rastsqrt(), /* handle \sqrt */ + *rastaccent(), /* handle \hat \vec \braces, etc */ + *rastfont(), /* handle \cal{} \scr{}, etc */ + *rastbegin(), /* handle \begin{}...\end{} */ + *rastleft(), /* handle \left...\right */ + *rastmiddle(), /* handle \left...\middle...\right */ + *rastarray(), /* handle \array{...} */ + *rastpicture(), /* handle \picture(,){...} */ + *rastline(), /* handle \line(xinc,yinc){xlen} */ + *rastrule(), /* handle \rule[lift]{width}{height}*/ + *rastcircle(), /* handle \circle(xdiam[,ydiam]) */ + *rastbezier(), /* handle\bezier(c0,r0)(c1,r1)(ct,rt)*/ + *rastraise(), /* handle \raisebox{lift}{expr} */ + *rastrotate(), /* handle \rotatebox{degs}{expr} */ + *rastmagnify(), /* handle \magnify{magstep}{expr} */ + *rastreflect(), /* handle \reflectbox[axis]{expr} */ + *rastfbox(), /* handle \fbox{expr} */ + *rastovalbox(), /* handle \ovalbox{expr} */ + *rastinput(), /* handle \input{filename} */ + *rastcounter(), /* handle \counter{filename} */ + *rasteval(), /* handle \eval{expression} */ + *rastmathtex(), /* handle \mathtex{expression} */ + *rasttoday(), /* handle \today[+/-tzdelta,ifmt] */ + *rastcalendar(), /* handle \calendar[yaer,month] */ + *rastenviron(), /* handle \environment */ + *rastmessage(), /* handle \message */ + *rastnoop() /* handle \escape's to be flushed */ + ; /* --- end-of-functions-for-math-operations --- */ +#endif /* --- sqrt --- */ #define SQRTACCENT (1) /* \sqrt */ @@ -2263,7 +2598,7 @@ STATIC mathchardef symtable[] } #endif /* INITVALS */ ; /* --- end-of-symtable[] --- */ - /* ======================= END-OF-FILE MIMETEX.H ========================= */ -#endif +#endif /*defined(_MIMETEXMAIN)*/ +#endif /*defined(_MIMETEX)*/ diff --git a/thirdParty/mimetex/mimetex.html b/thirdParty/mimetex/mimetex.html index eb9522b89..777e764e7 100644 --- a/thirdParty/mimetex/mimetex.html +++ b/thirdParty/mimetex/mimetex.html @@ -1,6 +1,6 @@