diff --git a/LedOK/7z/readme.txt b/LedOK/7z/readme.txt index 4437a5c..1f7c2a3 100644 --- a/LedOK/7z/readme.txt +++ b/LedOK/7z/readme.txt @@ -1,51 +1,51 @@ -7-Zip 21.07 ------------ - -7-Zip is a file archiver for Windows. - -7-Zip Copyright (C) 1999-2021 Igor Pavlov. - -The main features of 7-Zip: - - - High compression ratio in the new 7z format - - Supported formats: - - Packing / unpacking: 7z, XZ, BZIP2, GZIP, TAR, ZIP and WIM. - - Unpacking only: AR, ARJ, Base64, CAB, CHM, CPIO, CramFS, DMG, EXT, FAT, GPT, HFS, - IHEX, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, QCOW2, RAR, - RPM, SquashFS, UDF, UEFI, VDI, VHD, VHDX, VMDK, XAR and Z. - - Fast compression and decompression - - Self-extracting capability for 7z format - - Strong AES-256 encryption in 7z and ZIP formats - - Integration with Windows Shell - - Powerful File Manager - - Powerful command line version - - Localizations for 90 languages - - -7-Zip is free software distributed under the GNU LGPL (except for unRar code). -Read License.txt for more information about license. - - - This distribution package contains the following files: - - 7zFM.exe - 7-Zip File Manager - 7-zip.dll - Plugin for Windows Shell - 7-zip32.dll - Plugin for Windows Shell (32-bit plugin for 64-bit system) - 7zg.exe - GUI module - 7z.exe - Command line version - 7z.dll - 7-Zip engine module - 7z.sfx - SFX module (Windows version) - 7zCon.sfx - SFX module (Console version) - - License.txt - License information - readme.txt - This file - History.txt - History of 7-Zip - 7-zip.chm - User's Manual in HTML Help format - descript.ion - Description for files - - Lang\en.ttt - English (base) localization file - Lang\*.txt - Localization files - - ---- -End of document +7-Zip 21.07 +----------- + +7-Zip is a file archiver for Windows. + +7-Zip Copyright (C) 1999-2021 Igor Pavlov. + +The main features of 7-Zip: + + - High compression ratio in the new 7z format + - Supported formats: + - Packing / unpacking: 7z, XZ, BZIP2, GZIP, TAR, ZIP and WIM. + - Unpacking only: AR, ARJ, Base64, CAB, CHM, CPIO, CramFS, DMG, EXT, FAT, GPT, HFS, + IHEX, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, QCOW2, RAR, + RPM, SquashFS, UDF, UEFI, VDI, VHD, VHDX, VMDK, XAR and Z. + - Fast compression and decompression + - Self-extracting capability for 7z format + - Strong AES-256 encryption in 7z and ZIP formats + - Integration with Windows Shell + - Powerful File Manager + - Powerful command line version + - Localizations for 90 languages + + +7-Zip is free software distributed under the GNU LGPL (except for unRar code). +Read License.txt for more information about license. + + + This distribution package contains the following files: + + 7zFM.exe - 7-Zip File Manager + 7-zip.dll - Plugin for Windows Shell + 7-zip32.dll - Plugin for Windows Shell (32-bit plugin for 64-bit system) + 7zg.exe - GUI module + 7z.exe - Command line version + 7z.dll - 7-Zip engine module + 7z.sfx - SFX module (Windows version) + 7zCon.sfx - SFX module (Console version) + + License.txt - License information + readme.txt - This file + History.txt - History of 7-Zip + 7-zip.chm - User's Manual in HTML Help format + descript.ion - Description for files + + Lang\en.ttt - English (base) localization file + Lang\*.txt - Localization files + + +--- +End of document diff --git a/LedOK/LedOK.pro b/LedOK/LedOK.pro index 9a7adde..baeca29 100644 --- a/LedOK/LedOK.pro +++ b/LedOK/LedOK.pro @@ -1,313 +1,300 @@ -QT += core gui widgets -QT += multimedia -QT += network -QT += concurrent -QT += serialport -QT += opengl -QT += webenginewidgets - -CONFIG += c++20 -CONFIG += lrelease -CONFIG += embed_translations -# CONFIG += console - -# You can also make your code fail to compile if you use deprecated APIs. -# In order to do so, uncomment the following line. -# You can also select to disable deprecated APIs only up to a certain version of Qt. -#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 - -TARGET = $$quote(LedOK Express) -VERSION = 1.3.0 -DEFINES += APP_VERSION=\\\"$$VERSION\\\" -msvc { - QMAKE_CXXFLAGS += -execution-charset:utf-8 - QMAKE_CXXFLAGS += -source-charset:utf-8 - - CONFIG += force_debug_info - CONFIG += separate_debug_info -} -win* { - LIBS += -lwinmm - LIBS += -lDbghelp -} -win32 { -QMAKE_LFLAGS += /LARGEADDRESSAWARE -#QMAKE_LFLAGS += -Wl,--large-address-aware -} - -SOURCES += \ - base/aboutdlg.cpp \ - base/changepasswordform.cpp \ - base/customprogressindicator.cpp \ - base/loemptydialog.cpp \ - base/pixbmpshowdialog.cpp \ - base/qiplineedit.cpp \ - base/softconfigdialog.cpp \ - base/switchcontrol.cpp \ - base/taesclass.cpp \ - base/updateledset3dialog.cpp \ - base/updaterdialog.cpp \ - base/x_checkboxdelegate.cpp \ - base/x_spinboxdelegate.cpp \ - base/x_timeeditdelegate.cpp \ - base/x_uimsgboxok.cpp \ - base/extendedgroupbox.cpp \ - base/ffutil.cpp \ - base/locolorselector.cpp \ - base/lodateselector.cpp \ - base/loqtitlebar.cpp \ - base/loqtreewidget.cpp \ - base/table.cpp \ - base/waitingdlg.cpp \ - basedlg.cpp \ - basewin.cpp \ - cfg.cpp \ - communication/hpptclient.cpp \ - communication/taserialthread.cpp \ - devicectrlpanel.cpp \ - deviceitem.cpp \ - devicepanel.cpp \ - ffplayer.cpp \ - globaldefine.cpp \ - main.cpp \ - mainwindow.cpp \ - mguangyingpinwidget.cpp \ - passwordindlg.cpp \ - player/digiclock.cpp \ - player/eleanaclock.cpp \ - player/elebase.cpp \ - player/eleborder.cpp \ - player/elegif.cpp \ - player/eleimg.cpp \ - player/elemultipng.cpp \ - player/elescroll.cpp \ - player/eletimer.cpp \ - player/elevideo.cpp \ - player/playwin.cpp \ - player/posdlg.cpp \ - progpanel.cpp \ - synctimer.cpp \ - tcpsocket.cpp \ - test.cpp \ - tipdialog.cpp \ - tools.cpp \ - wDevicesManager/controlencryptwidget.cpp \ - wDevicesManager/controlhdmischedule.cpp \ - wDevicesManager/controlhdmiwidget.cpp \ - wDevicesManager/controlnetconfigwidget.cpp \ - wDevicesManager/controlpowermanual.cpp \ - wDevicesManager/controlpowerschedule.cpp \ - wDevicesManager/controlpowerwidget.cpp \ - wDevicesManager/controltestwidget.cpp \ - wDevicesManager/controlvolumemanual.cpp \ - wDevicesManager/controlvolumeschedule.cpp \ - wDevicesManager/controlvolumewidget.cpp \ - wDevicesManager/ctrladvancedpanel.cpp \ - wDevicesManager/ctrlbrightpanel.cpp \ - wDevicesManager/ctrlverifyclockpanel.cpp \ - wDevicesManager/ledcard.cpp \ - wDevicesManager/threadupgradeapk.cpp \ - wDevicesManager/upgradeapkdialog.cpp \ - wDevicesManager/wupgradeapkitem.cpp \ - wProgramManager/eaclock.cpp \ - wProgramManager/eaudio.cpp \ - wProgramManager/ebase.cpp \ - wProgramManager/edclock.cpp \ - wProgramManager/eenviron.cpp \ - wProgramManager/egif.cpp \ - wProgramManager/emultiwin.cpp \ - wProgramManager/ephoto.cpp \ - wProgramManager/etext.cpp \ - wProgramManager/etimer.cpp \ - wProgramManager/evideo.cpp \ - wProgramManager/eweb.cpp \ - wProgramManager/gentmpthread.cpp \ - wProgramManager/pageeditor.cpp \ - wProgramManager/pagelistitem.cpp \ - wProgramManager/progcreatedlg.cpp \ - wProgramManager/progeditorwin.cpp \ - wProgramManager/progitem.cpp \ - wProgramManager/sendprogramdialog.cpp \ - wProgramManager/sendprogthread.cpp \ - wProgramManager/threadexportprogrampro.cpp \ - wProgramManager/usbdetectdialog.cpp \ - wProgramManager/videosplitthread.cpp \ - wProgramManager/wexportprogramitem.cpp \ - wProgramManager/wplanitem.cpp \ - wProgramManager/wplanlist.cpp \ - wProgramManager/wprogrampublishitem.cpp \ - -HEADERS += \ - base/aboutdlg.h \ - base/changepasswordform.h \ - base/customprogressindicator.h \ - base/loemptydialog.h \ - base/pixbmpshowdialog.h \ - base/qiplineedit.h \ - base/softconfigdialog.h \ - base/switchcontrol.h \ - base/taesclass.h \ - base/updateledset3dialog.h \ - base/updaterdialog.h \ - base/x_checkboxdelegate.h \ - base/x_spinboxdelegate.h \ - base/x_timeeditdelegate.h \ - base/x_uimsgboxok.h \ - base/extendedgroupbox.h \ - base/locolorselector.h \ - base/lodateselector.h \ - base/loqtitlebar.h \ - base/loqtreewidget.h \ - base/table.h \ - base/waitingdlg.h \ - basedlg.h \ - basewin.h \ - cfg.h \ - communication/hpptclient.h \ - communication/taserialthread.h \ - devicectrlpanel.h \ - deviceitem.h \ - devicepanel.h \ - ffplayer.h \ - globaldefine.h \ - gqt.h \ - mainwindow.h \ - mguangyingpinwidget.h \ - passwordindlg.h \ - player/digiclock.h \ - player/eleanaclock.h \ - player/elebase.h \ - player/eleborder.h \ - player/elegif.h \ - player/eleimg.h \ - player/elemultipng.h \ - player/elescroll.h \ - player/eletimer.h \ - player/elevideo.h \ - player/playwin.h \ - player/posdlg.h \ - progpanel.h \ - synctimer.h \ - tcpsocket.h \ - tipdialog.h \ - tools.h \ - wDevicesManager/controlencryptwidget.h \ - wDevicesManager/controlhdmischedule.h \ - wDevicesManager/controlhdmiwidget.h \ - wDevicesManager/controlnetconfigwidget.h \ - wDevicesManager/controlpowermanual.h \ - wDevicesManager/controlpowerschedule.h \ - wDevicesManager/controlpowerwidget.h \ - wDevicesManager/controltestwidget.h \ - wDevicesManager/controlvolumemanual.h \ - wDevicesManager/controlvolumeschedule.h \ - wDevicesManager/controlvolumewidget.h \ - wDevicesManager/ctrladvancedpanel.h \ - wDevicesManager/ctrlbrightpanel.h \ - wDevicesManager/ctrlverifyclockpanel.h \ - wDevicesManager/ledcard.h \ - wDevicesManager/threadupgradeapk.h \ - wDevicesManager/upgradeapkdialog.h \ - wDevicesManager/wupgradeapkitem.h \ - wProgramManager/eaclock.h \ - wProgramManager/eaudio.h \ - wProgramManager/ebase.h \ - wProgramManager/edclock.h \ - wProgramManager/eenviron.h \ - wProgramManager/egif.h \ - wProgramManager/emultiwin.h \ - wProgramManager/ephoto.h \ - wProgramManager/etext.h \ - wProgramManager/etimer.h \ - wProgramManager/evideo.h \ - wProgramManager/eweb.h \ - wProgramManager/gentmpthread.h \ - wProgramManager/pageeditor.h \ - wProgramManager/pagelistitem.h \ - wProgramManager/progcreatedlg.h \ - wProgramManager/progeditorwin.h \ - wProgramManager/progitem.h \ - wProgramManager/sendprogramdialog.h \ - wProgramManager/sendprogthread.h \ - wProgramManager/threadexportprogrampro.h \ - wProgramManager/usbdetectdialog.h \ - wProgramManager/videosplitthread.h \ - wProgramManager/wexportprogramitem.h \ - wProgramManager/wplanitem.h \ - wProgramManager/wplanlist.h \ - wProgramManager/wprogrampublishitem.h \ - -FORMS += \ - base/pixbmpshowdialog.ui \ - base/updateledset3dialog.ui \ - base/updaterdialog.ui \ - base/x_uimsgboxok.ui \ - mguangyingpinwidget.ui \ - tipdialog.ui \ - wDevicesManager/controlencryptwidget.ui \ - wDevicesManager/controlhdmischedule.ui \ - wDevicesManager/controlpowermanual.ui \ - wDevicesManager/controlpowerschedule.ui \ - wDevicesManager/controlpowerwidget.ui \ - wDevicesManager/controltestwidget.ui \ - wDevicesManager/controlvolumemanual.ui \ - wDevicesManager/controlvolumeschedule.ui \ - wDevicesManager/controlvolumewidget.ui \ - wDevicesManager/upgradeapkdialog.ui \ - wProgramManager/wplanitem.ui \ - -TRANSLATIONS += \ - translations/app_zh_CN.ts \ - translations/app_zh_TW.ts \ - translations/app_ja.ts \ - translations/app_en.ts - -EXTRA_TRANSLATIONS += \ - translations/qt_zh_CN.ts \ - translations/qt_zh_TW.ts \ - translations/qt_ja.ts \ - translations/qt_en.ts - -RESOURCES += \ - res.qrc \ - qss.qrc - -win32:RC_ICONS = res/Logo.ico -osx:ICON = res/Logo.icns - - -# Default rules for deployment. -qnx: target.path = /tmp/$${TARGET}/bin -else: unix:!android: target.path = /opt/$${TARGET}/bin -!isEmpty(target.path): INSTALLS += target - - - -INCLUDEPATH += $$PWD/ffmpeg/include -LIBS += -L$$PWD/ffmpeg/lib/\ - -lavcodec \ - -lavdevice \ - -lavfilter \ - -lavformat \ - -lavutil \ - -lswresample \ - -lswscale - -copy.files += $$files(ffmpeg/bin/*.dll) -copy.files += ffmpeg/bin/ffmpeg.exe - -include(./xlsx/qtxlsx.pri) -include(./QSimpleUpdater/QSimpleUpdater.pri) - -# for https requests -copy2.files += $$files(OpenSSL/*.dll) - -copy.files += 7z/7z.dll -copy.files += 7z/7z.exe - -copy.path = $$OUT_PWD -copy2.path = $$OUT_PWD/release - -CONFIG += file_copies -COPIES += copy -COPIES += copy2 +QT += core gui widgets +QT += multimedia +QT += network +QT += concurrent +QT += serialport +QT += opengl +QT += webenginewidgets + +CONFIG += c++20 +CONFIG += lrelease +CONFIG += embed_translations +# CONFIG += console + +# You can also make your code fail to compile if you use deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +TARGET = $$quote(LedOK Express) +VERSION = 1.3.5 +DEFINES += APP_VERSION=\\\"$$VERSION\\\" +msvc { + QMAKE_CXXFLAGS += -execution-charset:utf-8 + QMAKE_CXXFLAGS += -source-charset:utf-8 + + CONFIG += force_debug_info + CONFIG += separate_debug_info + +# QMAKE_LFLAGS_RELEASE += /MAP +# QMAKE_CFLAGS_RELEASE += /Zi +# QMAKE_LFLAGS_RELEASE += /debug /opt:ref + +# QMAKE_CXXFLAGS_RELEASE += $$QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO +# QMAKE_LFLAGS_RELEASE += $$QMAKE_LFLAGS_RELEASE_WITH_DEBUGINFO + + LIBS += -lDbgHelp +} +win* { + LIBS += -lwinmm + LIBS += -lDbghelp +} +win32 { +QMAKE_LFLAGS += /LARGEADDRESSAWARE +#QMAKE_LFLAGS += -Wl,--large-address-aware +} + +SOURCES += \ + base/aboutdlg.cpp \ + base/changepasswordform.cpp \ + base/customprogressindicator.cpp \ + base/loemptydialog.cpp \ + base/pixbmpshowdialog.cpp \ + base/qiplineedit.cpp \ + base/softconfigdialog.cpp \ + base/switchcontrol.cpp \ + base/taesclass.cpp \ + base/updateledset3dialog.cpp \ + base/x_checkboxdelegate.cpp \ + base/x_spinboxdelegate.cpp \ + base/x_timeeditdelegate.cpp \ + base/x_uimsgboxok.cpp \ + base/extendedgroupbox.cpp \ + base/ffutil.cpp \ + base/locolorselector.cpp \ + base/lodateselector.cpp \ + base/loqtitlebar.cpp \ + base/loqtreewidget.cpp \ + base/waitingdlg.cpp \ + basedlg.cpp \ + basewin.cpp \ + cfg.cpp \ + communication/hpptclient.cpp \ + communication/taserialthread.cpp \ + device/ctrlhdmipanel.cpp \ + device/ctrlnetworkpanel.cpp \ + device/ctrlpwdpanel.cpp \ + devicectrlpanel.cpp \ + deviceitem.cpp \ + devicepanel.cpp \ + ffplayer.cpp \ + globaldefine.cpp \ + gutil/qgui.cpp \ + gutil/qnetwork.cpp \ + main.cpp \ + mainwindow.cpp \ + mguangyingpinwidget.cpp \ + passwordindlg.cpp \ + player/digiclock.cpp \ + player/eleanaclock.cpp \ + player/elebase.cpp \ + player/eleborder.cpp \ + player/elegif.cpp \ + player/eleimg.cpp \ + player/elemultipng.cpp \ + player/elescroll.cpp \ + player/eletimer.cpp \ + player/elevideo.cpp \ + player/playwin.cpp \ + player/posdlg.cpp \ + progpanel.cpp \ + synctimer.cpp \ + test.cpp \ + tools.cpp \ + device/controlpowerschedule.cpp \ + device/controlpowerwidget.cpp \ + device/controltestwidget.cpp \ + device/controlvolumeschedule.cpp \ + device/controlvolumewidget.cpp \ + device/ctrladvancedpanel.cpp \ + device/ctrlbrightpanel.cpp \ + device/ctrlverifyclockpanel.cpp \ + device/ledcard.cpp \ + device/upgradeapkdialog.cpp \ + device/wupgradeapkitem.cpp \ + program/copydirthread.cpp \ + program/eaclock.cpp \ + program/eaudio.cpp \ + program/ebase.cpp \ + program/edclock.cpp \ + program/eenviron.cpp \ + program/egif.cpp \ + program/emultiwin.cpp \ + program/ephoto.cpp \ + program/etext.cpp \ + program/etimer.cpp \ + program/evideo.cpp \ + program/eweb.cpp \ + program/gentmpthread.cpp \ + program/pageeditor.cpp \ + program/pagelistitem.cpp \ + program/progcreatedlg.cpp \ + program/progeditorwin.cpp \ + program/progitem.cpp \ + program/sendprogramdialog.cpp \ + program/sendprogthread.cpp \ + program/usbdetectdialog.cpp \ + program/videosplitthread.cpp \ + program/wplanitem.cpp \ + program/wplanlist.cpp \ + program/wprogrampublishitem.cpp \ + +HEADERS += \ + base/aboutdlg.h \ + base/changepasswordform.h \ + base/customprogressindicator.h \ + base/loemptydialog.h \ + base/pixbmpshowdialog.h \ + base/qiplineedit.h \ + base/softconfigdialog.h \ + base/switchcontrol.h \ + base/taesclass.h \ + base/updateledset3dialog.h \ + base/x_checkboxdelegate.h \ + base/x_spinboxdelegate.h \ + base/x_timeeditdelegate.h \ + base/x_uimsgboxok.h \ + base/extendedgroupbox.h \ + base/locolorselector.h \ + base/lodateselector.h \ + base/loqtitlebar.h \ + base/loqtreewidget.h \ + base/waitingdlg.h \ + basedlg.h \ + basewin.h \ + cfg.h \ + communication/hpptclient.h \ + communication/taserialthread.h \ + device/ctrlhdmipanel.h \ + device/ctrlnetworkpanel.h \ + device/ctrlpwdpanel.h \ + devicectrlpanel.h \ + deviceitem.h \ + devicepanel.h \ + ffplayer.h \ + globaldefine.h \ + gutil/qgui.h \ + gutil/qnetwork.h \ + mainwindow.h \ + mguangyingpinwidget.h \ + passwordindlg.h \ + player/digiclock.h \ + player/eleanaclock.h \ + player/elebase.h \ + player/eleborder.h \ + player/elegif.h \ + player/eleimg.h \ + player/elemultipng.h \ + player/elescroll.h \ + player/eletimer.h \ + player/elevideo.h \ + player/playwin.h \ + player/posdlg.h \ + progpanel.h \ + synctimer.h \ + tools.h \ + device/controlpowerschedule.h \ + device/controlpowerwidget.h \ + device/controltestwidget.h \ + device/controlvolumeschedule.h \ + device/controlvolumewidget.h \ + device/ctrladvancedpanel.h \ + device/ctrlbrightpanel.h \ + device/ctrlverifyclockpanel.h \ + device/ledcard.h \ + device/upgradeapkdialog.h \ + device/wupgradeapkitem.h \ + program/copydirthread.h \ + program/eaclock.h \ + program/eaudio.h \ + program/ebase.h \ + program/edclock.h \ + program/eenviron.h \ + program/egif.h \ + program/emultiwin.h \ + program/ephoto.h \ + program/etext.h \ + program/etimer.h \ + program/evideo.h \ + program/eweb.h \ + program/gentmpthread.h \ + program/pageeditor.h \ + program/pagelistitem.h \ + program/progcreatedlg.h \ + program/progeditorwin.h \ + program/progitem.h \ + program/sendprogramdialog.h \ + program/sendprogthread.h \ + program/usbdetectdialog.h \ + program/videosplitthread.h \ + program/wplanitem.h \ + program/wplanlist.h \ + program/wprogrampublishitem.h \ + +FORMS += \ + base/pixbmpshowdialog.ui \ + base/updateledset3dialog.ui \ + base/x_uimsgboxok.ui \ + mguangyingpinwidget.ui \ + device/controlpowerschedule.ui \ + device/controltestwidget.ui \ + device/controlvolumeschedule.ui \ + program/wplanitem.ui \ + +TRANSLATIONS += \ + translations/app_zh_CN.ts \ + translations/app_zh_TW.ts \ + translations/app_ja.ts \ + translations/app_en.ts + +EXTRA_TRANSLATIONS += \ + translations/qt_zh_CN.ts \ + translations/qt_zh_TW.ts \ + translations/qt_ja.ts \ + translations/qt_en.ts + +RESOURCES += res.qrc + +win32:RC_ICONS = res/Logo.ico +osx:ICON = res/Logo.icns + + +# Default rules for deployment. +qnx: target.path = /tmp/$${TARGET}/bin +else: unix:!android: target.path = /opt/$${TARGET}/bin +!isEmpty(target.path): INSTALLS += target + + + +INCLUDEPATH += $$PWD/ffmpeg/include +LIBS += -L$$PWD/ffmpeg/lib/\ + -lavcodec \ + -lavdevice \ + -lavfilter \ + -lavformat \ + -lavutil \ + -lswresample \ + -lswscale + +copy.files += $$files(ffmpeg/bin/*.dll) +copy.files += ffmpeg/bin/ffmpeg.exe + +include(./xlsx/qtxlsx.pri) +include(./QSimpleUpdater/QSimpleUpdater.pri) + +# for https requests +copy2.files += $$files(OpenSSL/*.dll) + +copy.files += 7z/7z.dll +copy.files += 7z/7z.exe + +copy.path = $$OUT_PWD +copy2.path = $$OUT_PWD/release + +copy3.files += $$quote(y50 param) +copy3.path = $$OUT_PWD/release + +CONFIG += file_copies +COPIES += copy +COPIES += copy2 +COPIES += copy3 diff --git a/LedOK/QSimpleUpdater/etc/resources/qsimpleupdater.qrc b/LedOK/QSimpleUpdater/etc/resources/qsimpleupdater.qrc index ac0c9e0..19dbb83 100644 --- a/LedOK/QSimpleUpdater/etc/resources/qsimpleupdater.qrc +++ b/LedOK/QSimpleUpdater/etc/resources/qsimpleupdater.qrc @@ -1,5 +1,5 @@ - - - update.png - - + + + update.png + + diff --git a/LedOK/QSimpleUpdater/etc/scripts/format-code.bat b/LedOK/QSimpleUpdater/etc/scripts/format-code.bat index 28ad63f..941bfda 100644 --- a/LedOK/QSimpleUpdater/etc/scripts/format-code.bat +++ b/LedOK/QSimpleUpdater/etc/scripts/format-code.bat @@ -1,20 +1,20 @@ -:: Description: This script changes the style format of -:: all the source code of the project. - -:: Setup the command line -@echo off -title Code Formatter - -:: Go to the directory where the script is run -cd /d %~dp0 - -:: Style and format the source code recursively -astyle --style=linux --indent=spaces --align-pointer=type --indent-preproc-block --indent-preproc-define --indent-col1-comments --pad-first-paren-out --pad-oper --attach-namespaces --remove-brackets --convert-tabs --close-templates --max-code-length=100 --max-instatement-indent=50 --lineend=windows --suffix=none --recursive ../../*.h ../../*.cpp ../../*.c - -:: Notify the user that we have finished -echo. -echo Code styling complete! -echo. - -:: Let the user see the output -pause +:: Description: This script changes the style format of +:: all the source code of the project. + +:: Setup the command line +@echo off +title Code Formatter + +:: Go to the directory where the script is run +cd /d %~dp0 + +:: Style and format the source code recursively +astyle --style=linux --indent=spaces --align-pointer=type --indent-preproc-block --indent-preproc-define --indent-col1-comments --pad-first-paren-out --pad-oper --attach-namespaces --remove-brackets --convert-tabs --close-templates --max-code-length=100 --max-instatement-indent=50 --lineend=windows --suffix=none --recursive ../../*.h ../../*.cpp ../../*.c + +:: Notify the user that we have finished +echo. +echo Code styling complete! +echo. + +:: Let the user see the output +pause diff --git a/LedOK/QSimpleUpdater/etc/scripts/format-code.sh b/LedOK/QSimpleUpdater/etc/scripts/format-code.sh index 5e3408f..8e9e418 100644 --- a/LedOK/QSimpleUpdater/etc/scripts/format-code.sh +++ b/LedOK/QSimpleUpdater/etc/scripts/format-code.sh @@ -1,2 +1,2 @@ -# Style and format recursively -astyle --style=linux --indent=spaces --align-pointer=type --indent-preproc-block --indent-preproc-define --indent-col1-comments --pad-first-paren-out --pad-oper --attach-namespaces --remove-brackets --convert-tabs --close-templates --max-code-length=100 --max-instatement-indent=50 --lineend=windows --suffix=none --recursive ../../*.h ../../*.cpp ../../*.cc +# Style and format recursively +astyle --style=linux --indent=spaces --align-pointer=type --indent-preproc-block --indent-preproc-define --indent-col1-comments --pad-first-paren-out --pad-oper --attach-namespaces --remove-brackets --convert-tabs --close-templates --max-code-length=100 --max-instatement-indent=50 --lineend=windows --suffix=none --recursive ../../*.h ../../*.cpp ../../*.cc diff --git a/LedOK/QSimpleUpdater/include/QSimpleUpdater.h b/LedOK/QSimpleUpdater/include/QSimpleUpdater.h index e5b4da7..673e05d 100644 --- a/LedOK/QSimpleUpdater/include/QSimpleUpdater.h +++ b/LedOK/QSimpleUpdater/include/QSimpleUpdater.h @@ -1,119 +1,119 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This file is part of the QSimpleUpdater library, which is released under - * the DBAD license, you can read a copy of it below: - * - * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, - * DISTRIBUTION AND MODIFICATION: - * - * Do whatever you like with the original work, just don't be a dick. - * Being a dick includes - but is not limited to - the following instances: - * - * 1a. Outright copyright infringement - Don't just copy this and change the - * name. - * 1b. Selling the unmodified original with no work done what-so-ever, that's - * REALLY being a dick. - * 1c. Modifying the original work to contain hidden harmful content. - * That would make you a PROPER dick. - * - * If you become rich through modifications, related works/services, or - * supporting the original work, share the love. - * Only a dick would make loads off this work and not buy the original works - * creator(s) a pint. - * - * Code is provided with no warranty. Using somebody else's code and bitching - * when it goes wrong makes you a DONKEY dick. - * Fix the problem yourself. A non-dick would submit the fix back. - */ - -#ifndef _QSIMPLEUPDATER_MAIN_H -#define _QSIMPLEUPDATER_MAIN_H - -#include -#include -#include - -#if defined (QSU_SHARED) - #define QSU_DECL Q_DECL_EXPORT -#elif defined (QSU_IMPORT) - #define QSU_DECL Q_DECL_IMPORT -#else - #define QSU_DECL -#endif - -class Updater; - -/** - * \brief Manages the updater instances - * - * The \c QSimpleUpdater class manages the updater system and allows for - * parallel application modules to check for updates and download them. - * - * The behavior of each updater can be regulated by specifying the update - * definitions URL (from where we download the individual update definitions) - * and defining the desired options by calling the individual "setter" - * functions (e.g. \c setNotifyOnUpdate()). - * - * The \c QSimpleUpdater also implements an integrated downloader. - * If you need to use a custom install procedure/code, just create a function - * that is called when the \c downloadFinished() signal is emitted to - * implement your own install procedures. - * - * By default, the downloader will try to open the file as if you opened it - * from a file manager or a web browser (with the "file:*" url). - */ -class QSU_DECL QSimpleUpdater : public QObject -{ - Q_OBJECT - -signals: - void checkingFinished (const QString& url); - void appcastDownloaded (const QString& url, const QByteArray& data); - void downloadFinished (const QString& url, const QString& filepath); - -public: - static QSimpleUpdater* getInstance(); - - bool usesCustomAppcast (const QString& url) const; - bool getNotifyOnUpdate (const QString& url) const; - bool getNotifyOnFinish (const QString& url) const; - bool getUpdateAvailable (const QString& url) const; - bool getUpdateSameVersionAvailable (const QString& url) const; - - bool getDownloaderEnabled (const QString& url) const; - bool usesCustomInstallProcedures (const QString& url) const; - - QString getOpenUrl (const QString& url) const; - QString getChangelog (const QString& url) const; - QString getModuleName (const QString& url) const; - QString getDownloadUrl (const QString& url) const; - QString getPlatformKey (const QString& url) const; - QString getLatestVersion (const QString& url) const; - QString getModuleVersion (const QString& url) const; - QString getUserAgentString (const QString& url) const; - -public slots: - void checkForUpdates (const QString& url); - void setModuleName (const QString& url, const QString& name); - void setNotifyOnUpdate (const QString& url, const bool notify); - void setNotifyOnFinish (const QString& url, const bool notify); - void setPlatformKey (const QString& url, const QString& platform); - void setModuleVersion (const QString& url, const QString& version); - void setDownloaderEnabled (const QString& url, const bool enabled); - void setUserAgentString (const QString& url, const QString& agent); - void setUseCustomAppcast (const QString& url, const bool customAppcast); - void setUseCustomInstallProcedures (const QString& url, const bool custom); - void setNoNotifyDownload (const QString& url, const bool custom); - void setCompareBySameString (const QString& url, const bool custom); - - void setMandatoryUpdate (const QString& url, const bool mandatory_update); - -protected: - ~QSimpleUpdater(); - -private: - Updater* getUpdater (const QString& url) const; -}; - -#endif +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This file is part of the QSimpleUpdater library, which is released under + * the DBAD license, you can read a copy of it below: + * + * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, + * DISTRIBUTION AND MODIFICATION: + * + * Do whatever you like with the original work, just don't be a dick. + * Being a dick includes - but is not limited to - the following instances: + * + * 1a. Outright copyright infringement - Don't just copy this and change the + * name. + * 1b. Selling the unmodified original with no work done what-so-ever, that's + * REALLY being a dick. + * 1c. Modifying the original work to contain hidden harmful content. + * That would make you a PROPER dick. + * + * If you become rich through modifications, related works/services, or + * supporting the original work, share the love. + * Only a dick would make loads off this work and not buy the original works + * creator(s) a pint. + * + * Code is provided with no warranty. Using somebody else's code and bitching + * when it goes wrong makes you a DONKEY dick. + * Fix the problem yourself. A non-dick would submit the fix back. + */ + +#ifndef _QSIMPLEUPDATER_MAIN_H +#define _QSIMPLEUPDATER_MAIN_H + +#include +#include +#include + +#if defined (QSU_SHARED) + #define QSU_DECL Q_DECL_EXPORT +#elif defined (QSU_IMPORT) + #define QSU_DECL Q_DECL_IMPORT +#else + #define QSU_DECL +#endif + +class Updater; + +/** + * \brief Manages the updater instances + * + * The \c QSimpleUpdater class manages the updater system and allows for + * parallel application modules to check for updates and download them. + * + * The behavior of each updater can be regulated by specifying the update + * definitions URL (from where we download the individual update definitions) + * and defining the desired options by calling the individual "setter" + * functions (e.g. \c setNotifyOnUpdate()). + * + * The \c QSimpleUpdater also implements an integrated downloader. + * If you need to use a custom install procedure/code, just create a function + * that is called when the \c downloadFinished() signal is emitted to + * implement your own install procedures. + * + * By default, the downloader will try to open the file as if you opened it + * from a file manager or a web browser (with the "file:*" url). + */ +class QSU_DECL QSimpleUpdater : public QObject +{ + Q_OBJECT + +signals: + void checkingFinished (const QString& url); + void appcastDownloaded (const QString& url, const QByteArray& data); + void downloadFinished (const QString& url, const QString& filepath); + +public: + static QSimpleUpdater* getInstance(); + + bool usesCustomAppcast (const QString& url) const; + bool getNotifyOnUpdate (const QString& url) const; + bool getNotifyOnFinish (const QString& url) const; + bool getUpdateAvailable (const QString& url) const; + bool getUpdateSameVersionAvailable (const QString& url) const; + + bool getDownloaderEnabled (const QString& url) const; + bool usesCustomInstallProcedures (const QString& url) const; + + QString getOpenUrl (const QString& url) const; + QString getChangelog (const QString& url) const; + QString getModuleName (const QString& url) const; + QString getDownloadUrl (const QString& url) const; + QString getPlatformKey (const QString& url) const; + QString getLatestVersion (const QString& url) const; + QString getModuleVersion (const QString& url) const; + QString getUserAgentString (const QString& url) const; + +public slots: + void checkForUpdates (const QString& url); + void setModuleName (const QString& url, const QString& name); + void setNotifyOnUpdate (const QString& url, const bool notify); + void setNotifyOnFinish (const QString& url, const bool notify); + void setPlatformKey (const QString& url, const QString& platform); + void setModuleVersion (const QString& url, const QString& version); + void setDownloaderEnabled (const QString& url, const bool enabled); + void setUserAgentString (const QString& url, const QString& agent); + void setUseCustomAppcast (const QString& url, const bool customAppcast); + void setUseCustomInstallProcedures (const QString& url, const bool custom); + void setNoNotifyDownload (const QString& url, const bool custom); + void setCompareBySameString (const QString& url, const bool custom); + + void setMandatoryUpdate (const QString& url, const bool mandatory_update); + +protected: + ~QSimpleUpdater(); + +private: + Updater* getUpdater (const QString& url) const; +}; + +#endif diff --git a/LedOK/QSimpleUpdater/src/Downloader.cpp b/LedOK/QSimpleUpdater/src/Downloader.cpp index 4f24641..77821ad 100644 --- a/LedOK/QSimpleUpdater/src/Downloader.cpp +++ b/LedOK/QSimpleUpdater/src/Downloader.cpp @@ -1,438 +1,438 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * Copyright (c) 2017 Gilmanov Ildar - * - * This file is part of the QSimpleUpdater library, which is released under - * the DBAD license, you can read a copy of it below: - * - * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, - * DISTRIBUTION AND MODIFICATION: - * - * Do whatever you like with the original work, just don't be a dick. - * Being a dick includes - but is not limited to - the following instances: - * - * 1a. Outright copyright infringement - Don't just copy this and change the - * name. - * 1b. Selling the unmodified original with no work done what-so-ever, that's - * REALLY being a dick. - * 1c. Modifying the original work to contain hidden harmful content. - * That would make you a PROPER dick. - * - * If you become rich through modifications, related works/services, or - * supporting the original work, share the love. - * Only a dick would make loads off this work and not buy the original works - * creator(s) a pint. - * - * Code is provided with no warranty. Using somebody else's code and bitching - * when it goes wrong makes you a DONKEY dick. - * Fix the problem yourself. A non-dick would submit the fix back. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Downloader.h" - -static const QString PARTIAL_DOWN (".part"); -extern QWidget *gMainWin; - -Downloader::Downloader (QWidget* parent) : QDialog (parent) { - setWindowFlag(Qt::WindowContextHelpButtonHint, false); - m_ui = new Ui::Downloader; - m_ui->setupUi (this); - //m_ui->label->setText(tr("Software update")); - /* Initialize private members */ - m_manager = new QNetworkAccessManager(); - - /* Initialize internal values */ - m_url = ""; - m_fileName = ""; - m_startTime = 0; - m_useCustomProcedures = false; - m_mandatoryUpdate = false; - - /* Set download directory */ - //m_downloadDir.setPath(QDir::homePath() + "/Downloads/"); - m_downloadDir.setPath(QCoreApplication::applicationDirPath() + "/Downloads/"); - - /* Make the window look like a modal dialog */ - // setWindowIcon (QIcon()); - // setWindowFlags (Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint); - - /* Configure the appearance and behavior of the buttons */ - m_ui->openButton->setEnabled (false); - m_ui->openButton->setVisible (false); - connect (m_ui->stopButton, SIGNAL (clicked()), - this, SLOT (cancelDownload())); - connect (m_ui->openButton, SIGNAL (clicked()), - this, SLOT (installUpdate())); - - /* Resize to fit */ - setFixedSize (minimumSizeHint()); - setStyleSheet("background-color: #D8D8D8"); -} - -Downloader::~Downloader() -{ - delete m_ui; - delete m_reply; - delete m_manager; -} - -/** - * Returns \c true if the updater shall not intervene when the download has - * finished (you can use the \c QSimpleUpdater signals to know when the - * download is completed). - */ -bool Downloader::useCustomInstallProcedures() const -{ - return m_useCustomProcedures; -} - -/** - * Changes the URL, which is used to indentify the downloader dialog - * with an \c Updater instance - * - * \note the \a url parameter is not the download URL, it is the URL of - * the AppCast file - */ -void Downloader::setUrlId (const QString& url) -{ - m_url = url; -} - -/** - * Begins downloading the file at the given \a url - */ -void Downloader::startDownload (const QUrl& url) -{ - - /* Reset UI */ - m_ui->progressBar->setValue (0); - m_ui->stopButton->setText (tr ("Stop")); - m_ui->downloadLabel->setText (tr ("Downloading updates")); - m_ui->timeLabel->setText (tr ("Time remaining") + ": " + tr ("unknown")); - - /* Configure the network request */ - QNetworkRequest request (url); - if (!m_userAgentString.isEmpty()) - request.setRawHeader ("User-Agent", m_userAgentString.toUtf8()); - - /* Start download */ - m_reply = m_manager->get (request); - m_startTime = QDateTime::currentDateTime().toTime_t(); - - /* Ensure that downloads directory exists */ - if (!m_downloadDir.exists()) - m_downloadDir.mkpath("."); - - /* Remove old downloads */ - QFile::remove (m_downloadDir.filePath (m_fileName)); - QFile::remove (m_downloadDir.filePath (m_fileName + PARTIAL_DOWN)); - - /* Update UI when download progress changes or download finishes */ - connect (m_reply, SIGNAL (downloadProgress (qint64, qint64)), - this, SLOT (updateProgress (qint64, qint64))); - connect (m_reply, SIGNAL (finished ()), - this, SLOT (finished ())); - connect (m_reply, SIGNAL (redirected (QUrl)), - this, SLOT (startDownload (QUrl))); - - showNormal(); -} - -/** - * Changes the name of the downloaded file - */ -void Downloader::setFileName (const QString& file) -{ - m_fileName = file; - - if (m_fileName.isEmpty()) - m_fileName = "QSU_Update.bin"; -} - -/** - * Changes the user-agent string used to communicate with the remote HTTP server - */ -void Downloader::setUserAgentString (const QString& agent) -{ - m_userAgentString = agent; -} -void Downloader::finished() -{ - /* Rename file */ - QFile::rename (m_downloadDir.filePath (m_fileName + PARTIAL_DOWN), - m_downloadDir.filePath (m_fileName)); - - /* Notify application */ - emit downloadFinished (m_url, m_downloadDir.filePath (m_fileName)); - /* Install the update */ - m_reply->close(); - installUpdate(); - setVisible (false); -} - -/** - * Opens the downloaded file. - * \note If the downloaded file is not found, then the function will alert the - * user about the error. - */ -void Downloader::openDownload() { - if(!m_fileName.isEmpty()) QDesktopServices::openUrl(QUrl::fromLocalFile(m_downloadDir.filePath(m_fileName))); - else QMessageBox::critical (gMainWin, tr("Error"), tr("Cannot find downloaded update!"), QMessageBox::Close); -} - -/** - * Instructs the OS to open the downloaded file. - * - * \note If \c useCustomInstallProcedures() returns \c true, the function will - * not instruct the OS to open the downloaded file. You can use the - * signals fired by the \c QSimpleUpdater to install the update with your - * own implementations/code. - */ -void Downloader::installUpdate(){ - if (useCustomInstallProcedures()){ - return; - } - - /* Update labels */ - m_ui->stopButton->setText (tr ("Close")); - m_ui->downloadLabel->setText (tr ("Download complete!")); - m_ui->timeLabel->setText (tr ("The installer will open separately") - + "..."); - - /* Ask the user to install the download */ -// QMessageBox box; -// box.setIcon (QMessageBox::Question); -// box.setDefaultButton (QMessageBox::Ok); -// box.setStandardButtons (QMessageBox::Ok | QMessageBox::Cancel); -// box.setInformativeText (tr ("Click \"OK\" to begin installing the update")); - - QString text = m_mandatoryUpdate ? tr("In order to install the update, you may need to quit the application. This is a mandatory update, exiting now will close the application") : tr("In order to install the update "); - auto res = QMessageBox::information(gMainWin, tr("Tip Info"), text, QMessageBox::Ok, QMessageBox::Cancel); - if(m_mandatoryUpdate) QApplication::quit(); - if(res == QMessageBox::Ok) { - if(!useCustomInstallProcedures()) openDownload(); - } else { - m_ui->openButton->setEnabled (true); - m_ui->openButton->setVisible (true); - m_ui->timeLabel->setText (tr ("Click the \"Open\" button to " - "apply the update")); - } -} - -/** - * Prompts the user if he/she wants to cancel the download and cancels the - * download if the user agrees to do that. - */ -void Downloader::cancelDownload() -{ - if (!m_reply->isFinished()) { - QMessageBox box; - box.setWindowTitle (tr ("Updater")); - box.setIcon (QMessageBox::Question); - box.setStandardButtons (QMessageBox::Yes | QMessageBox::No); - - QString text = tr("Are you sure you want to cancel the download?"); - if (m_mandatoryUpdate) - { - text = tr("Are you sure you want to cancel the download? This is a mandatory update, exiting now will close the application"); - } - box.setText (text); - - if (box.exec() == QMessageBox::Yes) { - hide(); - m_reply->abort(); - if(m_mandatoryUpdate) - QApplication::quit(); - } - } - else - { - if(m_mandatoryUpdate) - QApplication::quit(); - - hide(); - } -} - -/** - * Writes the downloaded data to the disk - */ -void Downloader::saveFile (qint64 received, qint64 total) -{ - Q_UNUSED (received); - Q_UNUSED (total); - - /* Check if we need to redirect */ - QUrl url = m_reply->attribute ( - QNetworkRequest::RedirectionTargetAttribute).toUrl(); - if (!url.isEmpty()) { - startDownload (url); - return; - } - - /* Save downloaded data to disk */ - QFile file (m_downloadDir.filePath (m_fileName + PARTIAL_DOWN)); - if (file.open (QIODevice::WriteOnly | QIODevice::Append)) { - file.write (m_reply->readAll()); - file.close(); - } -} - - -/** - * Calculates the appropiate size units (bytes, KB or MB) for the received - * data and the total download size. Then, this function proceeds to update the - * dialog controls/UI. - */ -void Downloader::calculateSizes (qint64 received, qint64 total) -{ - QString totalSize; - QString receivedSize; - - if (total < 1024) - totalSize = tr ("%1 bytes").arg (total); - - else if (total < 1048576) - totalSize = tr ("%1 KB").arg (round (total / 1024)); - - else - totalSize = tr ("%1 MB").arg (round (total / 1048576)); - - if (received < 1024) - receivedSize = tr ("%1 bytes").arg (received); - - else if (received < 1048576) - receivedSize = tr ("%1 KB").arg (received / 1024); - - else - receivedSize = tr ("%1 MB").arg (received / 1048576); - - m_ui->downloadLabel->setText (tr ("Downloading updates") - + " (" + receivedSize + " " + tr ("of") - + " " + totalSize + ")"); -} - -/** - * Uses the \a received and \a total parameters to get the download progress - * and update the progressbar value on the dialog. - */ -void Downloader::updateProgress (qint64 received, qint64 total) -{ - if (total > 0) { - m_ui->progressBar->setMinimum (0); - m_ui->progressBar->setMaximum (100); - m_ui->progressBar->setValue ((received * 100) / total); - - calculateSizes (received, total); - calculateTimeRemaining (received, total); - saveFile (received, total); - } - - else { - m_ui->progressBar->setMinimum (0); - m_ui->progressBar->setMaximum (0); - m_ui->progressBar->setValue (-1); - m_ui->downloadLabel->setText (tr ("Downloading Updates") + "..."); - m_ui->timeLabel->setText (QString ("%1: %2") - .arg (tr ("Time Remaining")) - .arg (tr ("Unknown"))); - } -} - -/** - * Uses two time samples (from the current time and a previous sample) to - * calculate how many bytes have been downloaded. - * - * Then, this function proceeds to calculate the appropiate units of time - * (hours, minutes or seconds) and constructs a user-friendly string, which - * is displayed in the dialog. - */ -void Downloader::calculateTimeRemaining (qint64 received, qint64 total) -{ - uint difference = QDateTime::currentDateTime().toTime_t() - m_startTime; - - if (difference > 0) { - QString timeString; - qreal timeRemaining = (total - received) / (received / difference); - - if (timeRemaining > 7200) { - timeRemaining /= 3600; - int hours = int (timeRemaining + 0.5); - - if (hours > 1) - timeString = tr ("about %1 hours").arg (hours); - else - timeString = tr ("about one hour"); - } - - else if (timeRemaining > 60) { - timeRemaining /= 60; - int minutes = int (timeRemaining + 0.5); - - if (minutes > 1) - timeString = tr ("%1 minutes").arg (minutes); - else - timeString = tr ("1 minute"); - } - - else if (timeRemaining <= 60) { - int seconds = int (timeRemaining + 0.5); - - if (seconds > 1) - timeString = tr ("%1 seconds").arg (seconds); - else - timeString = tr ("1 second"); - } - - m_ui->timeLabel->setText (tr ("Time remaining") + ": " + timeString); - } -} - -/** - * Rounds the given \a input to two decimal places - */ -qreal Downloader::round (const qreal& input) -{ - return static_cast(roundf (static_cast(input) * 100) / 100); -} - -QString Downloader::downloadDir() const -{ - return m_downloadDir.absolutePath(); -} - -void Downloader::setDownloadDir (const QString& downloadDir) -{ - if (m_downloadDir.absolutePath() != downloadDir) - m_downloadDir.setPath(downloadDir); -} - -/** - * If the \a mandatory_update is set to \c true, the \c Downloader has to download and install the - * update. If the user cancels or exits, the application will close - */ -void Downloader::setMandatoryUpdate(const bool mandatory_update) -{ - m_mandatoryUpdate = mandatory_update; -} - -/** - * If the \a custom parameter is set to \c true, then the \c Downloader will not - * attempt to open the downloaded file. - * - * Use the signals fired by the \c QSimpleUpdater to implement your own install - * procedures. - */ -void Downloader::setUseCustomInstallProcedures (const bool custom) -{ - m_useCustomProcedures = custom; -} +/* + * Copyright (c) 2014-2016 Alex Spataru + * Copyright (c) 2017 Gilmanov Ildar + * + * This file is part of the QSimpleUpdater library, which is released under + * the DBAD license, you can read a copy of it below: + * + * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, + * DISTRIBUTION AND MODIFICATION: + * + * Do whatever you like with the original work, just don't be a dick. + * Being a dick includes - but is not limited to - the following instances: + * + * 1a. Outright copyright infringement - Don't just copy this and change the + * name. + * 1b. Selling the unmodified original with no work done what-so-ever, that's + * REALLY being a dick. + * 1c. Modifying the original work to contain hidden harmful content. + * That would make you a PROPER dick. + * + * If you become rich through modifications, related works/services, or + * supporting the original work, share the love. + * Only a dick would make loads off this work and not buy the original works + * creator(s) a pint. + * + * Code is provided with no warranty. Using somebody else's code and bitching + * when it goes wrong makes you a DONKEY dick. + * Fix the problem yourself. A non-dick would submit the fix back. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Downloader.h" + +static const QString PARTIAL_DOWN (".part"); +extern QWidget *gMainWin; + +Downloader::Downloader (QWidget* parent) : QDialog (parent) { + setWindowFlag(Qt::WindowContextHelpButtonHint, false); + m_ui = new Ui::Downloader; + m_ui->setupUi (this); + //m_ui->label->setText(tr("Software update")); + /* Initialize private members */ + m_manager = new QNetworkAccessManager(); + + /* Initialize internal values */ + m_url = ""; + m_fileName = ""; + m_startTime = 0; + m_useCustomProcedures = false; + m_mandatoryUpdate = false; + + /* Set download directory */ + //m_downloadDir.setPath(QDir::homePath() + "/Downloads/"); + m_downloadDir.setPath(QCoreApplication::applicationDirPath() + "/Downloads/"); + + /* Make the window look like a modal dialog */ + // setWindowIcon (QIcon()); + // setWindowFlags (Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint); + + /* Configure the appearance and behavior of the buttons */ + m_ui->openButton->setEnabled (false); + m_ui->openButton->setVisible (false); + connect (m_ui->stopButton, SIGNAL (clicked()), + this, SLOT (cancelDownload())); + connect (m_ui->openButton, SIGNAL (clicked()), + this, SLOT (installUpdate())); + + /* Resize to fit */ + setFixedSize (minimumSizeHint()); + setStyleSheet("background-color: #D8D8D8"); +} + +Downloader::~Downloader() +{ + delete m_ui; + delete m_reply; + delete m_manager; +} + +/** + * Returns \c true if the updater shall not intervene when the download has + * finished (you can use the \c QSimpleUpdater signals to know when the + * download is completed). + */ +bool Downloader::useCustomInstallProcedures() const +{ + return m_useCustomProcedures; +} + +/** + * Changes the URL, which is used to indentify the downloader dialog + * with an \c Updater instance + * + * \note the \a url parameter is not the download URL, it is the URL of + * the AppCast file + */ +void Downloader::setUrlId (const QString& url) +{ + m_url = url; +} + +/** + * Begins downloading the file at the given \a url + */ +void Downloader::startDownload (const QUrl& url) +{ + + /* Reset UI */ + m_ui->progressBar->setValue (0); + m_ui->stopButton->setText (tr ("Stop")); + m_ui->downloadLabel->setText (tr ("Downloading updates")); + m_ui->timeLabel->setText (tr ("Time remaining") + ": " + tr ("unknown")); + + /* Configure the network request */ + QNetworkRequest request (url); + if (!m_userAgentString.isEmpty()) + request.setRawHeader ("User-Agent", m_userAgentString.toUtf8()); + + /* Start download */ + m_reply = m_manager->get (request); + m_startTime = QDateTime::currentDateTime().toTime_t(); + + /* Ensure that downloads directory exists */ + if (!m_downloadDir.exists()) + m_downloadDir.mkpath("."); + + /* Remove old downloads */ + QFile::remove (m_downloadDir.filePath (m_fileName)); + QFile::remove (m_downloadDir.filePath (m_fileName + PARTIAL_DOWN)); + + /* Update UI when download progress changes or download finishes */ + connect (m_reply, SIGNAL (downloadProgress (qint64, qint64)), + this, SLOT (updateProgress (qint64, qint64))); + connect (m_reply, SIGNAL (finished ()), + this, SLOT (finished ())); + connect (m_reply, SIGNAL (redirected (QUrl)), + this, SLOT (startDownload (QUrl))); + + showNormal(); +} + +/** + * Changes the name of the downloaded file + */ +void Downloader::setFileName (const QString& file) +{ + m_fileName = file; + + if (m_fileName.isEmpty()) + m_fileName = "QSU_Update.bin"; +} + +/** + * Changes the user-agent string used to communicate with the remote HTTP server + */ +void Downloader::setUserAgentString (const QString& agent) +{ + m_userAgentString = agent; +} +void Downloader::finished() +{ + /* Rename file */ + QFile::rename (m_downloadDir.filePath (m_fileName + PARTIAL_DOWN), + m_downloadDir.filePath (m_fileName)); + + /* Notify application */ + emit downloadFinished (m_url, m_downloadDir.filePath (m_fileName)); + /* Install the update */ + m_reply->close(); + installUpdate(); + setVisible (false); +} + +/** + * Opens the downloaded file. + * \note If the downloaded file is not found, then the function will alert the + * user about the error. + */ +void Downloader::openDownload() { + if(!m_fileName.isEmpty()) QDesktopServices::openUrl(QUrl::fromLocalFile(m_downloadDir.filePath(m_fileName))); + else QMessageBox::critical (gMainWin, tr("Error"), tr("Cannot find downloaded update!"), QMessageBox::Close); +} + +/** + * Instructs the OS to open the downloaded file. + * + * \note If \c useCustomInstallProcedures() returns \c true, the function will + * not instruct the OS to open the downloaded file. You can use the + * signals fired by the \c QSimpleUpdater to install the update with your + * own implementations/code. + */ +void Downloader::installUpdate(){ + if (useCustomInstallProcedures()){ + return; + } + + /* Update labels */ + m_ui->stopButton->setText (tr ("Close")); + m_ui->downloadLabel->setText (tr ("Download complete!")); + m_ui->timeLabel->setText (tr ("The installer will open separately") + + "..."); + + /* Ask the user to install the download */ +// QMessageBox box; +// box.setIcon (QMessageBox::Question); +// box.setDefaultButton (QMessageBox::Ok); +// box.setStandardButtons (QMessageBox::Ok | QMessageBox::Cancel); +// box.setInformativeText (tr ("Click \"OK\" to begin installing the update")); + + QString text = m_mandatoryUpdate ? tr("In order to install the update, you may need to quit the application. This is a mandatory update, exiting now will close the application") : tr("In order to install the update "); + auto res = QMessageBox::information(gMainWin, tr("Tip Info"), text, QMessageBox::Ok, QMessageBox::Cancel); + if(m_mandatoryUpdate) QApplication::quit(); + if(res == QMessageBox::Ok) { + if(!useCustomInstallProcedures()) openDownload(); + } else { + m_ui->openButton->setEnabled (true); + m_ui->openButton->setVisible (true); + m_ui->timeLabel->setText (tr ("Click the \"Open\" button to " + "apply the update")); + } +} + +/** + * Prompts the user if he/she wants to cancel the download and cancels the + * download if the user agrees to do that. + */ +void Downloader::cancelDownload() +{ + if (!m_reply->isFinished()) { + QMessageBox box; + box.setWindowTitle (tr ("Updater")); + box.setIcon (QMessageBox::Question); + box.setStandardButtons (QMessageBox::Yes | QMessageBox::No); + + QString text = tr("Are you sure you want to cancel the download?"); + if (m_mandatoryUpdate) + { + text = tr("Are you sure you want to cancel the download? This is a mandatory update, exiting now will close the application"); + } + box.setText (text); + + if (box.exec() == QMessageBox::Yes) { + hide(); + m_reply->abort(); + if(m_mandatoryUpdate) + QApplication::quit(); + } + } + else + { + if(m_mandatoryUpdate) + QApplication::quit(); + + hide(); + } +} + +/** + * Writes the downloaded data to the disk + */ +void Downloader::saveFile (qint64 received, qint64 total) +{ + Q_UNUSED (received); + Q_UNUSED (total); + + /* Check if we need to redirect */ + QUrl url = m_reply->attribute ( + QNetworkRequest::RedirectionTargetAttribute).toUrl(); + if (!url.isEmpty()) { + startDownload (url); + return; + } + + /* Save downloaded data to disk */ + QFile file (m_downloadDir.filePath (m_fileName + PARTIAL_DOWN)); + if (file.open (QIODevice::WriteOnly | QIODevice::Append)) { + file.write (m_reply->readAll()); + file.close(); + } +} + + +/** + * Calculates the appropiate size units (bytes, KB or MB) for the received + * data and the total download size. Then, this function proceeds to update the + * dialog controls/UI. + */ +void Downloader::calculateSizes (qint64 received, qint64 total) +{ + QString totalSize; + QString receivedSize; + + if (total < 1024) + totalSize = tr ("%1 bytes").arg (total); + + else if (total < 1048576) + totalSize = tr ("%1 KB").arg (round (total / 1024)); + + else + totalSize = tr ("%1 MB").arg (round (total / 1048576)); + + if (received < 1024) + receivedSize = tr ("%1 bytes").arg (received); + + else if (received < 1048576) + receivedSize = tr ("%1 KB").arg (received / 1024); + + else + receivedSize = tr ("%1 MB").arg (received / 1048576); + + m_ui->downloadLabel->setText (tr ("Downloading updates") + + " (" + receivedSize + " " + tr ("of") + + " " + totalSize + ")"); +} + +/** + * Uses the \a received and \a total parameters to get the download progress + * and update the progressbar value on the dialog. + */ +void Downloader::updateProgress (qint64 received, qint64 total) +{ + if (total > 0) { + m_ui->progressBar->setMinimum (0); + m_ui->progressBar->setMaximum (100); + m_ui->progressBar->setValue ((received * 100) / total); + + calculateSizes (received, total); + calculateTimeRemaining (received, total); + saveFile (received, total); + } + + else { + m_ui->progressBar->setMinimum (0); + m_ui->progressBar->setMaximum (0); + m_ui->progressBar->setValue (-1); + m_ui->downloadLabel->setText (tr ("Downloading Updates") + "..."); + m_ui->timeLabel->setText (QString ("%1: %2") + .arg (tr ("Time Remaining")) + .arg (tr ("Unknown"))); + } +} + +/** + * Uses two time samples (from the current time and a previous sample) to + * calculate how many bytes have been downloaded. + * + * Then, this function proceeds to calculate the appropiate units of time + * (hours, minutes or seconds) and constructs a user-friendly string, which + * is displayed in the dialog. + */ +void Downloader::calculateTimeRemaining (qint64 received, qint64 total) +{ + uint difference = QDateTime::currentDateTime().toTime_t() - m_startTime; + + if (difference > 0) { + QString timeString; + qreal timeRemaining = (total - received) / (received / difference); + + if (timeRemaining > 7200) { + timeRemaining /= 3600; + int hours = int (timeRemaining + 0.5); + + if (hours > 1) + timeString = tr ("about %1 hours").arg (hours); + else + timeString = tr ("about one hour"); + } + + else if (timeRemaining > 60) { + timeRemaining /= 60; + int minutes = int (timeRemaining + 0.5); + + if (minutes > 1) + timeString = tr ("%1 minutes").arg (minutes); + else + timeString = tr ("1 minute"); + } + + else if (timeRemaining <= 60) { + int seconds = int (timeRemaining + 0.5); + + if (seconds > 1) + timeString = tr ("%1 seconds").arg (seconds); + else + timeString = tr ("1 second"); + } + + m_ui->timeLabel->setText (tr ("Time remaining") + ": " + timeString); + } +} + +/** + * Rounds the given \a input to two decimal places + */ +qreal Downloader::round (const qreal& input) +{ + return static_cast(roundf (static_cast(input) * 100) / 100); +} + +QString Downloader::downloadDir() const +{ + return m_downloadDir.absolutePath(); +} + +void Downloader::setDownloadDir (const QString& downloadDir) +{ + if (m_downloadDir.absolutePath() != downloadDir) + m_downloadDir.setPath(downloadDir); +} + +/** + * If the \a mandatory_update is set to \c true, the \c Downloader has to download and install the + * update. If the user cancels or exits, the application will close + */ +void Downloader::setMandatoryUpdate(const bool mandatory_update) +{ + m_mandatoryUpdate = mandatory_update; +} + +/** + * If the \a custom parameter is set to \c true, then the \c Downloader will not + * attempt to open the downloaded file. + * + * Use the signals fired by the \c QSimpleUpdater to implement your own install + * procedures. + */ +void Downloader::setUseCustomInstallProcedures (const bool custom) +{ + m_useCustomProcedures = custom; +} diff --git a/LedOK/QSimpleUpdater/src/Downloader.h b/LedOK/QSimpleUpdater/src/Downloader.h index 00c9f11..40e9b11 100644 --- a/LedOK/QSimpleUpdater/src/Downloader.h +++ b/LedOK/QSimpleUpdater/src/Downloader.h @@ -1,101 +1,101 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * Copyright (c) 2017 Gilmanov Ildar - * - * This file is part of the QSimpleUpdater library, which is released under - * the DBAD license, you can read a copy of it below: - * - * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, - * DISTRIBUTION AND MODIFICATION: - * - * Do whatever you like with the original work, just don't be a dick. - * Being a dick includes - but is not limited to - the following instances: - * - * 1a. Outright copyright infringement - Don't just copy this and change the - * name. - * 1b. Selling the unmodified original with no work done what-so-ever, that's - * REALLY being a dick. - * 1c. Modifying the original work to contain hidden harmful content. - * That would make you a PROPER dick. - * - * If you become rich through modifications, related works/services, or - * supporting the original work, share the love. - * Only a dick would make loads off this work and not buy the original works - * creator(s) a pint. - * - * Code is provided with no warranty. Using somebody else's code and bitching - * when it goes wrong makes you a DONKEY dick. - * Fix the problem yourself. A non-dick would submit the fix back. - */ - -#ifndef DOWNLOAD_DIALOG_H -#define DOWNLOAD_DIALOG_H - -#include -#include -#include - -namespace Ui { -class Downloader; -} - -class QNetworkReply; -class QNetworkAccessManager; - -/** - * \brief Implements an integrated file downloader with a nice UI - */ -class Downloader : public QDialog//QWidget -{ - Q_OBJECT - -signals: - void downloadFinished (const QString& url, const QString& filepath); - -public: - explicit Downloader (QWidget* parent = 0); - ~Downloader(); - - bool useCustomInstallProcedures() const; - QString m_strVersion=""; - - QString downloadDir() const; - void setDownloadDir (const QString& downloadDir); - -public slots: - void setUrlId (const QString& url); - void startDownload (const QUrl& url); - void setFileName (const QString& file); - void setUserAgentString (const QString& agent); - void setUseCustomInstallProcedures (const bool custom); - void setMandatoryUpdate (const bool mandatory_update); - -private slots: - void finished(); - void openDownload(); - void installUpdate(); - void cancelDownload(); - void saveFile (qint64 received, qint64 total); - void calculateSizes (qint64 received, qint64 total); - void updateProgress (qint64 received, qint64 total); - void calculateTimeRemaining (qint64 received, qint64 total); - -private: - qreal round (const qreal& input); - -private: - QString m_url; - uint m_startTime; - QDir m_downloadDir; - QString m_fileName; - Ui::Downloader* m_ui; - QNetworkReply* m_reply; - QString m_userAgentString; - - bool m_useCustomProcedures; - bool m_mandatoryUpdate; - - QNetworkAccessManager* m_manager; -}; - -#endif +/* + * Copyright (c) 2014-2016 Alex Spataru + * Copyright (c) 2017 Gilmanov Ildar + * + * This file is part of the QSimpleUpdater library, which is released under + * the DBAD license, you can read a copy of it below: + * + * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, + * DISTRIBUTION AND MODIFICATION: + * + * Do whatever you like with the original work, just don't be a dick. + * Being a dick includes - but is not limited to - the following instances: + * + * 1a. Outright copyright infringement - Don't just copy this and change the + * name. + * 1b. Selling the unmodified original with no work done what-so-ever, that's + * REALLY being a dick. + * 1c. Modifying the original work to contain hidden harmful content. + * That would make you a PROPER dick. + * + * If you become rich through modifications, related works/services, or + * supporting the original work, share the love. + * Only a dick would make loads off this work and not buy the original works + * creator(s) a pint. + * + * Code is provided with no warranty. Using somebody else's code and bitching + * when it goes wrong makes you a DONKEY dick. + * Fix the problem yourself. A non-dick would submit the fix back. + */ + +#ifndef DOWNLOAD_DIALOG_H +#define DOWNLOAD_DIALOG_H + +#include +#include +#include + +namespace Ui { +class Downloader; +} + +class QNetworkReply; +class QNetworkAccessManager; + +/** + * \brief Implements an integrated file downloader with a nice UI + */ +class Downloader : public QDialog//QWidget +{ + Q_OBJECT + +signals: + void downloadFinished (const QString& url, const QString& filepath); + +public: + explicit Downloader (QWidget* parent = 0); + ~Downloader(); + + bool useCustomInstallProcedures() const; + QString m_strVersion=""; + + QString downloadDir() const; + void setDownloadDir (const QString& downloadDir); + +public slots: + void setUrlId (const QString& url); + void startDownload (const QUrl& url); + void setFileName (const QString& file); + void setUserAgentString (const QString& agent); + void setUseCustomInstallProcedures (const bool custom); + void setMandatoryUpdate (const bool mandatory_update); + +private slots: + void finished(); + void openDownload(); + void installUpdate(); + void cancelDownload(); + void saveFile (qint64 received, qint64 total); + void calculateSizes (qint64 received, qint64 total); + void updateProgress (qint64 received, qint64 total); + void calculateTimeRemaining (qint64 received, qint64 total); + +private: + qreal round (const qreal& input); + +private: + QString m_url; + uint m_startTime; + QDir m_downloadDir; + QString m_fileName; + Ui::Downloader* m_ui; + QNetworkReply* m_reply; + QString m_userAgentString; + + bool m_useCustomProcedures; + bool m_mandatoryUpdate; + + QNetworkAccessManager* m_manager; +}; + +#endif diff --git a/LedOK/QSimpleUpdater/src/Downloader.ui b/LedOK/QSimpleUpdater/src/Downloader.ui index 06c36bb..c1aa537 100644 --- a/LedOK/QSimpleUpdater/src/Downloader.ui +++ b/LedOK/QSimpleUpdater/src/Downloader.ui @@ -1,214 +1,214 @@ - - - Downloader - - - Qt::ApplicationModal - - - - 0 - 0 - 472 - 227 - - - - - 0 - 0 - - - - Updater - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 30 - 24 - - - - X - - - - - - - - - border-top: 2px solid gray; - - - Qt::Horizontal - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 96 - 96 - - - - - - - :/icons/update.png - - - - - - - - 0 - - - - - - 75 - true - - - - Downloading updates - - - - - - - - 320 - 0 - - - - 0 - - - false - - - - - - - Time remaining: 0 minutes - - - - - - - - - - - - - - 12 - - - 12 - - - 12 - - - 12 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Open - - - - - - - Stop - - - - - - - - - - - - - - - - + + + Downloader + + + Qt::ApplicationModal + + + + 0 + 0 + 472 + 227 + + + + + 0 + 0 + + + + Updater + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 30 + 24 + + + + X + + + + + + + + + border-top: 2px solid gray; + + + Qt::Horizontal + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 96 + 96 + + + + + + + :/icons/update.png + + + + + + + + 0 + + + + + + 75 + true + + + + Downloading updates + + + + + + + + 320 + 0 + + + + 0 + + + false + + + + + + + Time remaining: 0 minutes + + + + + + + + + + + + + + 12 + + + 12 + + + 12 + + + 12 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Open + + + + + + + Stop + + + + + + + + + + + + + + + + diff --git a/LedOK/QSimpleUpdater/src/QSimpleUpdater.cpp b/LedOK/QSimpleUpdater/src/QSimpleUpdater.cpp index 11c02e5..afbd86a 100644 --- a/LedOK/QSimpleUpdater/src/QSimpleUpdater.cpp +++ b/LedOK/QSimpleUpdater/src/QSimpleUpdater.cpp @@ -1,433 +1,433 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This file is part of the QSimpleUpdater library, which is released under - * the DBAD license, you can read a copy of it below: - * - * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, - * DISTRIBUTION AND MODIFICATION: - * - * Do whatever you like with the original work, just don't be a dick. - * Being a dick includes - but is not limited to - the following instances: - * - * 1a. Outright copyright infringement - Don't just copy this and change the - * name. - * 1b. Selling the unmodified original with no work done what-so-ever, that's - * REALLY being a dick. - * 1c. Modifying the original work to contain hidden harmful content. - * That would make you a PROPER dick. - * - * If you become rich through modifications, related works/services, or - * supporting the original work, share the love. - * Only a dick would make loads off this work and not buy the original works - * creator(s) a pint. - * - * Code is provided with no warranty. Using somebody else's code and bitching - * when it goes wrong makes you a DONKEY dick. - * Fix the problem yourself. A non-dick would submit the fix back. - */ - -#include "Updater.h" -#include "QSimpleUpdater.h" - -static QList URLS; -static QList UPDATERS; - -QSimpleUpdater::~QSimpleUpdater() -{ - URLS.clear(); - - foreach (Updater* updater, UPDATERS) - updater->deleteLater(); - - UPDATERS.clear(); -} - -/** - * Returns the only instance of the class - */ -QSimpleUpdater* QSimpleUpdater::getInstance() -{ - static QSimpleUpdater updater; - return &updater; -} - -/** - * Returns \c true if the \c Updater instance registered with the given \a url - * uses a custom appcast format and/or allows the application to read and - * interpret the downloaded appcast file - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -bool QSimpleUpdater::usesCustomAppcast (const QString& url) const -{ - return getUpdater (url)->customAppcast(); -} - -/** - * Returns \c true if the \c Updater instance registered with the given \a url - * shall notify the user when an update is available. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -bool QSimpleUpdater::getNotifyOnUpdate (const QString& url) const -{ - return getUpdater (url)->notifyOnUpdate(); -} - -/** - * Returns \c true if the \c Updater instance registered with the given \a url - * shall notify the user when it finishes checking for updates. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -bool QSimpleUpdater::getNotifyOnFinish (const QString& url) const -{ - return getUpdater (url)->notifyOnFinish(); -} - -/** - * Returns \c true if the \c Updater instance registered with the given \a url - * has an update available. - * - * \warning You should call \c checkForUpdates() before using this function - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -bool QSimpleUpdater::getUpdateAvailable (const QString& url) const -{ - return getUpdater (url)->updateAvailable(); -} -bool QSimpleUpdater::getUpdateSameVersionAvailable (const QString& url) const -{ - return getUpdater (url)->updateSameVersionAvailable(); -} - -/** - * Returns \c true if the \c Updater instance registered with the given \a url - * has the integrated downloader enabled. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -bool QSimpleUpdater::getDownloaderEnabled (const QString& url) const -{ - return getUpdater (url)->downloaderEnabled(); -} - -/** - * Returns \c true if the \c Updater instance registered with the given \a url - * shall try to open the downloaded file. - * - * If you want to implement your own way to handle the downloaded file, just - * bind to the \c downloadFinished() signal and disable the integrated - * downloader with the \c setUseCustomInstallProcedures() function. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -bool QSimpleUpdater::usesCustomInstallProcedures (const QString& url) const -{ - return getUpdater (url)->useCustomInstallProcedures(); -} - -/** - * Returns the URL to open in a web browser of the \c Updater instance - * registered with the given \a url. - * - * \note If the module name is empty, then the \c Updater will use the - * application name as its module name. - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getOpenUrl (const QString& url) const -{ - return getUpdater (url)->openUrl(); -} - -/** - * Returns the changelog of the \c Updater instance registered with the given - * \a url. - * - * \warning You should call \c checkForUpdates() before using this function - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getChangelog (const QString& url) const -{ - return getUpdater (url)->changelog(); -} - -/** - * Returns the module name of the \c Updater instance registered with the given - * \a url. - * - * \note If the module name is empty, then the \c Updater will use the - * application name as its module name. - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getModuleName (const QString& url) const -{ - return getUpdater (url)->moduleName(); -} - -/** - * Returns the download URL of the \c Updater instance registered with the given - * \a url. - * - * \warning You should call \c checkForUpdates() before using this function - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getDownloadUrl (const QString& url) const -{ - return getUpdater (url)->downloadUrl(); -} - -/** - * Returns the platform key of the \c Updater registered with the given \a url. - * If you do not define a platform key, the system will assign the following - * platform key: - * - On iOS: \c ios - * - On Mac OSX: \c osx - * - On Android: \c android - * - On GNU/Linux: \c linux - * - On Microsoft Windows: \c windows - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getPlatformKey (const QString& url) const -{ - return getUpdater (url)->platformKey(); -} - -/** - * Returns the remote module version of the \c Updater instance registered with - * the given \a url. - * - * \warning You should call \c checkForUpdates() before using this function - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getLatestVersion (const QString& url) const -{ - return getUpdater (url)->latestVersion(); -} - -/** - * Returns the module version of the \c Updater instance registered with the - * given \a url. - * - * \note If the module version is empty, then the \c Updater will use the - * application version as its module version. - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getModuleVersion (const QString& url) const -{ - return getUpdater (url)->moduleVersion(); -} - -/** - * Returns the user-agent string used by the updater to communicate with - * the remote HTTP(S) server. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -QString QSimpleUpdater::getUserAgentString (const QString& url) const -{ - return getUpdater (url)->userAgentString(); -} - -/** - * Instructs the \c Updater instance with the registered \c url to download and - * interpret the update definitions file. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::checkForUpdates (const QString& url) -{ - getUpdater (url)->checkForUpdates(); -} - -/** - * Changes the module \a name of the \c Updater instance registered at the - * given \a url. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - * \note The module name is used on the user prompts. If the module name is - * empty, then the prompts will show the name of the application. - */ -void QSimpleUpdater::setModuleName (const QString& url, const QString& name) -{ - getUpdater (url)->setModuleName (name); -} - -/** - * If \a notify is set to \c true, then the \c Updater instance registered with - * the given \a url will notify the user when an update is available. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setNotifyOnUpdate (const QString& url, - const bool notify) -{ - getUpdater (url)->setNotifyOnUpdate (notify); -} - -/** - * If \a notify is set to \c true, then the \c Updater instance registered with - * the given \a url will notify the user when it has finished interpreting the - * update definitions file. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setNotifyOnFinish (const QString& url, - const bool notify) -{ - getUpdater (url)->setNotifyOnFinish (notify); -} - -/** - * Changes the platform key of the \c Updater isntance registered at the given - * \a url. - * - * If the platform key is empty, then the system will use the following keys: - * - On iOS: \c ios - * - On Mac OSX: \c osx - * - On Android: \c android - * - On GNU/Linux: \c linux - * - On Microsoft Windows: \c windows - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setPlatformKey (const QString& url, - const QString& platform) -{ - getUpdater (url)->setPlatformKey (platform); -} - -/** - * Changes the module \version of the \c Updater instance registered at the - * given \a url. - * - * \note The module version is used to compare it with the remove version. - * If the module name is empty, then the \c Updater instance will use the - * application version. - */ -void QSimpleUpdater::setModuleVersion (const QString& url, - const QString& version) -{ - getUpdater (url)->setModuleVersion (version); -} - -/** - * If the \a enabled parameter is set to \c true, the \c Updater instance - * registered with the given \a url will open the integrated downloader - * if the user agrees to install the update (if any). - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setDownloaderEnabled (const QString& url, - const bool enabled) -{ - getUpdater (url)->setDownloaderEnabled (enabled); -} - -/** - * Changes the user-agent string used by the updater to communicate - * with the remote server - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setUserAgentString (const QString& url, - const QString& agent) -{ - getUpdater (url)->setUserAgentString (agent); -} - -/** - * If the \a customAppcast parameter is set to \c true, then the \c Updater - * will not try to read the network reply from the server, instead, it will - * emit the \c appcastDownloaded() signal, which allows the application to - * read and interpret the appcast file by itself. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setUseCustomAppcast (const QString& url, - const bool customAppcast) -{ - getUpdater (url)->setUseCustomAppcast (customAppcast); -} - -/** - * If the \a custom parameter is set to \c true, the \c Updater instance - * registered with the given \a url will not try to open the downloaded file. - * - * If you want to implement your own way to handle the downloaded file, just - * bind to the \c downloadFinished() signal and disable the integrated - * downloader with the \c setUseCustomInstallProcedures() function. - * - * \note If an \c Updater instance registered with the given \a url is not - * found, that \c Updater instance will be initialized automatically - */ -void QSimpleUpdater::setUseCustomInstallProcedures (const QString& url, - const bool custom) -{ - getUpdater (url)->setUseCustomInstallProcedures (custom); -} -void QSimpleUpdater::setNoNotifyDownload (const QString& url, - const bool custom) -{ - getUpdater (url)->setNoNotifyDownload (custom); -} -void QSimpleUpdater::setCompareBySameString (const QString& url, - const bool custom) -{ - getUpdater (url)->setCompareBySameString (custom); -} -void QSimpleUpdater::setMandatoryUpdate(const QString& url, - const bool mandatory_update) -{ - getUpdater (url)->setMandatoryUpdate(mandatory_update); -} - -/** - * Returns the \c Updater instance registered with the given \a url. - * - * If an \c Updater instance registered with teh given \a url does not exist, - * this function will create it and configure it automatically. - */ -Updater* QSimpleUpdater::getUpdater (const QString& url) const -{ - if (!URLS.contains (url)) { - Updater* updater = new Updater; - updater->setUrl (url); - - URLS.append (url); - UPDATERS.append (updater); - - connect (updater, SIGNAL (checkingFinished (QString)), - this, SIGNAL (checkingFinished (QString))); - connect (updater, SIGNAL (downloadFinished (QString, QString)), - this, SIGNAL (downloadFinished (QString, QString))); - connect (updater, SIGNAL (appcastDownloaded (QString, QByteArray)), - this, SIGNAL (appcastDownloaded (QString, QByteArray))); - } - - return UPDATERS.at (URLS.indexOf (url)); -} +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This file is part of the QSimpleUpdater library, which is released under + * the DBAD license, you can read a copy of it below: + * + * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, + * DISTRIBUTION AND MODIFICATION: + * + * Do whatever you like with the original work, just don't be a dick. + * Being a dick includes - but is not limited to - the following instances: + * + * 1a. Outright copyright infringement - Don't just copy this and change the + * name. + * 1b. Selling the unmodified original with no work done what-so-ever, that's + * REALLY being a dick. + * 1c. Modifying the original work to contain hidden harmful content. + * That would make you a PROPER dick. + * + * If you become rich through modifications, related works/services, or + * supporting the original work, share the love. + * Only a dick would make loads off this work and not buy the original works + * creator(s) a pint. + * + * Code is provided with no warranty. Using somebody else's code and bitching + * when it goes wrong makes you a DONKEY dick. + * Fix the problem yourself. A non-dick would submit the fix back. + */ + +#include "Updater.h" +#include "QSimpleUpdater.h" + +static QList URLS; +static QList UPDATERS; + +QSimpleUpdater::~QSimpleUpdater() +{ + URLS.clear(); + + foreach (Updater* updater, UPDATERS) + updater->deleteLater(); + + UPDATERS.clear(); +} + +/** + * Returns the only instance of the class + */ +QSimpleUpdater* QSimpleUpdater::getInstance() +{ + static QSimpleUpdater updater; + return &updater; +} + +/** + * Returns \c true if the \c Updater instance registered with the given \a url + * uses a custom appcast format and/or allows the application to read and + * interpret the downloaded appcast file + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +bool QSimpleUpdater::usesCustomAppcast (const QString& url) const +{ + return getUpdater (url)->customAppcast(); +} + +/** + * Returns \c true if the \c Updater instance registered with the given \a url + * shall notify the user when an update is available. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +bool QSimpleUpdater::getNotifyOnUpdate (const QString& url) const +{ + return getUpdater (url)->notifyOnUpdate(); +} + +/** + * Returns \c true if the \c Updater instance registered with the given \a url + * shall notify the user when it finishes checking for updates. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +bool QSimpleUpdater::getNotifyOnFinish (const QString& url) const +{ + return getUpdater (url)->notifyOnFinish(); +} + +/** + * Returns \c true if the \c Updater instance registered with the given \a url + * has an update available. + * + * \warning You should call \c checkForUpdates() before using this function + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +bool QSimpleUpdater::getUpdateAvailable (const QString& url) const +{ + return getUpdater (url)->updateAvailable(); +} +bool QSimpleUpdater::getUpdateSameVersionAvailable (const QString& url) const +{ + return getUpdater (url)->updateSameVersionAvailable(); +} + +/** + * Returns \c true if the \c Updater instance registered with the given \a url + * has the integrated downloader enabled. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +bool QSimpleUpdater::getDownloaderEnabled (const QString& url) const +{ + return getUpdater (url)->downloaderEnabled(); +} + +/** + * Returns \c true if the \c Updater instance registered with the given \a url + * shall try to open the downloaded file. + * + * If you want to implement your own way to handle the downloaded file, just + * bind to the \c downloadFinished() signal and disable the integrated + * downloader with the \c setUseCustomInstallProcedures() function. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +bool QSimpleUpdater::usesCustomInstallProcedures (const QString& url) const +{ + return getUpdater (url)->useCustomInstallProcedures(); +} + +/** + * Returns the URL to open in a web browser of the \c Updater instance + * registered with the given \a url. + * + * \note If the module name is empty, then the \c Updater will use the + * application name as its module name. + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getOpenUrl (const QString& url) const +{ + return getUpdater (url)->openUrl(); +} + +/** + * Returns the changelog of the \c Updater instance registered with the given + * \a url. + * + * \warning You should call \c checkForUpdates() before using this function + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getChangelog (const QString& url) const +{ + return getUpdater (url)->changelog(); +} + +/** + * Returns the module name of the \c Updater instance registered with the given + * \a url. + * + * \note If the module name is empty, then the \c Updater will use the + * application name as its module name. + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getModuleName (const QString& url) const +{ + return getUpdater (url)->moduleName(); +} + +/** + * Returns the download URL of the \c Updater instance registered with the given + * \a url. + * + * \warning You should call \c checkForUpdates() before using this function + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getDownloadUrl (const QString& url) const +{ + return getUpdater (url)->downloadUrl(); +} + +/** + * Returns the platform key of the \c Updater registered with the given \a url. + * If you do not define a platform key, the system will assign the following + * platform key: + * - On iOS: \c ios + * - On Mac OSX: \c osx + * - On Android: \c android + * - On GNU/Linux: \c linux + * - On Microsoft Windows: \c windows + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getPlatformKey (const QString& url) const +{ + return getUpdater (url)->platformKey(); +} + +/** + * Returns the remote module version of the \c Updater instance registered with + * the given \a url. + * + * \warning You should call \c checkForUpdates() before using this function + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getLatestVersion (const QString& url) const +{ + return getUpdater (url)->latestVersion(); +} + +/** + * Returns the module version of the \c Updater instance registered with the + * given \a url. + * + * \note If the module version is empty, then the \c Updater will use the + * application version as its module version. + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getModuleVersion (const QString& url) const +{ + return getUpdater (url)->moduleVersion(); +} + +/** + * Returns the user-agent string used by the updater to communicate with + * the remote HTTP(S) server. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +QString QSimpleUpdater::getUserAgentString (const QString& url) const +{ + return getUpdater (url)->userAgentString(); +} + +/** + * Instructs the \c Updater instance with the registered \c url to download and + * interpret the update definitions file. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::checkForUpdates (const QString& url) +{ + getUpdater (url)->checkForUpdates(); +} + +/** + * Changes the module \a name of the \c Updater instance registered at the + * given \a url. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + * \note The module name is used on the user prompts. If the module name is + * empty, then the prompts will show the name of the application. + */ +void QSimpleUpdater::setModuleName (const QString& url, const QString& name) +{ + getUpdater (url)->setModuleName (name); +} + +/** + * If \a notify is set to \c true, then the \c Updater instance registered with + * the given \a url will notify the user when an update is available. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setNotifyOnUpdate (const QString& url, + const bool notify) +{ + getUpdater (url)->setNotifyOnUpdate (notify); +} + +/** + * If \a notify is set to \c true, then the \c Updater instance registered with + * the given \a url will notify the user when it has finished interpreting the + * update definitions file. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setNotifyOnFinish (const QString& url, + const bool notify) +{ + getUpdater (url)->setNotifyOnFinish (notify); +} + +/** + * Changes the platform key of the \c Updater isntance registered at the given + * \a url. + * + * If the platform key is empty, then the system will use the following keys: + * - On iOS: \c ios + * - On Mac OSX: \c osx + * - On Android: \c android + * - On GNU/Linux: \c linux + * - On Microsoft Windows: \c windows + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setPlatformKey (const QString& url, + const QString& platform) +{ + getUpdater (url)->setPlatformKey (platform); +} + +/** + * Changes the module \version of the \c Updater instance registered at the + * given \a url. + * + * \note The module version is used to compare it with the remove version. + * If the module name is empty, then the \c Updater instance will use the + * application version. + */ +void QSimpleUpdater::setModuleVersion (const QString& url, + const QString& version) +{ + getUpdater (url)->setModuleVersion (version); +} + +/** + * If the \a enabled parameter is set to \c true, the \c Updater instance + * registered with the given \a url will open the integrated downloader + * if the user agrees to install the update (if any). + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setDownloaderEnabled (const QString& url, + const bool enabled) +{ + getUpdater (url)->setDownloaderEnabled (enabled); +} + +/** + * Changes the user-agent string used by the updater to communicate + * with the remote server + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setUserAgentString (const QString& url, + const QString& agent) +{ + getUpdater (url)->setUserAgentString (agent); +} + +/** + * If the \a customAppcast parameter is set to \c true, then the \c Updater + * will not try to read the network reply from the server, instead, it will + * emit the \c appcastDownloaded() signal, which allows the application to + * read and interpret the appcast file by itself. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setUseCustomAppcast (const QString& url, + const bool customAppcast) +{ + getUpdater (url)->setUseCustomAppcast (customAppcast); +} + +/** + * If the \a custom parameter is set to \c true, the \c Updater instance + * registered with the given \a url will not try to open the downloaded file. + * + * If you want to implement your own way to handle the downloaded file, just + * bind to the \c downloadFinished() signal and disable the integrated + * downloader with the \c setUseCustomInstallProcedures() function. + * + * \note If an \c Updater instance registered with the given \a url is not + * found, that \c Updater instance will be initialized automatically + */ +void QSimpleUpdater::setUseCustomInstallProcedures (const QString& url, + const bool custom) +{ + getUpdater (url)->setUseCustomInstallProcedures (custom); +} +void QSimpleUpdater::setNoNotifyDownload (const QString& url, + const bool custom) +{ + getUpdater (url)->setNoNotifyDownload (custom); +} +void QSimpleUpdater::setCompareBySameString (const QString& url, + const bool custom) +{ + getUpdater (url)->setCompareBySameString (custom); +} +void QSimpleUpdater::setMandatoryUpdate(const QString& url, + const bool mandatory_update) +{ + getUpdater (url)->setMandatoryUpdate(mandatory_update); +} + +/** + * Returns the \c Updater instance registered with the given \a url. + * + * If an \c Updater instance registered with teh given \a url does not exist, + * this function will create it and configure it automatically. + */ +Updater* QSimpleUpdater::getUpdater (const QString& url) const +{ + if (!URLS.contains (url)) { + Updater* updater = new Updater; + updater->setUrl (url); + + URLS.append (url); + UPDATERS.append (updater); + + connect (updater, SIGNAL (checkingFinished (QString)), + this, SIGNAL (checkingFinished (QString))); + connect (updater, SIGNAL (downloadFinished (QString, QString)), + this, SIGNAL (downloadFinished (QString, QString))); + connect (updater, SIGNAL (appcastDownloaded (QString, QByteArray)), + this, SIGNAL (appcastDownloaded (QString, QByteArray))); + } + + return UPDATERS.at (URLS.indexOf (url)); +} diff --git a/LedOK/QSimpleUpdater/src/Updater.cpp b/LedOK/QSimpleUpdater/src/Updater.cpp index ba7eb99..c315dd9 100644 --- a/LedOK/QSimpleUpdater/src/Updater.cpp +++ b/LedOK/QSimpleUpdater/src/Updater.cpp @@ -1,498 +1,498 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This file is part of the QSimpleUpdater library, which is released under - * the DBAD license, you can read a copy of it below: - * - * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, - * DISTRIBUTION AND MODIFICATION: - * - * Do whatever you like with the original work, just don't be a dick. - * Being a dick includes - but is not limited to - the following instances: - * - * 1a. Outright copyright infringement - Don't just copy this and change the - * name. - * 1b. Selling the unmodified original with no work done what-so-ever, that's - * REALLY being a dick. - * 1c. Modifying the original work to contain hidden harmful content. - * That would make you a PROPER dick. - * - * If you become rich through modifications, related works/services, or - * supporting the original work, share the love. - * Only a dick would make loads off this work and not buy the original works - * creator(s) a pint. - * - * Code is provided with no warranty. Using somebody else's code and bitching - * when it goes wrong makes you a DONKEY dick. - * Fix the problem yourself. A non-dick would submit the fix back. - */ - -#include -#include -#include -#include -#include -#include - -#include "Updater.h" -#include "Downloader.h" -#include "cfg.h" -#include "qsettings.h" -Updater::Updater() { - m_url = ""; - m_openUrl = ""; - m_changelog = ""; - m_downloadUrl = ""; - m_latestVersion = ""; - m_customAppcast = false; - m_notifyOnUpdate = true; - m_notifyOnFinish = false; - m_updateAvailable = true; - m_sameVersion = false; - m_downloaderEnabled = true; - m_noTipDownload = false; - m_bSameStringCompare = false; - m_moduleName = qApp->applicationName(); - m_moduleVersion = qApp->applicationVersion(); - m_mandatoryUpdate = false; - - m_downloader = new Downloader(); - m_manager = new QNetworkAccessManager(); - QNetworkReply *pReply = m_manager->get(QNetworkRequest(QUrl(UpdVerUrl))); - QReplyTimeout *pTimeout = new QReplyTimeout(pReply, 10000); - // 超时进一步处理 - connect(pTimeout, &QReplyTimeout::timeout, [=]() { - qDebug() << "Timeout"; - }); -#if defined Q_OS_WIN - m_platform = "windows"; -#elif defined Q_OS_MAC - m_platform = "osx"; -#elif defined Q_OS_LINUX - m_platform = "linux"; -#elif defined Q_OS_ANDROID - m_platform = "android"; -#elif defined Q_OS_IOS - m_platform = "ios"; -#endif - setUserAgentString (QString ("%1/%2 (Qt; QSimpleUpdater)").arg(qApp->applicationName(), qApp->applicationVersion())); - connect (m_downloader, SIGNAL(downloadFinished(QString, QString)), this, SIGNAL (downloadFinished(QString, QString))); - connect (m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onReply(QNetworkReply*))); -} - -Updater::~Updater() -{ - delete m_downloader; -} - -/** - * Returns the URL of the update definitions file - */ -QString Updater::url() const -{ - return m_url; -} - -/** - * Returns the URL that the update definitions file wants us to open in - * a web browser. - * - * \warning You should call \c checkForUpdates() before using this functio - */ -QString Updater::openUrl() const -{ - return m_openUrl; -} - -/** - * Returns the changelog defined by the update definitions file. - * \warning You should call \c checkForUpdates() before using this function - */ -QString Updater::changelog() const -{ - return m_changelog; -} - -/** - * Returns the name of the module (if defined) - */ -QString Updater::moduleName() const -{ - return m_moduleName; -} - -/** - * Returns the platform key (be it system-set or user-set). - * If you do not define a platform key, the system will assign the following - * platform key: - * - On iOS: \c ios - * - On Mac OSX: \c osx - * - On Android: \c android - * - On GNU/Linux: \c linux - * - On Microsoft Windows: \c windows - */ -QString Updater::platformKey() const -{ - return m_platform; -} - -/** - * Returns the download URL defined by the update definitions file. - * \warning You should call \c checkForUpdates() before using this function - */ -QString Updater::downloadUrl() const -{ - return m_downloadUrl; -} - -/** - * Returns the latest version defined by the update definitions file. - * \warning You should call \c checkForUpdates() before using this function - */ -QString Updater::latestVersion() const -{ - return m_latestVersion; -} - -/** - * Returns the user-agent header used by the client when communicating - * with the server through HTTP - */ -QString Updater::userAgentString() const -{ - return m_userAgentString; -} - -/** - * Returns the "local" version of the installed module - */ -QString Updater::moduleVersion() const -{ - return m_moduleVersion; -} - -/** - * Returns \c true if the updater should NOT interpret the downloaded appcast. - * This is useful if you need to store more variables (or information) in the - * JSON file or use another appcast format (e.g. XML) - */ -bool Updater::customAppcast() const -{ - return m_customAppcast; -} - -/** - * Returns \c true if the updater should notify the user when an update is - * available. - */ -bool Updater::notifyOnUpdate() const -{ - return m_notifyOnUpdate; -} - -/** - * Returns \c true if the updater should notify the user when it finishes - * checking for updates. - * - * \note If set to \c true, the \c Updater will notify the user even when there - * are no updates available (by congratulating him/her about being smart) - */ -bool Updater::notifyOnFinish() const -{ - return m_notifyOnFinish; -} - -/** - * Returns \c true if there the current update is mandatory. - * \warning You should call \c checkForUpdates() before using this function -*/ -bool Updater::mandatoryUpdate() const -{ - return m_mandatoryUpdate; -} - -/** - * Returns \c true if there is an update available. - * \warning You should call \c checkForUpdates() before using this function - */ -bool Updater::updateAvailable() const { - return m_updateAvailable; -} -bool Updater::updateSameVersionAvailable() const { - return m_sameVersion; -} - -/** - * Returns \c true if the integrated downloader is enabled. - * \note If set to \c true, the \c Updater will open the downloader dialog if - * the user agrees to download the update. - */ -bool Updater::downloaderEnabled() const -{ - return m_downloaderEnabled; -} - -/** - * Returns \c true if the updater shall not intervene when the download has - * finished (you can use the \c QSimpleUpdater signals to know when the - * download is completed). - */ -bool Updater::useCustomInstallProcedures() const -{ - return m_downloader->useCustomInstallProcedures(); -} - -/** - * Downloads and interpets the update definitions file referenced by the - * \c url() function. - */ -void Updater::checkForUpdates(){ - QNetworkRequest request (url()); - if(!userAgentString().isEmpty()) request.setRawHeader("User-Agent", userAgentString().toUtf8()); - m_manager->get(request); -} - -/** - * Changes the \c url in which the \c Updater can find the update definitions - * file. - */ -void Updater::setUrl (const QString& url) -{ - m_url = url; -} - -/** - * Changes the module \a name. - * \note The module name is used on the user prompts. If the module name is - * empty, then the prompts will show the name of the application. - */ -void Updater::setModuleName (const QString& name) -{ - m_moduleName = name; -} - -/** - * If \a notify is set to \c true, then the \c Updater will notify the user - * when an update is available. - */ -void Updater::setNotifyOnUpdate (const bool notify) -{ - m_notifyOnUpdate = notify; -} - -/** - * If \a notify is set to \c true, then the \c Updater will notify the user - * when it has finished interpreting the update definitions file. - */ -void Updater::setNotifyOnFinish (const bool notify) -{ - m_notifyOnFinish = notify; -} -void Updater::setNoNotifyDownload(const bool notify) -{ - m_noTipDownload = notify; -} -void Updater::setCompareBySameString(const bool notify) -{ - m_bSameStringCompare = notify; -} -/** - * Changes the user agent string used to identify the client application - * from the server in a HTTP session. - * - * By default, the user agent will co - */ -void Updater::setUserAgentString (const QString& agent) -{ - m_userAgentString = agent; - m_downloader->setUserAgentString (agent); -} - -/** - * Changes the module \a version - * \note The module version is used to compare the local and remote versions. - * If the \a version parameter is empty, then the \c Updater will use the - * application version (referenced by \c qApp) - */ -void Updater::setModuleVersion (const QString& version) -{ - m_moduleVersion = version; -} - -/** - * If the \a enabled parameter is set to \c true, the \c Updater will open the - * integrated downloader if the user agrees to install the update (if any) - */ -void Updater::setDownloaderEnabled (const bool enabled) -{ - m_downloaderEnabled = enabled; -} - -/** - * Changes the platform key. - * If the platform key is empty, then the system will use the following keys: - * - On iOS: \c ios - * - On Mac OSX: \c osx - * - On Android: \c android - * - On GNU/Linux: \c linux - * - On Microsoft Windows: \c windows - */ -void Updater::setPlatformKey (const QString& platformKey) -{ - m_platform = platformKey; -} - -/** - * If the \a customAppcast parameter is set to \c true, then the \c Updater - * will not try to read the network reply from the server, instead, it will - * emit the \c appcastDownloaded() signal, which allows the application to - * read and interpret the appcast file by itself - */ -void Updater::setUseCustomAppcast (const bool customAppcast) -{ - m_customAppcast = customAppcast; -} - -/** - * If the \a custom parameter is set to \c true, the \c Updater will not try - * to open the downloaded file. Use the signals fired by the \c QSimpleUpdater - * to install the update from the downloaded file by yourself. - */ -void Updater::setUseCustomInstallProcedures (const bool custom) -{ - m_downloader->setUseCustomInstallProcedures (custom); -} - -/** - * If the \a mandatory_update is set to \c true, the \c Updater has to download and install the - * update. If the user cancels or exits, the application will close - */ -void Updater::setMandatoryUpdate(const bool mandatory_update) -{ - m_mandatoryUpdate = mandatory_update; -} -/** - * Called when the download of the update definitions file is finished. - */ - -void Updater::onReply(QNetworkReply* reply) { - /* Check if we need to redirect */ - QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); - if (!redirect.isEmpty()) { - setUrl (redirect.toString()); - checkForUpdates(); - return; - } - reply->ignoreSslErrors(); - /* There was a network error */ - int err = reply->error(); - if (err != QNetworkReply::NoError) { - qDebug()<<"Updater::onReply QNetworkReply::Error="<< err <url(); - setUpdateAvailable (false); - emit checkingFinished (url()); - return; - } - /* The application wants to interpret the appcast by itself */ - if (customAppcast()) { - emit appcastDownloaded (url(), reply->readAll()); - emit checkingFinished (url()); - return; - } - - /* Try to create a JSON document from downloaded data */ - QJsonDocument document = QJsonDocument::fromJson (reply->readAll()); - /* JSON is invalid */ - if(document.isNull()) { - qDebug()<<"Updater::onReply document.isNull()"; - setUpdateAvailable (false); - emit checkingFinished (url()); - return; - } - /* Get the platform information */ - QJsonObject updates = document.object().value ("updates").toObject(); - QJsonObject platform = updates.value(platformKey()).toObject(); - /* Get update information */ - m_openUrl = platform.value("open-url").toString(); - m_changelog = platform.value("changelog_zhCN").toString(); - m_downloadUrl = platform.value("download-url").toString(); - m_latestVersion = platform.value("latest-version").toString(); - if(platform.contains("mandatory-update")) m_mandatoryUpdate = platform.value ("mandatory-update").toBool(); - - /* Compare latest and current version */ - if(m_bSameStringCompare) { - m_sameVersion = false; - if(latestVersion()==moduleVersion()) m_sameVersion=true; - setUpdateAvailable(!m_sameVersion); - } else { - if(latestVersion()==moduleVersion()){ - setUpdateAvailable(false); - m_sameVersion = true; - } else { - setUpdateAvailable(compare(latestVersion(), moduleVersion())); - m_sameVersion = false; - } - } - emit checkingFinished(url()); -} - -/** - * Prompts the user based on the value of the \a available parameter and the - * settings of this instance of the \c Updater class. - */ -void Updater::setUpdateAvailable(const bool available) { - m_updateAvailable = available; - QMessageBox box; - box.setTextFormat (Qt::RichText); - box.setIcon (QMessageBox::Information); - if(updateAvailable() && (notifyOnUpdate() || notifyOnFinish())) { - QString text = tr("Would you like to download the update now?"); - if(m_mandatoryUpdate) text = tr ("Would you like to download the update now? This is a mandatory update, exiting now will close the application"); - if(m_noTipDownload) { - m_downloader->setUrlId (url()); - m_downloader->setFileName (downloadUrl().split ("/").last()); - m_downloader->setMandatoryUpdate(m_mandatoryUpdate); - m_downloader->startDownload (QUrl (downloadUrl())); - m_downloader->m_strVersion=latestVersion(); - } else { - if (!openUrl().isEmpty()) QDesktopServices::openUrl (QUrl (openUrl())); - else if (downloaderEnabled()) { - m_downloader->setUrlId (url()); - m_downloader->setFileName (downloadUrl().split ("/").last()); - m_downloader->setMandatoryUpdate(m_mandatoryUpdate); - m_downloader->startDownload (QUrl (downloadUrl())); - m_downloader->m_strVersion=latestVersion(); - } - else QDesktopServices::openUrl (QUrl (downloadUrl())); - } - } - - else if (notifyOnFinish()) { - box.setStandardButtons (QMessageBox::Close); - box.setInformativeText (tr ("No updates are available for the moment")); - box.setText ("

" - + tr ("Congratulations! You are running the " - "latest version of %1").arg (moduleName()) - + "

"); - - box.exec(); - } -} - -/** - * Compares the two version strings (\a x and \a y). - * - If \a x is greater than \y, this function returns \c true. - * - If \a y is greater than \x, this function returns \c false. - * - If both versions are the same, this function returns \c false. - */ -bool Updater::compare(const QString& x, const QString& y) { - QStringList versionsX = x.split("."); - QStringList versionsY = y.split("."); - int count = qMin(versionsX.count(), versionsY.count()); - for (int i = 0; i < count; ++i) { - int a = QString(versionsX.at (i)).toInt(); - int b = QString(versionsY.at (i)).toInt(); - if(a >= b) return true; - else if(b > a) return false; - } - return versionsY.count() < versionsX.count(); -} +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This file is part of the QSimpleUpdater library, which is released under + * the DBAD license, you can read a copy of it below: + * + * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, + * DISTRIBUTION AND MODIFICATION: + * + * Do whatever you like with the original work, just don't be a dick. + * Being a dick includes - but is not limited to - the following instances: + * + * 1a. Outright copyright infringement - Don't just copy this and change the + * name. + * 1b. Selling the unmodified original with no work done what-so-ever, that's + * REALLY being a dick. + * 1c. Modifying the original work to contain hidden harmful content. + * That would make you a PROPER dick. + * + * If you become rich through modifications, related works/services, or + * supporting the original work, share the love. + * Only a dick would make loads off this work and not buy the original works + * creator(s) a pint. + * + * Code is provided with no warranty. Using somebody else's code and bitching + * when it goes wrong makes you a DONKEY dick. + * Fix the problem yourself. A non-dick would submit the fix back. + */ + +#include +#include +#include +#include +#include +#include + +#include "Updater.h" +#include "Downloader.h" +#include "cfg.h" +#include "qsettings.h" +Updater::Updater() { + m_url = ""; + m_openUrl = ""; + m_changelog = ""; + m_downloadUrl = ""; + m_latestVersion = ""; + m_customAppcast = false; + m_notifyOnUpdate = true; + m_notifyOnFinish = false; + m_updateAvailable = true; + m_sameVersion = false; + m_downloaderEnabled = true; + m_noTipDownload = false; + m_bSameStringCompare = false; + m_moduleName = qApp->applicationName(); + m_moduleVersion = qApp->applicationVersion(); + m_mandatoryUpdate = false; + + m_downloader = new Downloader(); + m_manager = new QNetworkAccessManager(); + QNetworkReply *pReply = m_manager->get(QNetworkRequest(QUrl(UpdVerUrl))); + QReplyTimeout *pTimeout = new QReplyTimeout(pReply, 10000); + // 超时进一步处理 + connect(pTimeout, &QReplyTimeout::timeout, [=]() { + qDebug() << "Timeout"; + }); +#if defined Q_OS_WIN + m_platform = "windows"; +#elif defined Q_OS_MAC + m_platform = "osx"; +#elif defined Q_OS_LINUX + m_platform = "linux"; +#elif defined Q_OS_ANDROID + m_platform = "android"; +#elif defined Q_OS_IOS + m_platform = "ios"; +#endif + setUserAgentString (QString ("%1/%2 (Qt; QSimpleUpdater)").arg(qApp->applicationName(), qApp->applicationVersion())); + connect (m_downloader, SIGNAL(downloadFinished(QString, QString)), this, SIGNAL (downloadFinished(QString, QString))); + connect (m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onReply(QNetworkReply*))); +} + +Updater::~Updater() +{ + delete m_downloader; +} + +/** + * Returns the URL of the update definitions file + */ +QString Updater::url() const +{ + return m_url; +} + +/** + * Returns the URL that the update definitions file wants us to open in + * a web browser. + * + * \warning You should call \c checkForUpdates() before using this functio + */ +QString Updater::openUrl() const +{ + return m_openUrl; +} + +/** + * Returns the changelog defined by the update definitions file. + * \warning You should call \c checkForUpdates() before using this function + */ +QString Updater::changelog() const +{ + return m_changelog; +} + +/** + * Returns the name of the module (if defined) + */ +QString Updater::moduleName() const +{ + return m_moduleName; +} + +/** + * Returns the platform key (be it system-set or user-set). + * If you do not define a platform key, the system will assign the following + * platform key: + * - On iOS: \c ios + * - On Mac OSX: \c osx + * - On Android: \c android + * - On GNU/Linux: \c linux + * - On Microsoft Windows: \c windows + */ +QString Updater::platformKey() const +{ + return m_platform; +} + +/** + * Returns the download URL defined by the update definitions file. + * \warning You should call \c checkForUpdates() before using this function + */ +QString Updater::downloadUrl() const +{ + return m_downloadUrl; +} + +/** + * Returns the latest version defined by the update definitions file. + * \warning You should call \c checkForUpdates() before using this function + */ +QString Updater::latestVersion() const +{ + return m_latestVersion; +} + +/** + * Returns the user-agent header used by the client when communicating + * with the server through HTTP + */ +QString Updater::userAgentString() const +{ + return m_userAgentString; +} + +/** + * Returns the "local" version of the installed module + */ +QString Updater::moduleVersion() const +{ + return m_moduleVersion; +} + +/** + * Returns \c true if the updater should NOT interpret the downloaded appcast. + * This is useful if you need to store more variables (or information) in the + * JSON file or use another appcast format (e.g. XML) + */ +bool Updater::customAppcast() const +{ + return m_customAppcast; +} + +/** + * Returns \c true if the updater should notify the user when an update is + * available. + */ +bool Updater::notifyOnUpdate() const +{ + return m_notifyOnUpdate; +} + +/** + * Returns \c true if the updater should notify the user when it finishes + * checking for updates. + * + * \note If set to \c true, the \c Updater will notify the user even when there + * are no updates available (by congratulating him/her about being smart) + */ +bool Updater::notifyOnFinish() const +{ + return m_notifyOnFinish; +} + +/** + * Returns \c true if there the current update is mandatory. + * \warning You should call \c checkForUpdates() before using this function +*/ +bool Updater::mandatoryUpdate() const +{ + return m_mandatoryUpdate; +} + +/** + * Returns \c true if there is an update available. + * \warning You should call \c checkForUpdates() before using this function + */ +bool Updater::updateAvailable() const { + return m_updateAvailable; +} +bool Updater::updateSameVersionAvailable() const { + return m_sameVersion; +} + +/** + * Returns \c true if the integrated downloader is enabled. + * \note If set to \c true, the \c Updater will open the downloader dialog if + * the user agrees to download the update. + */ +bool Updater::downloaderEnabled() const +{ + return m_downloaderEnabled; +} + +/** + * Returns \c true if the updater shall not intervene when the download has + * finished (you can use the \c QSimpleUpdater signals to know when the + * download is completed). + */ +bool Updater::useCustomInstallProcedures() const +{ + return m_downloader->useCustomInstallProcedures(); +} + +/** + * Downloads and interpets the update definitions file referenced by the + * \c url() function. + */ +void Updater::checkForUpdates(){ + QNetworkRequest request (url()); + if(!userAgentString().isEmpty()) request.setRawHeader("User-Agent", userAgentString().toUtf8()); + m_manager->get(request); +} + +/** + * Changes the \c url in which the \c Updater can find the update definitions + * file. + */ +void Updater::setUrl (const QString& url) +{ + m_url = url; +} + +/** + * Changes the module \a name. + * \note The module name is used on the user prompts. If the module name is + * empty, then the prompts will show the name of the application. + */ +void Updater::setModuleName (const QString& name) +{ + m_moduleName = name; +} + +/** + * If \a notify is set to \c true, then the \c Updater will notify the user + * when an update is available. + */ +void Updater::setNotifyOnUpdate (const bool notify) +{ + m_notifyOnUpdate = notify; +} + +/** + * If \a notify is set to \c true, then the \c Updater will notify the user + * when it has finished interpreting the update definitions file. + */ +void Updater::setNotifyOnFinish (const bool notify) +{ + m_notifyOnFinish = notify; +} +void Updater::setNoNotifyDownload(const bool notify) +{ + m_noTipDownload = notify; +} +void Updater::setCompareBySameString(const bool notify) +{ + m_bSameStringCompare = notify; +} +/** + * Changes the user agent string used to identify the client application + * from the server in a HTTP session. + * + * By default, the user agent will co + */ +void Updater::setUserAgentString (const QString& agent) +{ + m_userAgentString = agent; + m_downloader->setUserAgentString (agent); +} + +/** + * Changes the module \a version + * \note The module version is used to compare the local and remote versions. + * If the \a version parameter is empty, then the \c Updater will use the + * application version (referenced by \c qApp) + */ +void Updater::setModuleVersion (const QString& version) +{ + m_moduleVersion = version; +} + +/** + * If the \a enabled parameter is set to \c true, the \c Updater will open the + * integrated downloader if the user agrees to install the update (if any) + */ +void Updater::setDownloaderEnabled (const bool enabled) +{ + m_downloaderEnabled = enabled; +} + +/** + * Changes the platform key. + * If the platform key is empty, then the system will use the following keys: + * - On iOS: \c ios + * - On Mac OSX: \c osx + * - On Android: \c android + * - On GNU/Linux: \c linux + * - On Microsoft Windows: \c windows + */ +void Updater::setPlatformKey (const QString& platformKey) +{ + m_platform = platformKey; +} + +/** + * If the \a customAppcast parameter is set to \c true, then the \c Updater + * will not try to read the network reply from the server, instead, it will + * emit the \c appcastDownloaded() signal, which allows the application to + * read and interpret the appcast file by itself + */ +void Updater::setUseCustomAppcast (const bool customAppcast) +{ + m_customAppcast = customAppcast; +} + +/** + * If the \a custom parameter is set to \c true, the \c Updater will not try + * to open the downloaded file. Use the signals fired by the \c QSimpleUpdater + * to install the update from the downloaded file by yourself. + */ +void Updater::setUseCustomInstallProcedures (const bool custom) +{ + m_downloader->setUseCustomInstallProcedures (custom); +} + +/** + * If the \a mandatory_update is set to \c true, the \c Updater has to download and install the + * update. If the user cancels or exits, the application will close + */ +void Updater::setMandatoryUpdate(const bool mandatory_update) +{ + m_mandatoryUpdate = mandatory_update; +} +/** + * Called when the download of the update definitions file is finished. + */ + +void Updater::onReply(QNetworkReply* reply) { + /* Check if we need to redirect */ + QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); + if (!redirect.isEmpty()) { + setUrl (redirect.toString()); + checkForUpdates(); + return; + } + reply->ignoreSslErrors(); + /* There was a network error */ + int err = reply->error(); + if (err != QNetworkReply::NoError) { + qDebug()<<"Updater::onReply QNetworkReply::Error="<< err <url(); + setUpdateAvailable (false); + emit checkingFinished (url()); + return; + } + /* The application wants to interpret the appcast by itself */ + if (customAppcast()) { + emit appcastDownloaded (url(), reply->readAll()); + emit checkingFinished (url()); + return; + } + + /* Try to create a JSON document from downloaded data */ + QJsonDocument document = QJsonDocument::fromJson (reply->readAll()); + /* JSON is invalid */ + if(document.isNull()) { + qDebug()<<"Updater::onReply document.isNull()"; + setUpdateAvailable (false); + emit checkingFinished (url()); + return; + } + /* Get the platform information */ + QJsonObject updates = document.object().value ("updates").toObject(); + QJsonObject platform = updates.value(platformKey()).toObject(); + /* Get update information */ + m_openUrl = platform.value("open-url").toString(); + m_changelog = platform.value("changelog_zhCN").toString(); + m_downloadUrl = platform.value("download-url").toString(); + m_latestVersion = platform.value("latest-version").toString(); + if(platform.contains("mandatory-update")) m_mandatoryUpdate = platform.value ("mandatory-update").toBool(); + + /* Compare latest and current version */ + if(m_bSameStringCompare) { + m_sameVersion = false; + if(latestVersion()==moduleVersion()) m_sameVersion=true; + setUpdateAvailable(!m_sameVersion); + } else { + if(latestVersion()==moduleVersion()){ + setUpdateAvailable(false); + m_sameVersion = true; + } else { + setUpdateAvailable(compare(latestVersion(), moduleVersion())); + m_sameVersion = false; + } + } + emit checkingFinished(url()); +} + +/** + * Prompts the user based on the value of the \a available parameter and the + * settings of this instance of the \c Updater class. + */ +void Updater::setUpdateAvailable(const bool available) { + m_updateAvailable = available; + QMessageBox box; + box.setTextFormat (Qt::RichText); + box.setIcon (QMessageBox::Information); + if(updateAvailable() && (notifyOnUpdate() || notifyOnFinish())) { + QString text = tr("Would you like to download the update now?"); + if(m_mandatoryUpdate) text = tr ("Would you like to download the update now? This is a mandatory update, exiting now will close the application"); + if(m_noTipDownload) { + m_downloader->setUrlId (url()); + m_downloader->setFileName (downloadUrl().split ("/").last()); + m_downloader->setMandatoryUpdate(m_mandatoryUpdate); + m_downloader->startDownload (QUrl (downloadUrl())); + m_downloader->m_strVersion=latestVersion(); + } else { + if (!openUrl().isEmpty()) QDesktopServices::openUrl (QUrl (openUrl())); + else if (downloaderEnabled()) { + m_downloader->setUrlId (url()); + m_downloader->setFileName (downloadUrl().split ("/").last()); + m_downloader->setMandatoryUpdate(m_mandatoryUpdate); + m_downloader->startDownload (QUrl (downloadUrl())); + m_downloader->m_strVersion=latestVersion(); + } + else QDesktopServices::openUrl (QUrl (downloadUrl())); + } + } + + else if (notifyOnFinish()) { + box.setStandardButtons (QMessageBox::Close); + box.setInformativeText (tr ("No updates are available for the moment")); + box.setText ("

" + + tr ("Congratulations! You are running the " + "latest version of %1").arg (moduleName()) + + "

"); + + box.exec(); + } +} + +/** + * Compares the two version strings (\a x and \a y). + * - If \a x is greater than \y, this function returns \c true. + * - If \a y is greater than \x, this function returns \c false. + * - If both versions are the same, this function returns \c false. + */ +bool Updater::compare(const QString& x, const QString& y) { + QStringList versionsX = x.split("."); + QStringList versionsY = y.split("."); + int count = qMin(versionsX.count(), versionsY.count()); + for (int i = 0; i < count; ++i) { + int a = QString(versionsX.at (i)).toInt(); + int b = QString(versionsY.at (i)).toInt(); + if(a >= b) return true; + else if(b > a) return false; + } + return versionsY.count() < versionsX.count(); +} diff --git a/LedOK/QSimpleUpdater/src/Updater.h b/LedOK/QSimpleUpdater/src/Updater.h index 984d30d..9e9c064 100644 --- a/LedOK/QSimpleUpdater/src/Updater.h +++ b/LedOK/QSimpleUpdater/src/Updater.h @@ -1,156 +1,156 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This file is part of the QSimpleUpdater library, which is released under - * the DBAD license, you can read a copy of it below: - * - * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, - * DISTRIBUTION AND MODIFICATION: - * - * Do whatever you like with the original work, just don't be a dick. - * Being a dick includes - but is not limited to - the following instances: - * - * 1a. Outright copyright infringement - Don't just copy this and change the - * name. - * 1b. Selling the unmodified original with no work done what-so-ever, that's - * REALLY being a dick. - * 1c. Modifying the original work to contain hidden harmful content. - * That would make you a PROPER dick. - * - * If you become rich through modifications, related works/services, or - * supporting the original work, share the love. - * Only a dick would make loads off this work and not buy the original works - * creator(s) a pint. - * - * Code is provided with no warranty. Using somebody else's code and bitching - * when it goes wrong makes you a DONKEY dick. - * Fix the problem yourself. A non-dick would submit the fix back. - */ - -#ifndef _QSIMPLEUPDATER_UPDATER_H -#define _QSIMPLEUPDATER_UPDATER_H - -#include -#include -#include -#include - -#include - -class Downloader; - -/** - * \brief Downloads and interprests the update definition file - */ -class QSU_DECL Updater : public QObject -{ - Q_OBJECT - -signals: - void checkingFinished (const QString& url); - void downloadFinished (const QString& url, const QString& filepath); - void appcastDownloaded (const QString& url, const QByteArray& data); - -public: - Updater(); - ~Updater(); - - QString url() const; - QString openUrl() const; - QString changelog() const; - QString moduleName() const; - QString downloadUrl() const; - QString platformKey() const; - QString moduleVersion() const; - QString latestVersion() const; - QString userAgentString() const; - bool mandatoryUpdate() const; - - bool customAppcast() const; - bool notifyOnUpdate() const; - bool notifyOnFinish() const; - bool updateAvailable() const; - bool updateSameVersionAvailable() const; - bool downloaderEnabled() const; - bool useCustomInstallProcedures() const; - -public slots: - void checkForUpdates(); - void setUrl (const QString& url); - void setModuleName (const QString& name); - void setNotifyOnUpdate (const bool notify); - void setNotifyOnFinish (const bool notify); - void setNoNotifyDownload(const bool notify); - void setCompareBySameString(const bool notify); - - void setUserAgentString (const QString& agent); - void setModuleVersion (const QString& version); - void setDownloaderEnabled (const bool enabled); - void setPlatformKey (const QString& platformKey); - void setUseCustomAppcast (const bool customAppcast); - void setUseCustomInstallProcedures (const bool custom); - void setMandatoryUpdate (const bool mandatory_update); - -private slots: - void onReply (QNetworkReply* reply); - void setUpdateAvailable (const bool available); - -private: - bool compare (const QString& x, const QString& y); - -private: - QString m_url; - QString m_userAgentString; - - bool m_customAppcast; - bool m_notifyOnUpdate; - bool m_notifyOnFinish; - bool m_updateAvailable; - bool m_sameVersion; - bool m_downloaderEnabled; - bool m_mandatoryUpdate; - bool m_noTipDownload; - bool m_bSameStringCompare; - - QString m_openUrl; - QString m_platform; - QString m_changelog; - QString m_moduleName; - QString m_downloadUrl; - QString m_moduleVersion; - QString m_latestVersion; - - - Downloader* m_downloader; - QNetworkAccessManager* m_manager; -}; -#include -#include -#include - -class QReplyTimeout : public QObject { - - Q_OBJECT - -public: - QReplyTimeout(QNetworkReply *reply, const int timeout) : QObject(reply) { - Q_ASSERT(reply); - if (reply && reply->isRunning()) { // 启动单次定时器 - QTimer::singleShot(timeout, this, SLOT(onTimeout())); - } - } - -signals: - void timeout(); // 超时信号 - 供进一步处理 - -private slots: - void onTimeout() { // 处理超时 - QNetworkReply *reply = static_cast(parent()); - if (reply->isRunning()) { - reply->abort(); - reply->deleteLater(); - emit timeout(); - } - } -}; -#endif +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This file is part of the QSimpleUpdater library, which is released under + * the DBAD license, you can read a copy of it below: + * + * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, + * DISTRIBUTION AND MODIFICATION: + * + * Do whatever you like with the original work, just don't be a dick. + * Being a dick includes - but is not limited to - the following instances: + * + * 1a. Outright copyright infringement - Don't just copy this and change the + * name. + * 1b. Selling the unmodified original with no work done what-so-ever, that's + * REALLY being a dick. + * 1c. Modifying the original work to contain hidden harmful content. + * That would make you a PROPER dick. + * + * If you become rich through modifications, related works/services, or + * supporting the original work, share the love. + * Only a dick would make loads off this work and not buy the original works + * creator(s) a pint. + * + * Code is provided with no warranty. Using somebody else's code and bitching + * when it goes wrong makes you a DONKEY dick. + * Fix the problem yourself. A non-dick would submit the fix back. + */ + +#ifndef _QSIMPLEUPDATER_UPDATER_H +#define _QSIMPLEUPDATER_UPDATER_H + +#include +#include +#include +#include + +#include + +class Downloader; + +/** + * \brief Downloads and interprests the update definition file + */ +class QSU_DECL Updater : public QObject +{ + Q_OBJECT + +signals: + void checkingFinished (const QString& url); + void downloadFinished (const QString& url, const QString& filepath); + void appcastDownloaded (const QString& url, const QByteArray& data); + +public: + Updater(); + ~Updater(); + + QString url() const; + QString openUrl() const; + QString changelog() const; + QString moduleName() const; + QString downloadUrl() const; + QString platformKey() const; + QString moduleVersion() const; + QString latestVersion() const; + QString userAgentString() const; + bool mandatoryUpdate() const; + + bool customAppcast() const; + bool notifyOnUpdate() const; + bool notifyOnFinish() const; + bool updateAvailable() const; + bool updateSameVersionAvailable() const; + bool downloaderEnabled() const; + bool useCustomInstallProcedures() const; + +public slots: + void checkForUpdates(); + void setUrl (const QString& url); + void setModuleName (const QString& name); + void setNotifyOnUpdate (const bool notify); + void setNotifyOnFinish (const bool notify); + void setNoNotifyDownload(const bool notify); + void setCompareBySameString(const bool notify); + + void setUserAgentString (const QString& agent); + void setModuleVersion (const QString& version); + void setDownloaderEnabled (const bool enabled); + void setPlatformKey (const QString& platformKey); + void setUseCustomAppcast (const bool customAppcast); + void setUseCustomInstallProcedures (const bool custom); + void setMandatoryUpdate (const bool mandatory_update); + +private slots: + void onReply (QNetworkReply* reply); + void setUpdateAvailable (const bool available); + +private: + bool compare (const QString& x, const QString& y); + +private: + QString m_url; + QString m_userAgentString; + + bool m_customAppcast; + bool m_notifyOnUpdate; + bool m_notifyOnFinish; + bool m_updateAvailable; + bool m_sameVersion; + bool m_downloaderEnabled; + bool m_mandatoryUpdate; + bool m_noTipDownload; + bool m_bSameStringCompare; + + QString m_openUrl; + QString m_platform; + QString m_changelog; + QString m_moduleName; + QString m_downloadUrl; + QString m_moduleVersion; + QString m_latestVersion; + + + Downloader* m_downloader; + QNetworkAccessManager* m_manager; +}; +#include +#include +#include + +class QReplyTimeout : public QObject { + + Q_OBJECT + +public: + QReplyTimeout(QNetworkReply *reply, const int timeout) : QObject(reply) { + Q_ASSERT(reply); + if (reply && reply->isRunning()) { // 启动单次定时器 + QTimer::singleShot(timeout, this, SLOT(onTimeout())); + } + } + +signals: + void timeout(); // 超时信号 - 供进一步处理 + +private slots: + void onTimeout() { // 处理超时 + QNetworkReply *reply = static_cast(parent()); + if (reply->isRunning()) { + reply->abort(); + reply->deleteLater(); + emit timeout(); + } + } +}; +#endif diff --git a/LedOK/QSimpleUpdater/tests/Test_Downloader.h b/LedOK/QSimpleUpdater/tests/Test_Downloader.h index b0d0658..a8c4e9b 100644 --- a/LedOK/QSimpleUpdater/tests/Test_Downloader.h +++ b/LedOK/QSimpleUpdater/tests/Test_Downloader.h @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2015-2016 Alex Spataru - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#ifndef TEST_DOWNLOADER_H -#define TEST_DOWNLOADER_H - -#include -#include - -class Test_Downloader : public QObject -{ - Q_OBJECT -}; - -#endif +/* + * Copyright (c) 2015-2016 Alex Spataru + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef TEST_DOWNLOADER_H +#define TEST_DOWNLOADER_H + +#include +#include + +class Test_Downloader : public QObject +{ + Q_OBJECT +}; + +#endif diff --git a/LedOK/QSimpleUpdater/tests/Test_QSimpleUpdater.h b/LedOK/QSimpleUpdater/tests/Test_QSimpleUpdater.h index 2fff5ee..0e78a3f 100644 --- a/LedOK/QSimpleUpdater/tests/Test_QSimpleUpdater.h +++ b/LedOK/QSimpleUpdater/tests/Test_QSimpleUpdater.h @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2015-2016 Alex Spataru - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#ifndef TEST_QSIMPLEUPDATER_H -#define TEST_QSIMPLEUPDATER_H - -#include -#include - -class Test_QSimpleUpdater : public QObject -{ - Q_OBJECT -}; - -#endif +/* + * Copyright (c) 2015-2016 Alex Spataru + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef TEST_QSIMPLEUPDATER_H +#define TEST_QSIMPLEUPDATER_H + +#include +#include + +class Test_QSimpleUpdater : public QObject +{ + Q_OBJECT +}; + +#endif diff --git a/LedOK/QSimpleUpdater/tests/Test_Updater.h b/LedOK/QSimpleUpdater/tests/Test_Updater.h index 886eaba..cb354d8 100644 --- a/LedOK/QSimpleUpdater/tests/Test_Updater.h +++ b/LedOK/QSimpleUpdater/tests/Test_Updater.h @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2015-2016 Alex Spataru - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#ifndef TEST_UPDATER_H -#define TEST_UPDATER_H - -#include -#include - -class Test_Updater : public QObject -{ - Q_OBJECT -}; - -#endif +/* + * Copyright (c) 2015-2016 Alex Spataru + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef TEST_UPDATER_H +#define TEST_UPDATER_H + +#include +#include + +class Test_Updater : public QObject +{ + Q_OBJECT +}; + +#endif diff --git a/LedOK/QSimpleUpdater/tests/main.cpp b/LedOK/QSimpleUpdater/tests/main.cpp index 60e7521..787818e 100644 --- a/LedOK/QSimpleUpdater/tests/main.cpp +++ b/LedOK/QSimpleUpdater/tests/main.cpp @@ -1,41 +1,41 @@ -/* - * Copyright (c) 2015-2016 Alex Spataru - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include "Test_Updater.h" -#include "Test_Downloader.h" -#include "Test_QSimpleUpdater.h" - -int main (int argc, char* argv[]) -{ - QApplication app (argc, argv); - - app.setApplicationName ("QSimpleUpdater Tests"); - app.setOrganizationName ("The QSimpleUpdater Library"); - - QTest::qExec (new Test_Updater, argc, argv); - QTest::qExec (new Test_Downloader, argc, argv); - QTest::qExec (new Test_QSimpleUpdater, argc, argv); - - QTimer::singleShot (1000, Qt::PreciseTimer, qApp, SLOT (quit())); - - return app.exec(); -} +/* + * Copyright (c) 2015-2016 Alex Spataru + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "Test_Updater.h" +#include "Test_Downloader.h" +#include "Test_QSimpleUpdater.h" + +int main (int argc, char* argv[]) +{ + QApplication app (argc, argv); + + app.setApplicationName ("QSimpleUpdater Tests"); + app.setOrganizationName ("The QSimpleUpdater Library"); + + QTest::qExec (new Test_Updater, argc, argv); + QTest::qExec (new Test_Downloader, argc, argv); + QTest::qExec (new Test_QSimpleUpdater, argc, argv); + + QTimer::singleShot (1000, Qt::PreciseTimer, qApp, SLOT (quit())); + + return app.exec(); +} diff --git a/LedOK/QSimpleUpdater/tutorial/src/Window.cpp b/LedOK/QSimpleUpdater/tutorial/src/Window.cpp index 1b34273..5879e06 100644 --- a/LedOK/QSimpleUpdater/tutorial/src/Window.cpp +++ b/LedOK/QSimpleUpdater/tutorial/src/Window.cpp @@ -1,137 +1,137 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This work is free. You can redistribute it and/or modify it under the - * terms of the Do What The Fuck You Want To Public License, Version 2, - * as published by Sam Hocevar. See the COPYING file for more details. - */ - -#include "Window.h" -#include "ui_Window.h" - -#include -#include - -//============================================================================== -// Define the URL of the Update Definitions file -//============================================================================== - -static const QString DEFS_URL = "https://raw.githubusercontent.com/" - "alex-spataru/QSimpleUpdater/master/tutorial/" - "definitions/updates.json"; - -//============================================================================== -// Window::Window -//============================================================================== - -Window::Window (QWidget* parent) : QMainWindow (parent) -{ - m_ui = new Ui::Window; - m_ui->setupUi (this); - - setWindowTitle (qApp->applicationName()); - - /* QSimpleUpdater is single-instance */ - m_updater = QSimpleUpdater::getInstance(); - - /* Check for updates when the "Check For Updates" button is clicked */ - connect (m_updater, SIGNAL (checkingFinished (QString)), - this, SLOT (updateChangelog (QString))); - connect (m_updater, SIGNAL (appcastDownloaded (QString, QByteArray)), - this, SLOT (displayAppcast (QString, QByteArray))); - - /* React to button clicks */ - connect (m_ui->resetButton, SIGNAL (clicked()), - this, SLOT (resetFields())); - connect (m_ui->closeButton, SIGNAL (clicked()), - this, SLOT (close())); - connect (m_ui->checkButton, SIGNAL (clicked()), - this, SLOT (checkForUpdates())); - - /* Resize the dialog to fit */ - setMinimumSize (minimumSizeHint()); - resize (minimumSizeHint()); - - /* Reset the UI state */ - resetFields(); -} - -//============================================================================== -// Window::~Window -//============================================================================== - -Window::~Window() -{ - delete m_ui; -} - -//============================================================================== -// Window::checkForUpdates -//============================================================================== - -void Window::resetFields() -{ - m_ui->installedVersion->setText ("0.1"); - m_ui->customAppcast->setChecked (false); - m_ui->enableDownloader->setChecked (true); - m_ui->showAllNotifcations->setChecked (false); - m_ui->showUpdateNotifications->setChecked (true); - m_ui->mandatoryUpdate->setChecked (false); - -} - -//============================================================================== -// Window::checkForUpdates -//============================================================================== - -void Window::checkForUpdates() -{ - /* Get settings from the UI */ - QString version = m_ui->installedVersion->text(); - bool customAppcast = m_ui->customAppcast->isChecked(); - bool downloaderEnabled = m_ui->enableDownloader->isChecked(); - bool notifyOnFinish = m_ui->showAllNotifcations->isChecked(); - bool notifyOnUpdate = m_ui->showUpdateNotifications->isChecked(); - bool mandatoryUpdate = m_ui->mandatoryUpdate->isChecked(); - - /* Apply the settings */ - m_updater->setModuleVersion (DEFS_URL, version); - m_updater->setNotifyOnFinish (DEFS_URL, notifyOnFinish); - m_updater->setNotifyOnUpdate (DEFS_URL, notifyOnUpdate); - m_updater->setUseCustomAppcast (DEFS_URL, customAppcast); - m_updater->setDownloaderEnabled (DEFS_URL, downloaderEnabled); - m_updater->setMandatoryUpdate (DEFS_URL, mandatoryUpdate); - - /* Check for updates */ - m_updater->checkForUpdates (DEFS_URL); -} - -//============================================================================== -// Window::updateChangelog -//============================================================================== - -void Window::updateChangelog (const QString& url) -{ - if (url == DEFS_URL) - m_ui->changelogText->setText (m_updater->getChangelog (url)); -} - - -//============================================================================== -// Window::displayAppcast -//============================================================================== - -void Window::displayAppcast (const QString& url, const QByteArray& reply) -{ - if (url == DEFS_URL) { - QString text = "This is the downloaded appcast:

" +
-                       QString::fromUtf8 (reply) +
-                       "

If you need to store more information on the " - "appcast (or use another format), just use the " - "QSimpleUpdater::setCustomAppcast() function. " - "It allows your application to interpret the appcast " - "using your code and not QSU's code.

"; - - m_ui->changelogText->setText (text); - } -} +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This work is free. You can redistribute it and/or modify it under the + * terms of the Do What The Fuck You Want To Public License, Version 2, + * as published by Sam Hocevar. See the COPYING file for more details. + */ + +#include "Window.h" +#include "ui_Window.h" + +#include +#include + +//============================================================================== +// Define the URL of the Update Definitions file +//============================================================================== + +static const QString DEFS_URL = "https://raw.githubusercontent.com/" + "alex-spataru/QSimpleUpdater/master/tutorial/" + "definitions/updates.json"; + +//============================================================================== +// Window::Window +//============================================================================== + +Window::Window (QWidget* parent) : QMainWindow (parent) +{ + m_ui = new Ui::Window; + m_ui->setupUi (this); + + setWindowTitle (qApp->applicationName()); + + /* QSimpleUpdater is single-instance */ + m_updater = QSimpleUpdater::getInstance(); + + /* Check for updates when the "Check For Updates" button is clicked */ + connect (m_updater, SIGNAL (checkingFinished (QString)), + this, SLOT (updateChangelog (QString))); + connect (m_updater, SIGNAL (appcastDownloaded (QString, QByteArray)), + this, SLOT (displayAppcast (QString, QByteArray))); + + /* React to button clicks */ + connect (m_ui->resetButton, SIGNAL (clicked()), + this, SLOT (resetFields())); + connect (m_ui->closeButton, SIGNAL (clicked()), + this, SLOT (close())); + connect (m_ui->checkButton, SIGNAL (clicked()), + this, SLOT (checkForUpdates())); + + /* Resize the dialog to fit */ + setMinimumSize (minimumSizeHint()); + resize (minimumSizeHint()); + + /* Reset the UI state */ + resetFields(); +} + +//============================================================================== +// Window::~Window +//============================================================================== + +Window::~Window() +{ + delete m_ui; +} + +//============================================================================== +// Window::checkForUpdates +//============================================================================== + +void Window::resetFields() +{ + m_ui->installedVersion->setText ("0.1"); + m_ui->customAppcast->setChecked (false); + m_ui->enableDownloader->setChecked (true); + m_ui->showAllNotifcations->setChecked (false); + m_ui->showUpdateNotifications->setChecked (true); + m_ui->mandatoryUpdate->setChecked (false); + +} + +//============================================================================== +// Window::checkForUpdates +//============================================================================== + +void Window::checkForUpdates() +{ + /* Get settings from the UI */ + QString version = m_ui->installedVersion->text(); + bool customAppcast = m_ui->customAppcast->isChecked(); + bool downloaderEnabled = m_ui->enableDownloader->isChecked(); + bool notifyOnFinish = m_ui->showAllNotifcations->isChecked(); + bool notifyOnUpdate = m_ui->showUpdateNotifications->isChecked(); + bool mandatoryUpdate = m_ui->mandatoryUpdate->isChecked(); + + /* Apply the settings */ + m_updater->setModuleVersion (DEFS_URL, version); + m_updater->setNotifyOnFinish (DEFS_URL, notifyOnFinish); + m_updater->setNotifyOnUpdate (DEFS_URL, notifyOnUpdate); + m_updater->setUseCustomAppcast (DEFS_URL, customAppcast); + m_updater->setDownloaderEnabled (DEFS_URL, downloaderEnabled); + m_updater->setMandatoryUpdate (DEFS_URL, mandatoryUpdate); + + /* Check for updates */ + m_updater->checkForUpdates (DEFS_URL); +} + +//============================================================================== +// Window::updateChangelog +//============================================================================== + +void Window::updateChangelog (const QString& url) +{ + if (url == DEFS_URL) + m_ui->changelogText->setText (m_updater->getChangelog (url)); +} + + +//============================================================================== +// Window::displayAppcast +//============================================================================== + +void Window::displayAppcast (const QString& url, const QByteArray& reply) +{ + if (url == DEFS_URL) { + QString text = "This is the downloaded appcast:

" +
+                       QString::fromUtf8 (reply) +
+                       "

If you need to store more information on the " + "appcast (or use another format), just use the " + "QSimpleUpdater::setCustomAppcast() function. " + "It allows your application to interpret the appcast " + "using your code and not QSU's code.

"; + + m_ui->changelogText->setText (text); + } +} diff --git a/LedOK/QSimpleUpdater/tutorial/src/Window.h b/LedOK/QSimpleUpdater/tutorial/src/Window.h index ccd8da2..027508e 100644 --- a/LedOK/QSimpleUpdater/tutorial/src/Window.h +++ b/LedOK/QSimpleUpdater/tutorial/src/Window.h @@ -1,40 +1,40 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This work is free. You can redistribute it and/or modify it under the - * terms of the Do What The Fuck You Want To Public License, Version 2, - * as published by Sam Hocevar. See the COPYING file for more details. - */ - -#ifndef _WINDOW_H -#define _WINDOW_H - -#include -#include - -namespace Ui { -class Window; -} - -class QSimpleUpdater; - -class Window : public QMainWindow -{ - Q_OBJECT - -public: - explicit Window (QWidget* parent = 0); - ~Window(); - -public slots: - void resetFields(); - void checkForUpdates(); - void updateChangelog (const QString& url); - void displayAppcast (const QString& url, const QByteArray& reply); - -private: - Ui::Window* m_ui; - QSimpleUpdater* m_updater; -}; - -#endif +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This work is free. You can redistribute it and/or modify it under the + * terms of the Do What The Fuck You Want To Public License, Version 2, + * as published by Sam Hocevar. See the COPYING file for more details. + */ + +#ifndef _WINDOW_H +#define _WINDOW_H + +#include +#include + +namespace Ui { +class Window; +} + +class QSimpleUpdater; + +class Window : public QMainWindow +{ + Q_OBJECT + +public: + explicit Window (QWidget* parent = 0); + ~Window(); + +public slots: + void resetFields(); + void checkForUpdates(); + void updateChangelog (const QString& url); + void displayAppcast (const QString& url, const QByteArray& reply); + +private: + Ui::Window* m_ui; + QSimpleUpdater* m_updater; +}; + +#endif diff --git a/LedOK/QSimpleUpdater/tutorial/src/main.cpp b/LedOK/QSimpleUpdater/tutorial/src/main.cpp index a793d0d..85c31ba 100644 --- a/LedOK/QSimpleUpdater/tutorial/src/main.cpp +++ b/LedOK/QSimpleUpdater/tutorial/src/main.cpp @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2014-2016 Alex Spataru - * - * This work is free. You can redistribute it and/or modify it under the - * terms of the Do What The Fuck You Want To Public License, Version 2, - * as published by Sam Hocevar. See the COPYING file for more details. - */ - -#include "Window.h" - -int main (int argc, char** argv) -{ - QApplication app (argc, argv); - app.setApplicationVersion ("1.0"); - app.setApplicationName ("Bob's Badass App"); - - Window window; - window.show(); - - return app.exec(); -} +/* + * Copyright (c) 2014-2016 Alex Spataru + * + * This work is free. You can redistribute it and/or modify it under the + * terms of the Do What The Fuck You Want To Public License, Version 2, + * as published by Sam Hocevar. See the COPYING file for more details. + */ + +#include "Window.h" + +int main (int argc, char** argv) +{ + QApplication app (argc, argv); + app.setApplicationVersion ("1.0"); + app.setApplicationName ("Bob's Badass App"); + + Window window; + window.show(); + + return app.exec(); +} diff --git a/LedOK/base/aboutdlg.cpp b/LedOK/base/aboutdlg.cpp index 92327ca..6361d3c 100644 --- a/LedOK/base/aboutdlg.cpp +++ b/LedOK/base/aboutdlg.cpp @@ -1,43 +1,43 @@ -#include "aboutdlg.h" -#include "globaldefine.h" -#include -#include -#include - -AboutDlg::AboutDlg(QWidget *parent) : QDialog(parent) { - setWindowFlag(Qt::WindowContextHelpButtonHint, false); - setWindowTitle(tr("About")); - - auto hBox = new QHBoxLayout(this); - hBox->setContentsMargins(24,24,24,24); - hBox->setSpacing(24); - auto label_4 = new QLabel(); - label_4->setPixmap(QPixmap(":/res/Logo.png")); - hBox->addWidget(label_4); - - auto vBox = new QVBoxLayout(); - auto label = new QLabel("LedOK Express"); - QFont font; - font.setPointSize(24); - label->setFont(font); - label->setTextFormat(Qt::AutoText); - label->setAlignment(Qt::AlignCenter); - vBox->addWidget(label); - - auto label_2 = new QLabel(APP_VERSION); - QFont font1; - font1.setPointSize(14); - label_2->setFont(font1); - label_2->setAlignment(Qt::AlignCenter); - vBox->addWidget(label_2); - - auto label_3 = new QLabel("www.ledok.cn"); - QFont font2; - font2.setPointSize(15); - label_3->setFont(font2); - label_3->setAlignment(Qt::AlignCenter); - label_3->setOpenExternalLinks(true); - vBox->addWidget(label_3); - - hBox->addLayout(vBox); -} +#include "aboutdlg.h" +#include "globaldefine.h" +#include +#include +#include + +AboutDlg::AboutDlg(QWidget *parent) : QDialog(parent) { + setWindowFlag(Qt::WindowContextHelpButtonHint, false); + setWindowTitle(tr("About")); + + auto hBox = new QHBoxLayout(this); + hBox->setContentsMargins(24,24,24,24); + hBox->setSpacing(24); + auto label_4 = new QLabel(); + label_4->setPixmap(QPixmap(":/res/Logo.png")); + hBox->addWidget(label_4); + + auto vBox = new QVBoxLayout(); + auto label = new QLabel("LedOK Express"); + QFont font; + font.setPointSize(24); + label->setFont(font); + label->setTextFormat(Qt::AutoText); + label->setAlignment(Qt::AlignCenter); + vBox->addWidget(label); + + auto label_2 = new QLabel(APP_VERSION); + QFont font1; + font1.setPointSize(14); + label_2->setFont(font1); + label_2->setAlignment(Qt::AlignCenter); + vBox->addWidget(label_2); + + auto label_3 = new QLabel("www.ledok.cn"); + QFont font2; + font2.setPointSize(15); + label_3->setFont(font2); + label_3->setAlignment(Qt::AlignCenter); + label_3->setOpenExternalLinks(true); + vBox->addWidget(label_3); + + hBox->addLayout(vBox); +} diff --git a/LedOK/base/aboutdlg.h b/LedOK/base/aboutdlg.h index b182f75..566056d 100644 --- a/LedOK/base/aboutdlg.h +++ b/LedOK/base/aboutdlg.h @@ -1,12 +1,12 @@ -#ifndef ABOUTDLG_H -#define ABOUTDLG_H - -#include - -class AboutDlg : public QDialog { - Q_OBJECT -public: - explicit AboutDlg(QWidget *parent = nullptr); -}; - -#endif // ABOUTDLG_H +#ifndef ABOUTDLG_H +#define ABOUTDLG_H + +#include + +class AboutDlg : public QDialog { + Q_OBJECT +public: + explicit AboutDlg(QWidget *parent = nullptr); +}; + +#endif // ABOUTDLG_H diff --git a/LedOK/base/changepasswordform.cpp b/LedOK/base/changepasswordform.cpp index 5d670f9..cadff25 100644 --- a/LedOK/base/changepasswordform.cpp +++ b/LedOK/base/changepasswordform.cpp @@ -1,84 +1,84 @@ -#include "changepasswordform.h" -#include -#include -#include -#include -#include -#include -#include "cfg.h" -#include "QTextCodec" -ChangePasswordForm::ChangePasswordForm(QWidget *parent) : BaseDlg(parent) { - resize(240, 160); - auto vBox = new QVBoxLayout(this); - auto hBox = new QHBoxLayout(); - auto label = new QLabel(tr("Old password")); - hBox->addWidget(label); - - fdOld = new QLineEdit(); - fdOld->setEchoMode(QLineEdit::Password); - fdOld->setMaxLength(16); - hBox->addWidget(fdOld); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - auto label_2 = new QLabel(tr("New password")); - hBox->addWidget(label_2); - - fdNew = new QLineEdit(); - fdNew->setEchoMode(QLineEdit::Password); - fdNew->setMaxLength(8); - hBox->addWidget(fdNew); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - auto label_3 = new QLabel(tr("Repeat again")); - hBox->addWidget(label_3); - - fdAgn = new QLineEdit(); - fdAgn->setEchoMode(QLineEdit::Password); - fdAgn->setMaxLength(8); - hBox->addWidget(fdAgn); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - auto pushButton_2 = new QPushButton(tr("OK")); - pushButton_2->setProperty("ssType", "progManageTool"); - hBox->addWidget(pushButton_2); - connect(pushButton_2, &QPushButton::clicked, this, [this]() { - QString pwdOld = fdOld->text(); - if(pwdOld.isEmpty()) { - QMessageBox::warning(this, tr("Tip"), tr("Please input old password")); - fdOld->setFocus(); - return; - } - QSettings settings; - QString pwdRaw = settings.value("advUiPs").toString(); - QString pwd = pwdRaw.isEmpty() ? "888" : QTextCodec::codecForName("GBK")->toUnicode(QByteArray::fromBase64(pwdRaw.toLocal8Bit())); - if(pwd != pwdOld) { - QMessageBox::critical(this, tr("Tip"), tr("Old password is wrong")); - fdOld->setFocus(); - return; - } - QString pwdNew = fdNew->text(); - if(pwdNew.length() < 6) { - QMessageBox::warning(this, tr("Tip"), tr("Please enter a password with more than 6 characters")); - fdNew->setFocus(); - return; - } - QString pwdAgn = fdAgn->text(); - if(pwdAgn != pwdNew) { - QMessageBox::warning(this, tr("Tip"), tr("The new password is not consistent in two times")); - fdAgn->setFocus(); - return; - } - settings.setValue("advUiPs", QString::fromLatin1(pwdNew.toLocal8Bit().toBase64())); - QMessageBox::information(this, tr("Tip"), tr("Password changed successfully")); - accept(); - }); - - auto pushButton = new QPushButton(tr("Cancel")); - pushButton->setProperty("ssType", "progManageTool"); - hBox->addWidget(pushButton); - connect(pushButton, &QPushButton::clicked, this, &ChangePasswordForm::reject); - vBox->addLayout(hBox); -} +#include "changepasswordform.h" +#include +#include +#include +#include +#include +#include +#include "cfg.h" +#include "QTextCodec" +ChangePasswordForm::ChangePasswordForm(QWidget *parent) : BaseDlg(parent) { + resize(240, 160); + auto vBox = new QVBoxLayout(this); + auto hBox = new QHBoxLayout(); + auto label = new QLabel(tr("Old password")); + hBox->addWidget(label); + + fdOld = new QLineEdit(); + fdOld->setEchoMode(QLineEdit::Password); + fdOld->setMaxLength(16); + hBox->addWidget(fdOld); + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + auto label_2 = new QLabel(tr("New password")); + hBox->addWidget(label_2); + + fdNew = new QLineEdit(); + fdNew->setEchoMode(QLineEdit::Password); + fdNew->setMaxLength(8); + hBox->addWidget(fdNew); + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + auto label_3 = new QLabel(tr("Repeat again")); + hBox->addWidget(label_3); + + fdAgn = new QLineEdit(); + fdAgn->setEchoMode(QLineEdit::Password); + fdAgn->setMaxLength(8); + hBox->addWidget(fdAgn); + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + auto pushButton_2 = new QPushButton(tr("OK")); + pushButton_2->setProperty("ssType", "progManageTool"); + hBox->addWidget(pushButton_2); + connect(pushButton_2, &QPushButton::clicked, this, [this]() { + QString pwdOld = fdOld->text(); + if(pwdOld.isEmpty()) { + QMessageBox::warning(this, tr("Tip"), tr("Please input old password")); + fdOld->setFocus(); + return; + } + QSettings settings; + QString pwdRaw = settings.value("advUiPs").toString(); + QString pwd = pwdRaw.isEmpty() ? "888" : QTextCodec::codecForName("GBK")->toUnicode(QByteArray::fromBase64(pwdRaw.toLocal8Bit())); + if(pwd != pwdOld) { + QMessageBox::critical(this, tr("Tip"), tr("Old password is wrong")); + fdOld->setFocus(); + return; + } + QString pwdNew = fdNew->text(); + if(pwdNew.length() < 6) { + QMessageBox::warning(this, tr("Tip"), tr("Please enter a password with more than 6 characters")); + fdNew->setFocus(); + return; + } + QString pwdAgn = fdAgn->text(); + if(pwdAgn != pwdNew) { + QMessageBox::warning(this, tr("Tip"), tr("The new password is not consistent in two times")); + fdAgn->setFocus(); + return; + } + settings.setValue("advUiPs", QString::fromLatin1(pwdNew.toLocal8Bit().toBase64())); + QMessageBox::information(this, tr("Tip"), tr("Password changed successfully")); + accept(); + }); + + auto pushButton = new QPushButton(tr("Cancel")); + pushButton->setProperty("ssType", "progManageTool"); + hBox->addWidget(pushButton); + connect(pushButton, &QPushButton::clicked, this, &ChangePasswordForm::reject); + vBox->addLayout(hBox); +} diff --git a/LedOK/base/changepasswordform.h b/LedOK/base/changepasswordform.h index ad0b372..f1301f9 100644 --- a/LedOK/base/changepasswordform.h +++ b/LedOK/base/changepasswordform.h @@ -1,16 +1,16 @@ -#ifndef CHANGEPASSWORDFORM_H -#define CHANGEPASSWORDFORM_H - -#include "basedlg.h" -#include - -class ChangePasswordForm : public BaseDlg { - Q_OBJECT - -public: - explicit ChangePasswordForm(QWidget *parent = nullptr); - QLineEdit *fdOld, *fdNew, *fdAgn; - -}; - -#endif // CHANGEPASSWORDFORM_H +#ifndef CHANGEPASSWORDFORM_H +#define CHANGEPASSWORDFORM_H + +#include "basedlg.h" +#include + +class ChangePasswordForm : public BaseDlg { + Q_OBJECT + +public: + explicit ChangePasswordForm(QWidget *parent = nullptr); + QLineEdit *fdOld, *fdNew, *fdAgn; + +}; + +#endif // CHANGEPASSWORDFORM_H diff --git a/LedOK/base/customprogressindicator.cpp b/LedOK/base/customprogressindicator.cpp index cd7ecdb..743fcf1 100644 --- a/LedOK/base/customprogressindicator.cpp +++ b/LedOK/base/customprogressindicator.cpp @@ -1,137 +1,137 @@ -#include "customprogressindicator.h" -#include -#include - -CustomProgressIndicator::CustomProgressIndicator(QWidget* parent) - : QWidget(parent), - angle_(0), - timerId_(-1), - delay_(20), - displayedWhenStopped_(false), - color_(Qt::green) { - setAttribute(Qt::WA_DeleteOnClose); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setFocusPolicy(Qt::NoFocus); - setWindowFlags(Qt::FramelessWindowHint);//无窗体 - setAttribute(Qt::WA_TranslucentBackground);//背景透明 -} - -bool CustomProgressIndicator::isAnimated () const { - return (timerId_ != -1); -} - -void CustomProgressIndicator::setDisplayedWhenStopped(bool state) { - displayedWhenStopped_ = state; - - update(); -} - -bool CustomProgressIndicator::isDisplayedWhenStopped() const { - return displayedWhenStopped_; -} -void CustomProgressIndicator::setDisplayModel(int iFlag) -{ - m_iLoopBackFlag=iFlag; -} -void CustomProgressIndicator::startAnimation() { - angle_ = 0; - - if (timerId_ == -1) { - timerId_ = startTimer(delay_); - } -} -void CustomProgressIndicator::setDisplayStringInfo(QString strTip,QString strTiping) { - m_strTip=strTip; - m_strTiping=strTiping; - update(); -} -void CustomProgressIndicator::stopAnimation() { - if (timerId_ != -1) { - killTimer(timerId_); - } - - timerId_ = -1; - - update(); -} - -void CustomProgressIndicator::setAnimationDelay(int delay) { - if (timerId_ != -1){ - killTimer(timerId_); - } - - delay_ = delay; - - if (timerId_ != -1){ - timerId_ = startTimer(delay_); - } -} - -void CustomProgressIndicator::setColor(const QColor & color) { - color_ = color; - - update(); -} - -QSize CustomProgressIndicator::sizeHint() const { - return QSize(80,80); -} - - -void CustomProgressIndicator::timerEvent(QTimerEvent *) { - angle_ = (angle_+30)%360; - - update(); -} - -void CustomProgressIndicator::paintEvent(QPaintEvent *) { - QPainter p(this); - drawJuHua(&p); -} -void CustomProgressIndicator::drawJuHua(QPainter *painter) -{ - painter->setRenderHint(QPainter::Antialiasing); - if (displayedWhenStopped_ && !isAnimated()) //如果displayedWhenStopped_==flash并且动画已经停止则不绘制 - { - painter->setPen(color_); - painter->drawPixmap(rect(),currentPix_); - painter->drawText(rect(), Qt::AlignCenter, m_strTip); - - return; - } - - int width = qMin(this->width(), this->height()); - - int outerRadius = (width-1) >> 1; - int innerRadius = int(((width-1) >> 1)*0.38); - - int capsuleHeight = outerRadius - innerRadius; - int capsuleWidth = (width > 32 ) ? (int)(capsuleHeight *0.23) : (int)(capsuleHeight *0.35); - int capsuleRadius = capsuleWidth >> 1; - if(m_iLoopBackFlag==1) - { - painter->setPen(color_); - painter->drawText(rect(), Qt::AlignCenter, m_strTiping); - } - else { - /* 撰写进度 */ - if (progress_ > 0 && progress_ < 100) { - painter->setPen(color_); - painter->drawText(rect(), Qt::AlignCenter, QString("%1%").arg(progress_)); - } - else if (progress_ == 100) { - stopAnimation(); - } - } - for (int i=0; i<12; ++i) { - QColor color = color_; - color.setAlphaF(1.0f - (i/12.0f)); - painter->setPen(Qt::NoPen); - painter->setBrush(color); - painter->save(); - painter->translate(rect().center()); - painter->rotate(angle_ - i*30.0f); - painter->drawRoundedRect(((-capsuleWidth) >> 1), -(innerRadius+capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius); - painter->restore(); - } -} +#include "customprogressindicator.h" +#include +#include + +CustomProgressIndicator::CustomProgressIndicator(QWidget* parent) + : QWidget(parent), + angle_(0), + timerId_(-1), + delay_(20), + displayedWhenStopped_(false), + color_(Qt::green) { + setAttribute(Qt::WA_DeleteOnClose); + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setFocusPolicy(Qt::NoFocus); + setWindowFlags(Qt::FramelessWindowHint);//无窗体 + setAttribute(Qt::WA_TranslucentBackground);//背景透明 +} + +bool CustomProgressIndicator::isAnimated () const { + return (timerId_ != -1); +} + +void CustomProgressIndicator::setDisplayedWhenStopped(bool state) { + displayedWhenStopped_ = state; + + update(); +} + +bool CustomProgressIndicator::isDisplayedWhenStopped() const { + return displayedWhenStopped_; +} +void CustomProgressIndicator::setDisplayModel(int iFlag) +{ + m_iLoopBackFlag=iFlag; +} +void CustomProgressIndicator::startAnimation() { + angle_ = 0; + + if (timerId_ == -1) { + timerId_ = startTimer(delay_); + } +} +void CustomProgressIndicator::setDisplayStringInfo(QString strTip,QString strTiping) { + m_strTip=strTip; + m_strTiping=strTiping; + update(); +} +void CustomProgressIndicator::stopAnimation() { + if (timerId_ != -1) { + killTimer(timerId_); + } + + timerId_ = -1; + + update(); +} + +void CustomProgressIndicator::setAnimationDelay(int delay) { + if (timerId_ != -1){ + killTimer(timerId_); + } + + delay_ = delay; + + if (timerId_ != -1){ + timerId_ = startTimer(delay_); + } +} + +void CustomProgressIndicator::setColor(const QColor & color) { + color_ = color; + + update(); +} + +QSize CustomProgressIndicator::sizeHint() const { + return QSize(80,80); +} + + +void CustomProgressIndicator::timerEvent(QTimerEvent *) { + angle_ = (angle_+30)%360; + + update(); +} + +void CustomProgressIndicator::paintEvent(QPaintEvent *) { + QPainter p(this); + drawJuHua(&p); +} +void CustomProgressIndicator::drawJuHua(QPainter *painter) +{ + painter->setRenderHint(QPainter::Antialiasing); + if (displayedWhenStopped_ && !isAnimated()) //如果displayedWhenStopped_==flash并且动画已经停止则不绘制 + { + painter->setPen(color_); + painter->drawPixmap(rect(),currentPix_); + painter->drawText(rect(), Qt::AlignCenter, m_strTip); + + return; + } + + int width = qMin(this->width(), this->height()); + + int outerRadius = (width-1) >> 1; + int innerRadius = int(((width-1) >> 1)*0.38); + + int capsuleHeight = outerRadius - innerRadius; + int capsuleWidth = (width > 32 ) ? (int)(capsuleHeight *0.23) : (int)(capsuleHeight *0.35); + int capsuleRadius = capsuleWidth >> 1; + if(m_iLoopBackFlag==1) + { + painter->setPen(color_); + painter->drawText(rect(), Qt::AlignCenter, m_strTiping); + } + else { + /* 撰写进度 */ + if (progress_ > 0 && progress_ < 100) { + painter->setPen(color_); + painter->drawText(rect(), Qt::AlignCenter, QString("%1%").arg(progress_)); + } + else if (progress_ == 100) { + stopAnimation(); + } + } + for (int i=0; i<12; ++i) { + QColor color = color_; + color.setAlphaF(1.0f - (i/12.0f)); + painter->setPen(Qt::NoPen); + painter->setBrush(color); + painter->save(); + painter->translate(rect().center()); + painter->rotate(angle_ - i*30.0f); + painter->drawRoundedRect(((-capsuleWidth) >> 1), -(innerRadius+capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius); + painter->restore(); + } +} diff --git a/LedOK/base/customprogressindicator.h b/LedOK/base/customprogressindicator.h index 571760d..3238a08 100644 --- a/LedOK/base/customprogressindicator.h +++ b/LedOK/base/customprogressindicator.h @@ -1,116 +1,116 @@ -#ifndef CUSTOMPROGRESSINDICATOR_H -#define CUSTOMPROGRESSINDICATOR_H - -#include -#include -#include -/* -* 菊花转 进度类,基于代码无需图片资源 -* 作者:陈鲁勇 -* 邮箱:727057301@qq.com -* 创建时间:2017年2月10日16:26:48 -* QT版本:5.0.2 -* CSDN:http://blog.csdn.net/csnd_ayo -* ************************************** -* 说明: -* 使用前请确保在QT.pro中加入 C++11 的支持 -* -* 示例代码: - - pIndicator = new CustomProgressIndicator(this); - pIndicator->setColor(Qt::red); - pIndicator->startAnimation(); -*/ - -class CustomProgressIndicator : public QWidget -{ - Q_OBJECT - Q_PROPERTY(int delay READ animationDelay WRITE setAnimationDelay) - Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped) - Q_PROPERTY(QColor color READ color WRITE setColor) -public: - CustomProgressIndicator(QWidget* parent = nullptr); - - int animationDelay() const { return delay_; } - - /* 动画是否正在进行中 */ - bool isAnimated () const; - - /* 动画完毕后,是否隐藏菊花转 */ - bool isDisplayedWhenStopped() const; - - /* 当前菊花转的颜色 */ - const QColor & color() const { return color_; } - - /* 虚函数:当前大小 */ - virtual QSize sizeHint() const; - - void setBackground(const QString& _icon) { - currentPix_ = QPixmap(_icon); - } -signals: - void Finished(void); -public slots: - - /* 开始动画 */ - void startAnimation(); - - /* 停止动画 */ - void stopAnimation(); - /* 设置停止菊花,显示圆圈加对号*/ - void setDisplayStringInfo(QString strTip,QString strTiping); - void setDisplayModel(int iFlag);//iFlag 0:表示进度统计,1:表示strTiping提示,结束后显示strTip - - /* 设置菊花转的转速 */ - void setAnimationDelay(int delay); - - /* 动画完毕后,是否隐藏菊花转 */ - void setDisplayedWhenStopped(bool state); - - /* 设置菊花转颜色 */ - void setColor(const QColor & color); - - /* - * 进度 - * 参数 _progress:当前进度 0 < _progress < 100 - */ - void onProgress(QString msg, int _progress, bool done) - { - Q_UNUSED(msg) - progress_ = _progress; - if(done) - { - progress_=100; - - } - } -protected: - /* 系统基类函数 */ - virtual void timerEvent(QTimerEvent * event); - virtual void paintEvent(QPaintEvent * event); - void drawJuHua(QPainter *painter); - -private: - /* 角度 */ - unsigned int angle_; - /* 定时器ID */ - int timerId_; - /* 转速 */ - int delay_; - /* 是否隐藏 */ - bool displayedWhenStopped_; - /* 菊花转颜色 */ - QColor color_; - /* 进度 */ - int progress_; - /* 背景图 */ - QPixmap currentPix_; - /*显示圆圈中的字符串内容*/ - QString m_strTip = ""; - QString m_strTiping = ""; - int m_iLoopBackFlag = 0; - -}; - - -#endif // CUSTOMPROGRESSINDICATOR_H +#ifndef CUSTOMPROGRESSINDICATOR_H +#define CUSTOMPROGRESSINDICATOR_H + +#include +#include +#include +/* +* 菊花转 进度类,基于代码无需图片资源 +* 作者:陈鲁勇 +* 邮箱:727057301@qq.com +* 创建时间:2017年2月10日16:26:48 +* QT版本:5.0.2 +* CSDN:http://blog.csdn.net/csnd_ayo +* ************************************** +* 说明: +* 使用前请确保在QT.pro中加入 C++11 的支持 +* +* 示例代码: + + pIndicator = new CustomProgressIndicator(this); + pIndicator->setColor(Qt::red); + pIndicator->startAnimation(); +*/ + +class CustomProgressIndicator : public QWidget +{ + Q_OBJECT + Q_PROPERTY(int delay READ animationDelay WRITE setAnimationDelay) + Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped) + Q_PROPERTY(QColor color READ color WRITE setColor) +public: + CustomProgressIndicator(QWidget* parent = nullptr); + + int animationDelay() const { return delay_; } + + /* 动画是否正在进行中 */ + bool isAnimated () const; + + /* 动画完毕后,是否隐藏菊花转 */ + bool isDisplayedWhenStopped() const; + + /* 当前菊花转的颜色 */ + const QColor & color() const { return color_; } + + /* 虚函数:当前大小 */ + virtual QSize sizeHint() const; + + void setBackground(const QString& _icon) { + currentPix_ = QPixmap(_icon); + } +signals: + void Finished(void); +public slots: + + /* 开始动画 */ + void startAnimation(); + + /* 停止动画 */ + void stopAnimation(); + /* 设置停止菊花,显示圆圈加对号*/ + void setDisplayStringInfo(QString strTip,QString strTiping); + void setDisplayModel(int iFlag);//iFlag 0:表示进度统计,1:表示strTiping提示,结束后显示strTip + + /* 设置菊花转的转速 */ + void setAnimationDelay(int delay); + + /* 动画完毕后,是否隐藏菊花转 */ + void setDisplayedWhenStopped(bool state); + + /* 设置菊花转颜色 */ + void setColor(const QColor & color); + + /* + * 进度 + * 参数 _progress:当前进度 0 < _progress < 100 + */ + void onProgress(QString msg, int _progress, bool done) + { + Q_UNUSED(msg) + progress_ = _progress; + if(done) + { + progress_=100; + + } + } +protected: + /* 系统基类函数 */ + virtual void timerEvent(QTimerEvent * event); + virtual void paintEvent(QPaintEvent * event); + void drawJuHua(QPainter *painter); + +private: + /* 角度 */ + unsigned int angle_; + /* 定时器ID */ + int timerId_; + /* 转速 */ + int delay_; + /* 是否隐藏 */ + bool displayedWhenStopped_; + /* 菊花转颜色 */ + QColor color_; + /* 进度 */ + int progress_; + /* 背景图 */ + QPixmap currentPix_; + /*显示圆圈中的字符串内容*/ + QString m_strTip = ""; + QString m_strTiping = ""; + int m_iLoopBackFlag = 0; + +}; + + +#endif // CUSTOMPROGRESSINDICATOR_H diff --git a/LedOK/base/extendedgroupbox.cpp b/LedOK/base/extendedgroupbox.cpp index 4b14434..206236d 100644 --- a/LedOK/base/extendedgroupbox.cpp +++ b/LedOK/base/extendedgroupbox.cpp @@ -1,62 +1,62 @@ -#include "extendedgroupbox.h" -ExtendedGroupBox::ExtendedGroupBox(QWidget *parent /*= nullptr*/, State state /*= STATE_NORMAL*/) - : QGroupBox(parent) -{ - setCheckable(true); - state_ = state; - if (state_ == STATE_NORMAL) - { - //隐藏垂直边框 - setFlat(true); - } - connect(this, SIGNAL(clicked(bool)), this, SLOT(onChecked(bool))); -} - -ExtendedGroupBox::ExtendedGroupBox(const QString &title, QWidget *parent /*= nullptr*/, State state /*= STATE_NORMAL*/) - : QGroupBox(title, parent) -{ - setCheckable(true); - state_ = state; - if (state_ == STATE_NORMAL) - { - //隐藏垂直边框 - setFlat(true); - } - // this->toggled(); - - connect(this, SIGNAL(toggled(bool)), this, SLOT(onChecked(bool))); -} - - -void ExtendedGroupBox::onChecked(bool checked) -{ - if (checked) - { - //显示垂直边框 - QList widgets = findChildren(); - for (auto iter = widgets.begin(); iter != widgets.end(); ++iter) - { - (*iter)->setVisible(true); - } - state_ = STATE_EXPAND; - } - else - { - //隐藏垂直边框 - QList widgets = findChildren(); - for (auto iter = widgets.begin(); iter != widgets.end(); ++iter) - (*iter)->setVisible(false); -// QList layouts = findChildren(); -// for (auto iter1 = layouts.begin(); iter1 != layouts.end(); ++iter1) -// (*iter1)->setVisible(false); - -// QLayout aa; -// a-> - state_ = STATE_NORMAL; - } -} - -ExtendedGroupBox::State ExtendedGroupBox::getState() const -{ - return state_; -} +#include "extendedgroupbox.h" +ExtendedGroupBox::ExtendedGroupBox(QWidget *parent /*= nullptr*/, State state /*= STATE_NORMAL*/) + : QGroupBox(parent) +{ + setCheckable(true); + state_ = state; + if (state_ == STATE_NORMAL) + { + //隐藏垂直边框 + setFlat(true); + } + connect(this, SIGNAL(clicked(bool)), this, SLOT(onChecked(bool))); +} + +ExtendedGroupBox::ExtendedGroupBox(const QString &title, QWidget *parent /*= nullptr*/, State state /*= STATE_NORMAL*/) + : QGroupBox(title, parent) +{ + setCheckable(true); + state_ = state; + if (state_ == STATE_NORMAL) + { + //隐藏垂直边框 + setFlat(true); + } + // this->toggled(); + + connect(this, SIGNAL(toggled(bool)), this, SLOT(onChecked(bool))); +} + + +void ExtendedGroupBox::onChecked(bool checked) +{ + if (checked) + { + //显示垂直边框 + QList widgets = findChildren(); + for (auto iter = widgets.begin(); iter != widgets.end(); ++iter) + { + (*iter)->setVisible(true); + } + state_ = STATE_EXPAND; + } + else + { + //隐藏垂直边框 + QList widgets = findChildren(); + for (auto iter = widgets.begin(); iter != widgets.end(); ++iter) + (*iter)->setVisible(false); +// QList layouts = findChildren(); +// for (auto iter1 = layouts.begin(); iter1 != layouts.end(); ++iter1) +// (*iter1)->setVisible(false); + +// QLayout aa; +// a-> + state_ = STATE_NORMAL; + } +} + +ExtendedGroupBox::State ExtendedGroupBox::getState() const +{ + return state_; +} diff --git a/LedOK/base/extendedgroupbox.h b/LedOK/base/extendedgroupbox.h index 960d675..2adc841 100644 --- a/LedOK/base/extendedgroupbox.h +++ b/LedOK/base/extendedgroupbox.h @@ -1,32 +1,32 @@ -#ifndef EXTENDEDGROUPBOX_H -#define EXTENDEDGROUPBOX_H -#include -#include - -class ExtendedGroupBox : public QGroupBox -{ - Q_OBJECT - -public: - enum State - { - STATE_NORMAL, - STATE_EXPAND - }; - -public: - ExtendedGroupBox(QWidget *parent = nullptr, State state = STATE_NORMAL); - ExtendedGroupBox(const QString &title, QWidget *parent = nullptr, State state = STATE_NORMAL); - -private Q_SLOTS: - void onChecked(bool checked); - -public: - void addWidget(QWidget *widget); - State getState() const; - -private: - State state_; -}; - -#endif // EXTENDEDGROUPBOX_H +#ifndef EXTENDEDGROUPBOX_H +#define EXTENDEDGROUPBOX_H +#include +#include + +class ExtendedGroupBox : public QGroupBox +{ + Q_OBJECT + +public: + enum State + { + STATE_NORMAL, + STATE_EXPAND + }; + +public: + ExtendedGroupBox(QWidget *parent = nullptr, State state = STATE_NORMAL); + ExtendedGroupBox(const QString &title, QWidget *parent = nullptr, State state = STATE_NORMAL); + +private Q_SLOTS: + void onChecked(bool checked); + +public: + void addWidget(QWidget *widget); + State getState() const; + +private: + State state_; +}; + +#endif // EXTENDEDGROUPBOX_H diff --git a/LedOK/base/ffutil.cpp b/LedOK/base/ffutil.cpp index 18a8188..fe03275 100644 --- a/LedOK/base/ffutil.cpp +++ b/LedOK/base/ffutil.cpp @@ -6,6 +6,10 @@ extern "C"{ #include } +static void imgCleanupHandler(void *info) { + delete [] (uchar*)info; +} + QString videoInfo(QByteArray url, QImage &img, int64_t *dur, AVCodecID *codec_id) { AVFormatContext *fmt_ctx = avformat_alloc_context(); QString err; @@ -44,9 +48,12 @@ QString videoInfo(QByteArray url, QImage &img, int64_t *dur, AVCodecID *codec_id avcodec_free_context(&vcCtx); goto free; } - auto sws_ctx = sws_getContext(vcCtx->width, vcCtx->height, vcCtx->pix_fmt, vcCtx->width, vcCtx->height, AV_PIX_FMT_RGB32, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr); + auto sws_ctx = sws_getContext(vcCtx->width, vcCtx->height, vcCtx->pix_fmt, vcCtx->width, vcCtx->height, AV_PIX_FMT_RGB32, SWS_FAST_BILINEAR, 0, 0, 0); auto packet = av_packet_alloc(); auto frm = av_frame_alloc(); + int dstStride[4]{(vcCtx->width*4+63)/64*64}; + dstStride[3] = dstStride[0] * vcCtx->height; + uint8_t *dst[4]{0}; while(1) { if(av_read_frame(fmt_ctx, packet) < 0) break; if(packet->stream_index != vi_idx) continue; @@ -54,10 +61,9 @@ QString videoInfo(QByteArray url, QImage &img, int64_t *dur, AVCodecID *codec_id if(res < 0) break; while((res = avcodec_receive_frame(vcCtx, frm)) != AVERROR(EAGAIN)) { if(res < 0) goto free2; - img = QImage(vcCtx->width, vcCtx->height, QImage::Format_ARGB32); - uint8_t *dst[4]{img.bits()}; - int dstStride[4]{img.bytesPerLine()}; + dst[0] = new uchar[dstStride[3]]; sws_scale(sws_ctx, frm->data, frm->linesize, 0, vcCtx->height, dst, dstStride); + img = QImage(dst[0], vcCtx->width, vcCtx->height, dstStride[0], QImage::Format_ARGB32, imgCleanupHandler, dst[0]); goto free2; } } @@ -71,188 +77,6 @@ QString videoInfo(QByteArray url, QImage &img, int64_t *dur, AVCodecID *codec_id avformat_close_input(&fmt_ctx); return err; } -QString videoTrans(int sw, int sh, int dw, int dh, int cnt, QPointF pos, QByteArray file) { - AVFormatContext *in_fmt = avformat_alloc_context(), *out_fmt = 0; - AVCodecContext *de_ctx = 0, *en_ctx = 0; - QString err; - char buf[AV_ERROR_MAX_STRING_SIZE]; - int ret; - { - if((ret = avformat_open_input(&in_fmt, file.constData(), nullptr, nullptr)) < 0) { - err = QString("Couldn't open input stream. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - if((ret = avformat_find_stream_info(in_fmt, nullptr)) < 0) { - err = QString("Couldn't find stream information. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - auto outfile = file+"-square.mp4"; - if((ret = avformat_alloc_output_context2(&out_fmt, 0, "mp4", outfile.constData())) < 0) { - err = QString("avformat_alloc_output_context2 fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - int vi_idx = -1; - for(uint ss=0; ssnb_streams; ss++) { - AVStream *stream = in_fmt->streams[ss]; - AVStream *out_stream = avformat_new_stream(out_fmt, 0); - if((ret = avcodec_parameters_copy(out_stream->codecpar, stream->codecpar)) < 0) { - err = QString("avcodec_parameters_copy fail. ") + av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - out_stream->time_base = stream->time_base; - out_stream->start_time = stream->start_time; - out_stream->duration = stream->duration; - out_stream->avg_frame_rate = stream->avg_frame_rate; - out_stream->sample_aspect_ratio = {1,1}; - if(vi_idx == -1 && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) vi_idx = ss; - } - if(vi_idx == -1) { - err = "Didn't find a Video Stream"; - goto free; - } - - auto codecpar = in_fmt->streams[vi_idx]->codecpar; - qDebug()<<"codec_id"<codec_id<codec_id); - - auto decoder = avcodec_find_decoder(codecpar->codec_id); - if(decoder==0) { - err = "Could not found Video Decoder"; - goto free; - } - de_ctx = avcodec_alloc_context3(decoder); - avcodec_parameters_to_context(de_ctx, codecpar); - if(avcodec_open2(de_ctx, decoder, 0) < 0) { - err = "Could not open Video decode Ctx"; - goto free; - } - - auto out_codecpar = out_fmt->streams[vi_idx]->codecpar; - out_codecpar->codec_id = AV_CODEC_ID_H264; - out_codecpar->format = AV_PIX_FMT_YUV420P; - out_codecpar->width = dw; - out_codecpar->height = dh; - out_codecpar->sample_aspect_ratio = {1,1}; - out_fmt->streams[vi_idx]->sample_aspect_ratio = {1,1}; - - auto encoder = avcodec_find_encoder(out_codecpar->codec_id); - if(encoder==0) { - fprintf(stderr, "Codec not found\n"); - goto free; - } - en_ctx = avcodec_alloc_context3(encoder); - avcodec_parameters_to_context(en_ctx, out_codecpar); - en_ctx->bit_rate = dw*dh*6; - en_ctx->gop_size = de_ctx->gop_size; - en_ctx->max_b_frames = 3; - en_ctx->framerate = de_ctx->framerate; - en_ctx->time_base = out_fmt->streams[vi_idx]->time_base; - - if((ret = avcodec_open2(en_ctx, encoder, 0)) < 0) { - err = QString("Open video encode ctx failed. ") + av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - - if(out_fmt->flags & AVFMT_NOFILE) qDebug()<<"AVFMT_NOFILE"; - else if((ret = avio_open(&out_fmt->pb, outfile.constData(), AVIO_FLAG_WRITE)) < 0) { - err = QString("avio_open fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - if((ret = avformat_write_header(out_fmt, 0)) < 0) { - err = QString("avformat_write_header fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - auto sws_ctx = sws_getContext(de_ctx->width, de_ctx->height, de_ctx->pix_fmt, sw, sh, AV_PIX_FMT_0RGB, SWS_FAST_BILINEAR, 0, 0, 0); - auto out_sws_ctx = sws_getContext(dw, dh, AV_PIX_FMT_0RGB, dw, dh, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, 0, 0, 0); - auto packet = av_packet_alloc(); - auto frm = av_frame_alloc(); - auto out_frm = av_frame_alloc(); - QImage img(sw, sh, QImage::Format_RGB32); - uint8_t *img_data[4]{img.bits(), 0, 0, 0}; - int img_linesize[4]{img.bytesPerLine(), 0, 0, 0}; - QImage out_img(dw, dh, QImage::Format_RGB32); - uint8_t *out_img_data[4]{out_img.bits(), 0, 0, 0}; - int out_img_linesize[4]{out_img.bytesPerLine(), 0, 0, 0}; - QPainter painter(&out_img); - while(1) { - if((ret = av_read_frame(in_fmt, packet)) < 0) { - if(ret!=AVERROR_EOF) { - err = QString("Read packet fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - break; - } - ret = avcodec_send_packet(de_ctx, 0); - } else { - if(packet->stream_index != vi_idx) { - av_interleaved_write_frame(out_fmt, packet); - continue; - } - ret = avcodec_send_packet(de_ctx, packet); - } - if(ret < 0) { - err = QString("avcodec_send_packet fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - break; - } - while((ret = avcodec_receive_frame(de_ctx, frm)) != AVERROR(EAGAIN)) { - if(ret < 0) { - if(ret!=AVERROR_EOF) { - err = QString("Receive frame fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free2; - } - ret = avcodec_send_frame(en_ctx, 0); - } else { - sws_scale(sws_ctx, frm->data, frm->linesize, 0, de_ctx->height, img_data, img_linesize); - painter.drawImage(pos, img); - auto apos = pos; - for(int i=1; iformat = AV_PIX_FMT_YUV420P; - out_frm->width = dw; - out_frm->height = dh; - out_frm->sample_aspect_ratio = {1,1}; - if((ret = av_frame_get_buffer(out_frm, 0)) < 0) { - err = QString("av_frame_get_buffer fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free2; - } - sws_scale(out_sws_ctx, out_img_data, out_img_linesize, 0, dh, out_frm->data, out_frm->linesize); - ret = avcodec_send_frame(en_ctx, out_frm); - } - if(ret < 0) { - err = QString("avcodec_send_frame fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free2; - } - while((ret = avcodec_receive_packet(en_ctx, packet)) != AVERROR(EAGAIN)) { - if(ret < 0) { - if(ret!=AVERROR_EOF) err = QString("Receive frame fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - else { - av_interleaved_write_frame(out_fmt, 0); - av_write_trailer(out_fmt); - } - goto free2; - } else { - av_interleaved_write_frame(out_fmt, packet); - } - } - } - } - free2: - av_frame_free(&frm); - av_frame_free(&out_frm); - av_packet_free(&packet); - sws_freeContext(sws_ctx); - sws_freeContext(out_sws_ctx); - } - free: - avcodec_free_context(&de_ctx); - avcodec_free_context(&en_ctx); - avformat_close_input(&in_fmt); - avio_closep(&out_fmt->pb); - if(out_fmt) avformat_free_context(out_fmt); - return err; -} QString audioInfo(QByteArray url, int64_t *dur) { AVFormatContext *fmt_ctx = avformat_alloc_context(); QString err; diff --git a/LedOK/base/ffutil.h b/LedOK/base/ffutil.h index 2cda8cb..fff1b75 100644 --- a/LedOK/base/ffutil.h +++ b/LedOK/base/ffutil.h @@ -7,7 +7,6 @@ extern "C"{ } QString videoInfo(QByteArray url, QImage &, int64_t *dur, AVCodecID *); -QString videoTrans(int sw, int sh, int dw, int dh, int cnt, QPointF pos, QByteArray file); QString audioInfo(QByteArray url, int64_t *dur); #endif // FFUTIL_H diff --git a/LedOK/base/locolorselector.cpp b/LedOK/base/locolorselector.cpp index a07c69c..af69799 100644 --- a/LedOK/base/locolorselector.cpp +++ b/LedOK/base/locolorselector.cpp @@ -13,9 +13,12 @@ LoColorSelector::LoColorSelector(const QString &text, const QColor &color, QWidg } void LoColorSelector::init() { connect(this, &QPushButton::clicked, this, [this]{ - QColorDialog colorDlg(this->color, this); + QColorDialog colorDlg(this); colorDlg.setOption(QColorDialog::ShowAlphaChannel); colorDlg.setOption(QColorDialog::DontUseNativeDialog); + auto color = this->color; + color.setAlpha(255); + colorDlg.setCurrentColor(color); auto btn = new QPushButton(tr("Transparent")); connect(btn, &QPushButton::clicked, &colorDlg, [&colorDlg] { @@ -25,10 +28,8 @@ void LoColorSelector::init() { static_cast(colorDlg.layout()->itemAt(0)->layout()->itemAt(0)->layout())->insertWidget(2, btn); if(colorDlg.exec() != QColorDialog::Accepted) return; - QColor color = colorDlg.selectedColor(); - if(color == this->color) return; + color = colorDlg.selectedColor(); if(! color.isValid()) return; - if(color.alpha()==0 && this->color.alpha()==0) color.setAlpha(255); setColor(color); emit sColorChanged(color); }); diff --git a/LedOK/base/lodateselector.cpp b/LedOK/base/lodateselector.cpp index f306b50..66d4dbb 100644 --- a/LedOK/base/lodateselector.cpp +++ b/LedOK/base/lodateselector.cpp @@ -7,13 +7,13 @@ LoDateSelector::LoDateSelector(QWidget *parent) : QPushButton(parent) { setStyleSheet(R"rrr( LoDateSelector { background-color: transparent; - image: url(:/res/ProgramManager/EditProgram/DateSelect_enable.png); + image: url(:/res/program/DateSelect_enable.png); padding: 0; max-width: 32px; max-height: 32px; } LoDateSelector:!enabled{ - image: url(:/res/ProgramManager/EditProgram/DateSelect_e.png); + image: url(:/res/program/DateSelect_e.png); } LoDateSelector:pressed { margin-top: 1px; diff --git a/LedOK/base/loemptydialog.cpp b/LedOK/base/loemptydialog.cpp index 0ca4441..b24d64a 100644 --- a/LedOK/base/loemptydialog.cpp +++ b/LedOK/base/loemptydialog.cpp @@ -1,78 +1,78 @@ -#include "loemptydialog.h" -#include - -LoEmptyDialog::LoEmptyDialog(QWidget *parent) : BaseDlg(parent) { - setAttribute(Qt::WA_DeleteOnClose); - - auto pal = palette(); - pal.setBrush(QPalette::Window, QColor(0xdd, 0xdd, 0xdd, 0xdd)); - setPalette(pal); - - auto vBox = new QVBoxLayout(this); - vBox->addStretch(); - - mIndicator = new CustomProgressIndicator(this); - mIndicator->setDisplayModel(1); - mIndicator->setColor(QColor(0x0088dd)); - mIndicator->setDisplayedWhenStopped(true);//动画停止后任就显示,直到关闭窗口 - mIndicator->startAnimation(); - vBox->addWidget(mIndicator, 0, Qt::AlignCenter); - - vBox->addStretch(); - - label = new QLabel(); - label->setAlignment(Qt::AlignCenter); - label->setStyleSheet("font-size: 24px; font-weight: bold; color: #08d;"); - vBox->addWidget(label); - - vBox->addStretch(); -} - -void LoEmptyDialog::SetTipTextContent(QString strTip) { - label->setText(strTip); -} -void LoEmptyDialog::SetFailedTipString(QString strTip) { - mTimeroutTip = strTip; -} -bool LoEmptyDialog::getLockStatus() { - return iLockFlag; -} - -void LoEmptyDialog::lock(QString strTip, QString finishTip, QString timeroutTip) { - iLockFlag = true; - label->setText(strTip); - mFinishTip = finishTip; - mTimeroutTip = timeroutTip; -} - -void LoEmptyDialog::unlock() { - if(iClosedFlag==1) return; - label->setText(mFinishTip); - if(mIndicator != nullptr) { - mIndicator->setBackground(":/res/success.png"); - mIndicator->stopAnimation(); - CloseWndByDelaySec(600); - } - iClosedFlag=1; - iLockFlag = false; -} -void LoEmptyDialog::TimerOutUnlock() { - if(iClosedFlag==1) return; - label->setText(mTimeroutTip); - if(mIndicator != nullptr) { - mIndicator->setBackground(":/res/tip.png"); - mIndicator->stopAnimation(); - CloseWndByDelaySec(600); - } - iClosedFlag = 1; -} -void LoEmptyDialog::CloseWndByDelaySec(int iCloseWndDelaySec) { - auto timer = new QTimer(this); - timer->setSingleShot(true); - connect(timer, &QTimer::timeout, this, [this, timer] { - timer->stop(); - close(); - emit sigClose(); - }); - timer->start(iCloseWndDelaySec); -} +#include "loemptydialog.h" +#include + +LoEmptyDialog::LoEmptyDialog(QWidget *parent) : BaseDlg(parent) { + setAttribute(Qt::WA_DeleteOnClose); + + auto pal = palette(); + pal.setBrush(QPalette::Window, QColor(0xdd, 0xdd, 0xdd, 0xdd)); + setPalette(pal); + + auto vBox = new QVBoxLayout(this); + vBox->addStretch(); + + mIndicator = new CustomProgressIndicator(this); + mIndicator->setDisplayModel(1); + mIndicator->setColor(QColor(0x0088dd)); + mIndicator->setDisplayedWhenStopped(true);//动画停止后任就显示,直到关闭窗口 + mIndicator->startAnimation(); + vBox->addWidget(mIndicator, 0, Qt::AlignCenter); + + vBox->addStretch(); + + label = new QLabel(); + label->setAlignment(Qt::AlignCenter); + label->setStyleSheet("font-size: 24px; font-weight: bold; color: #08d;"); + vBox->addWidget(label); + + vBox->addStretch(); +} + +void LoEmptyDialog::SetTipTextContent(QString strTip) { + label->setText(strTip); +} +void LoEmptyDialog::SetFailedTipString(QString strTip) { + mTimeroutTip = strTip; +} +bool LoEmptyDialog::getLockStatus() { + return iLockFlag; +} + +void LoEmptyDialog::lock(QString strTip, QString finishTip, QString timeroutTip) { + iLockFlag = true; + label->setText(strTip); + mFinishTip = finishTip; + mTimeroutTip = timeroutTip; +} + +void LoEmptyDialog::unlock() { + if(iClosedFlag==1) return; + label->setText(mFinishTip); + if(mIndicator != nullptr) { + mIndicator->setBackground(":/res/success.png"); + mIndicator->stopAnimation(); + CloseWndByDelaySec(600); + } + iClosedFlag=1; + iLockFlag = false; +} +void LoEmptyDialog::TimerOutUnlock() { + if(iClosedFlag==1) return; + label->setText(mTimeroutTip); + if(mIndicator != nullptr) { + mIndicator->setBackground(":/res/tip.png"); + mIndicator->stopAnimation(); + CloseWndByDelaySec(600); + } + iClosedFlag = 1; +} +void LoEmptyDialog::CloseWndByDelaySec(int iCloseWndDelaySec) { + auto timer = new QTimer(this); + timer->setSingleShot(true); + connect(timer, &QTimer::timeout, this, [this, timer] { + timer->stop(); + close(); + emit sigClose(); + }); + timer->start(iCloseWndDelaySec); +} diff --git a/LedOK/base/loemptydialog.h b/LedOK/base/loemptydialog.h index 8bdbfe5..456ec1c 100644 --- a/LedOK/base/loemptydialog.h +++ b/LedOK/base/loemptydialog.h @@ -1,37 +1,37 @@ -#ifndef LOEMPTYDIALOG_H -#define LOEMPTYDIALOG_H - -#include -#include -#include - -class LoEmptyDialog : public BaseDlg { - Q_OBJECT -public: - explicit LoEmptyDialog(QWidget *parent = nullptr); - int exec() override { - emit startUp(); - return BaseDlg::exec(); - } - CustomProgressIndicator *mIndicator{0}; -signals: - void startUp(); - void sigClose(); -public slots: - void lock(QString strTip,QString strUnLockTip,QString strTimerOutUnLockTip); - void unlock(); - void TimerOutUnlock(); - bool getLockStatus(); - void SetFailedTipString(QString strTip); - void SetTipTextContent(QString strTip); -private: - QLabel *label; - int iClosedFlag=0; - bool iLockFlag = false; - QString mFinishTip; - QString mTimeroutTip; - LoEmptyDialog *m_pSelf=nullptr; - void CloseWndByDelaySec(int iCloseWndDelaySec); -}; - -#endif // LOEMPTYDIALOG_H +#ifndef LOEMPTYDIALOG_H +#define LOEMPTYDIALOG_H + +#include +#include +#include + +class LoEmptyDialog : public BaseDlg { + Q_OBJECT +public: + explicit LoEmptyDialog(QWidget *parent = nullptr); + int exec() override { + emit startUp(); + return BaseDlg::exec(); + } + CustomProgressIndicator *mIndicator{0}; +signals: + void startUp(); + void sigClose(); +public slots: + void lock(QString strTip,QString strUnLockTip,QString strTimerOutUnLockTip); + void unlock(); + void TimerOutUnlock(); + bool getLockStatus(); + void SetFailedTipString(QString strTip); + void SetTipTextContent(QString strTip); +private: + QLabel *label; + int iClosedFlag=0; + bool iLockFlag = false; + QString mFinishTip; + QString mTimeroutTip; + LoEmptyDialog *m_pSelf=nullptr; + void CloseWndByDelaySec(int iCloseWndDelaySec); +}; + +#endif // LOEMPTYDIALOG_H diff --git a/LedOK/base/loqtreewidget.cpp b/LedOK/base/loqtreewidget.cpp index faf4fc5..611d63e 100644 --- a/LedOK/base/loqtreewidget.cpp +++ b/LedOK/base/loqtreewidget.cpp @@ -19,13 +19,7 @@ void CheckableHeader::paintSection(QPainter *painter, const QRect &rect, int log LoQTreeWidget::LoQTreeWidget(QWidget *parent) : QTreeWidget(parent), m_checkState(CheckNone) { fdIsSelAll = new QCheckBox(); - fdIsSelAll->setStyleSheet(R"rrr( -QCheckBox::indicator { - width: 24px; - height: 24px; - margin-left: 10px; -} -)rrr"); + fdIsSelAll->setStyleSheet("QCheckBox{margin-left: 5px;}"); m_header = new CheckableHeader(Qt::Horizontal, fdIsSelAll); setHeader(m_header); setProperty("ssType", "topList"); diff --git a/LedOK/base/pixbmpshowdialog.cpp b/LedOK/base/pixbmpshowdialog.cpp index 5920617..6ad57d6 100644 --- a/LedOK/base/pixbmpshowdialog.cpp +++ b/LedOK/base/pixbmpshowdialog.cpp @@ -1,41 +1,41 @@ -#include "pixbmpshowdialog.h" -#include "ui_pixbmpshowdialog.h" -#include -PixbmpShowDialog::PixbmpShowDialog(QWidget *parent) : - BaseDlg(parent), - ui(new Ui::PixbmpShowDialog) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - -} - -PixbmpShowDialog::~PixbmpShowDialog() -{ - delete ui; -} -void PixbmpShowDialog::ResizeByPixmap(int w,int h) -{ - m_iWidth=w; - m_iHeight=h; - int iWidth=w; - int iHeight=h; - if(iWidthresize(iWidth,iHeight); - else { - if(iWidth>iHeight) - this->resize(rect().height()*iWidth/iHeight,rect().height()); - else - this->resize(rect().width(),rect().width()*iHeight/iWidth); - } -} -void PixbmpShowDialog::paintEvent(QPaintEvent * event) -{ - Q_UNUSED(event); - QPainter painter(this); - //painter.eraseRect(rect()); - // painter.scale(m_PixMap.width(), m_PixMap.height()); - QRectF sourceRt(0,0,m_iWidth,m_iHeight); - painter.drawPixmap(rect(), m_PixMap,sourceRt); - -} +#include "pixbmpshowdialog.h" +#include "ui_pixbmpshowdialog.h" +#include +PixbmpShowDialog::PixbmpShowDialog(QWidget *parent) : + BaseDlg(parent), + ui(new Ui::PixbmpShowDialog) +{ + setAttribute(Qt::WA_DeleteOnClose); + ui->setupUi(this); + +} + +PixbmpShowDialog::~PixbmpShowDialog() +{ + delete ui; +} +void PixbmpShowDialog::ResizeByPixmap(int w,int h) +{ + m_iWidth=w; + m_iHeight=h; + int iWidth=w; + int iHeight=h; + if(iWidthresize(iWidth,iHeight); + else { + if(iWidth>iHeight) + this->resize(rect().height()*iWidth/iHeight,rect().height()); + else + this->resize(rect().width(),rect().width()*iHeight/iWidth); + } +} +void PixbmpShowDialog::paintEvent(QPaintEvent * event) +{ + Q_UNUSED(event); + QPainter painter(this); + //painter.eraseRect(rect()); + // painter.scale(m_PixMap.width(), m_PixMap.height()); + QRectF sourceRt(0,0,m_iWidth,m_iHeight); + painter.drawPixmap(rect(), m_PixMap,sourceRt); + +} diff --git a/LedOK/base/pixbmpshowdialog.h b/LedOK/base/pixbmpshowdialog.h index db4b49c..005b545 100644 --- a/LedOK/base/pixbmpshowdialog.h +++ b/LedOK/base/pixbmpshowdialog.h @@ -1,30 +1,30 @@ -#ifndef PIXBMPSHOWDIALOG_H -#define PIXBMPSHOWDIALOG_H - -#include - -namespace Ui { -class PixbmpShowDialog; -} - -class PixbmpShowDialog : public BaseDlg -{ - Q_OBJECT - -public: - explicit PixbmpShowDialog(QWidget *parent = nullptr); - ~PixbmpShowDialog(); - QPixmap m_PixMap; - void ResizeByPixmap(int w,int h); - int m_iWidth; - int m_iHeight; - -public: - virtual void paintEvent(QPaintEvent *); - -private: - Ui::PixbmpShowDialog *ui; - -}; - -#endif // PIXBMPSHOWDIALOG_H +#ifndef PIXBMPSHOWDIALOG_H +#define PIXBMPSHOWDIALOG_H + +#include + +namespace Ui { +class PixbmpShowDialog; +} + +class PixbmpShowDialog : public BaseDlg +{ + Q_OBJECT + +public: + explicit PixbmpShowDialog(QWidget *parent = nullptr); + ~PixbmpShowDialog(); + QPixmap m_PixMap; + void ResizeByPixmap(int w,int h); + int m_iWidth; + int m_iHeight; + +public: + virtual void paintEvent(QPaintEvent *); + +private: + Ui::PixbmpShowDialog *ui; + +}; + +#endif // PIXBMPSHOWDIALOG_H diff --git a/LedOK/base/pixbmpshowdialog.ui b/LedOK/base/pixbmpshowdialog.ui index 8724de0..4e92161 100644 --- a/LedOK/base/pixbmpshowdialog.ui +++ b/LedOK/base/pixbmpshowdialog.ui @@ -1,88 +1,88 @@ - - - PixbmpShowDialog - - - - 0 - 0 - 800 - 600 - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 30 - 20 - - - - - 40 - 30 - - - - X - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - pushButton - clicked() - PixbmpShowDialog - close() - - - 199 - 20 - - - 199 - 149 - - - - - + + + PixbmpShowDialog + + + + 0 + 0 + 800 + 600 + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 30 + 20 + + + + + 40 + 30 + + + + X + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + pushButton + clicked() + PixbmpShowDialog + close() + + + 199 + 20 + + + 199 + 149 + + + + + diff --git a/LedOK/base/qexcel.cpp b/LedOK/base/qexcel.cpp index d90b7ed..5203db5 100644 --- a/LedOK/base/qexcel.cpp +++ b/LedOK/base/qexcel.cpp @@ -1,335 +1,335 @@ -#include -#include -#include -#include - -#include "qexcel.h" -#include "QMessageBox" -#include - -QExcel::QExcel(QString xlsFilePath, QObject *parent) -{ - excel = nullptr; - workBooks = nullptr; - workBook = nullptr; - sheets = nullptr; - sheet = nullptr; - CoInitializeEx(NULL, COINIT_MULTITHREADED); - - excel = new QAxObject("Excel.Application"); - excel->setProperty("Visible", false); - workBooks = excel->querySubObject("Workbooks"); - if(workBooks!=nullptr) - { - QFile file(xlsFilePath); - if (file.exists()) - { - workBooks->dynamicCall("Open(const QString&)", xlsFilePath); - workBook = excel->querySubObject("ActiveWorkBook"); - sheets = workBook->querySubObject("WorkSheets"); - } - m_bSupportExcel=true; - } - else { - QMessageBox::information(nullptr, "Title", tr("no support QExcel"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - m_bSupportExcel=false; - } - -} - -QExcel::~QExcel() -{ - if(excel!=nullptr) - close(); -} - -void QExcel::close() -{ - excel->dynamicCall("Quit()"); - delete sheet; - delete sheets; - delete workBook; - delete workBooks; - delete excel; - - excel = nullptr; - workBooks = nullptr; - workBook = nullptr; - sheets = nullptr; - sheet = nullptr; -} - -QAxObject *QExcel::getWorkBooks() -{ - return workBooks; -} - -QAxObject *QExcel::getWorkBook() -{ - return workBook; -} - -QAxObject *QExcel::getWorkSheets() -{ - return sheets; -} - -QAxObject *QExcel::getWorkSheet() -{ - return sheet; -} - -void QExcel::selectSheet(const QString& sheetName) -{ - sheet = sheets->querySubObject("Item(const QString&)", sheetName); -} - -void QExcel::deleteSheet(const QString& sheetName) -{ - QAxObject * a = sheets->querySubObject("Item(const QString&)", sheetName); - a->dynamicCall("delete"); -} - -void QExcel::deleteSheet(int sheetIndex) -{ - QAxObject * a = sheets->querySubObject("Item(int)", sheetIndex); - a->dynamicCall("delete"); -} - -void QExcel::selectSheet(int sheetIndex) -{ - sheet = sheets->querySubObject("Item(int)", sheetIndex); -} - -void QExcel::setCellString(int row, int column, const QString& value) -{ - QAxObject *range = sheet->querySubObject("Cells(int,int)", row, column); - range->dynamicCall("SetValue(const QString&)", value); -} - -void QExcel::setCellFontBold(int row, int column, bool isBold) -{ - QString cell; - cell.append(QChar(column - 1 + 'A')); - cell.append(QString::number(row)); - - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range = range->querySubObject("Font"); - range->setProperty("Bold", isBold); -} - -void QExcel::setCellFontSize(int row, int column, int size) -{ - QString cell; - cell.append(QChar(column - 1 + 'A')); - cell.append(QString::number(row)); - - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range = range->querySubObject("Font"); - range->setProperty("Size", size); -} - -void QExcel::mergeCells(const QString& cell) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->setProperty("VerticalAlignment", -4108);//xlCenter - range->setProperty("WrapText", true); - range->setProperty("MergeCells", true); -} - -void QExcel::mergeCells(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn) -{ - QString cell; - cell.append(QChar(topLeftColumn - 1 + 'A')); - cell.append(QString::number(topLeftRow)); - cell.append(":"); - cell.append(QChar(bottomRightColumn - 1 + 'A')); - cell.append(QString::number(bottomRightRow)); - - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->setProperty("VerticalAlignment", -4108);//xlCenter - range->setProperty("WrapText", true); - range->setProperty("MergeCells", true); -} - -QVariant QExcel::getCellValue(int row, int column) -{ - QAxObject *range = sheet->querySubObject("Cells(int,int)", row, column); - return range->property("Value"); -} - -void QExcel::save() -{ - workBook->dynamicCall("Save()"); -} - -int QExcel::getSheetsCount() -{ - return sheets->property("Count").toInt(); -} - -QString QExcel::getSheetName() -{ - return sheet->property("Name").toString(); -} - -QString QExcel::getSheetName(int sheetIndex) -{ - QAxObject * a = sheets->querySubObject("Item(int)", sheetIndex); - return a->property("Name").toString(); -} - -void QExcel::getUsedRange(int *topLeftRow, int *topLeftColumn, int *bottomRightRow, int *bottomRightColumn) -{ - QAxObject *usedRange = sheet->querySubObject("UsedRange"); - *topLeftRow = usedRange->property("Row").toInt(); - *topLeftColumn = usedRange->property("Column").toInt(); - - QAxObject *rows = usedRange->querySubObject("Rows"); - *bottomRightRow = *topLeftRow + rows->property("Count").toInt() - 1; - - QAxObject *columns = usedRange->querySubObject("Columns"); - *bottomRightColumn = *topLeftColumn + columns->property("Count").toInt() - 1; -} - -void QExcel::setColumnWidth(int column, int width) -{ - QString columnName; - columnName.append(QChar(column - 1 + 'A')); - columnName.append(":"); - columnName.append(QChar(column - 1 + 'A')); - - QAxObject * col = sheet->querySubObject("Columns(const QString&)", columnName); - col->setProperty("ColumnWidth", width); -} - -void QExcel::setCellTextCenter(int row, int column) -{ - QString cell; - cell.append(QChar(column - 1 + 'A')); - cell.append(QString::number(row)); - - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->setProperty("HorizontalAlignment", -4108);//xlCenter -} - -void QExcel::setCellTextWrap(int row, int column, bool isWrap) -{ - QString cell; - cell.append(QChar(column - 1 + 'A')); - cell.append(QString::number(row)); - - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->setProperty("WrapText", isWrap); -} - -void QExcel::setAutoFitRow(int row) -{ - QString rowsName; - rowsName.append(QString::number(row)); - rowsName.append(":"); - rowsName.append(QString::number(row)); - - QAxObject * rows = sheet->querySubObject("Rows(const QString &)", rowsName); - rows->dynamicCall("AutoFit()"); -} - -void QExcel::insertSheet(QString sheetName) -{ - sheets->querySubObject("Add()"); - QAxObject * a = sheets->querySubObject("Item(int)", 1); - a->setProperty("Name", sheetName); -} - -void QExcel::mergeSerialSameCellsInAColumn(int column, int topRow) -{ - int a,b,c,rowsCount; - getUsedRange(&a, &b, &rowsCount, &c); - - int aMergeStart = topRow, aMergeEnd = topRow + 1; - - QString value; - while(aMergeEnd <= rowsCount) - { - value = getCellValue(aMergeStart, column).toString(); - while(value == getCellValue(aMergeEnd, column).toString()) - { - clearCell(aMergeEnd, column); - aMergeEnd++; - } - aMergeEnd--; - mergeCells(aMergeStart, column, aMergeEnd, column); - - aMergeStart = aMergeEnd + 1; - aMergeEnd = aMergeStart + 1; - } -} - -void QExcel::clearCell(int row, int column) -{ - QString cell; - cell.append(QChar(column - 1 + 'A')); - cell.append(QString::number(row)); - - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->dynamicCall("ClearContents()"); -} - -void QExcel::clearCell(const QString& cell) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->dynamicCall("ClearContents()"); -} - -int QExcel::getUsedRowsCount() -{ - QAxObject *usedRange = sheet->querySubObject("UsedRange"); - int topRow = usedRange->property("Row").toInt(); - QAxObject *rows = usedRange->querySubObject("Rows"); - int bottomRow = topRow + rows->property("Count").toInt() - 1; - return bottomRow; -} - -void QExcel::setCellString(const QString& cell, const QString& value) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->dynamicCall("SetValue(const QString&)", value); -} - -void QExcel::setCellFontSize(const QString &cell, int size) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range = range->querySubObject("Font"); - range->setProperty("Size", size); -} - -void QExcel::setCellTextCenter(const QString &cell) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->setProperty("HorizontalAlignment", -4108);//xlCenter -} - -void QExcel::setCellFontBold(const QString &cell, bool isBold) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range = range->querySubObject("Font"); - range->setProperty("Bold", isBold); -} - -void QExcel::setCellTextWrap(const QString &cell, bool isWrap) -{ - QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); - range->setProperty("WrapText", isWrap); -} - -void QExcel::setRowHeight(int row, int height) -{ - QString rowsName; - rowsName.append(QString::number(row)); - rowsName.append(":"); - rowsName.append(QString::number(row)); - - QAxObject * r = sheet->querySubObject("Rows(const QString &)", rowsName); - r->setProperty("RowHeight", height); -} +#include +#include +#include +#include + +#include "qexcel.h" +#include "QMessageBox" +#include + +QExcel::QExcel(QString xlsFilePath, QObject *parent) +{ + excel = nullptr; + workBooks = nullptr; + workBook = nullptr; + sheets = nullptr; + sheet = nullptr; + CoInitializeEx(NULL, COINIT_MULTITHREADED); + + excel = new QAxObject("Excel.Application"); + excel->setProperty("Visible", false); + workBooks = excel->querySubObject("Workbooks"); + if(workBooks!=nullptr) + { + QFile file(xlsFilePath); + if (file.exists()) + { + workBooks->dynamicCall("Open(const QString&)", xlsFilePath); + workBook = excel->querySubObject("ActiveWorkBook"); + sheets = workBook->querySubObject("WorkSheets"); + } + m_bSupportExcel=true; + } + else { + QMessageBox::information(nullptr, "Title", tr("no support QExcel"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + m_bSupportExcel=false; + } + +} + +QExcel::~QExcel() +{ + if(excel!=nullptr) + close(); +} + +void QExcel::close() +{ + excel->dynamicCall("Quit()"); + delete sheet; + delete sheets; + delete workBook; + delete workBooks; + delete excel; + + excel = nullptr; + workBooks = nullptr; + workBook = nullptr; + sheets = nullptr; + sheet = nullptr; +} + +QAxObject *QExcel::getWorkBooks() +{ + return workBooks; +} + +QAxObject *QExcel::getWorkBook() +{ + return workBook; +} + +QAxObject *QExcel::getWorkSheets() +{ + return sheets; +} + +QAxObject *QExcel::getWorkSheet() +{ + return sheet; +} + +void QExcel::selectSheet(const QString& sheetName) +{ + sheet = sheets->querySubObject("Item(const QString&)", sheetName); +} + +void QExcel::deleteSheet(const QString& sheetName) +{ + QAxObject * a = sheets->querySubObject("Item(const QString&)", sheetName); + a->dynamicCall("delete"); +} + +void QExcel::deleteSheet(int sheetIndex) +{ + QAxObject * a = sheets->querySubObject("Item(int)", sheetIndex); + a->dynamicCall("delete"); +} + +void QExcel::selectSheet(int sheetIndex) +{ + sheet = sheets->querySubObject("Item(int)", sheetIndex); +} + +void QExcel::setCellString(int row, int column, const QString& value) +{ + QAxObject *range = sheet->querySubObject("Cells(int,int)", row, column); + range->dynamicCall("SetValue(const QString&)", value); +} + +void QExcel::setCellFontBold(int row, int column, bool isBold) +{ + QString cell; + cell.append(QChar(column - 1 + 'A')); + cell.append(QString::number(row)); + + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range = range->querySubObject("Font"); + range->setProperty("Bold", isBold); +} + +void QExcel::setCellFontSize(int row, int column, int size) +{ + QString cell; + cell.append(QChar(column - 1 + 'A')); + cell.append(QString::number(row)); + + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range = range->querySubObject("Font"); + range->setProperty("Size", size); +} + +void QExcel::mergeCells(const QString& cell) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->setProperty("VerticalAlignment", -4108);//xlCenter + range->setProperty("WrapText", true); + range->setProperty("MergeCells", true); +} + +void QExcel::mergeCells(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn) +{ + QString cell; + cell.append(QChar(topLeftColumn - 1 + 'A')); + cell.append(QString::number(topLeftRow)); + cell.append(":"); + cell.append(QChar(bottomRightColumn - 1 + 'A')); + cell.append(QString::number(bottomRightRow)); + + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->setProperty("VerticalAlignment", -4108);//xlCenter + range->setProperty("WrapText", true); + range->setProperty("MergeCells", true); +} + +QVariant QExcel::getCellValue(int row, int column) +{ + QAxObject *range = sheet->querySubObject("Cells(int,int)", row, column); + return range->property("Value"); +} + +void QExcel::save() +{ + workBook->dynamicCall("Save()"); +} + +int QExcel::getSheetsCount() +{ + return sheets->property("Count").toInt(); +} + +QString QExcel::getSheetName() +{ + return sheet->property("Name").toString(); +} + +QString QExcel::getSheetName(int sheetIndex) +{ + QAxObject * a = sheets->querySubObject("Item(int)", sheetIndex); + return a->property("Name").toString(); +} + +void QExcel::getUsedRange(int *topLeftRow, int *topLeftColumn, int *bottomRightRow, int *bottomRightColumn) +{ + QAxObject *usedRange = sheet->querySubObject("UsedRange"); + *topLeftRow = usedRange->property("Row").toInt(); + *topLeftColumn = usedRange->property("Column").toInt(); + + QAxObject *rows = usedRange->querySubObject("Rows"); + *bottomRightRow = *topLeftRow + rows->property("Count").toInt() - 1; + + QAxObject *columns = usedRange->querySubObject("Columns"); + *bottomRightColumn = *topLeftColumn + columns->property("Count").toInt() - 1; +} + +void QExcel::setColumnWidth(int column, int width) +{ + QString columnName; + columnName.append(QChar(column - 1 + 'A')); + columnName.append(":"); + columnName.append(QChar(column - 1 + 'A')); + + QAxObject * col = sheet->querySubObject("Columns(const QString&)", columnName); + col->setProperty("ColumnWidth", width); +} + +void QExcel::setCellTextCenter(int row, int column) +{ + QString cell; + cell.append(QChar(column - 1 + 'A')); + cell.append(QString::number(row)); + + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->setProperty("HorizontalAlignment", -4108);//xlCenter +} + +void QExcel::setCellTextWrap(int row, int column, bool isWrap) +{ + QString cell; + cell.append(QChar(column - 1 + 'A')); + cell.append(QString::number(row)); + + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->setProperty("WrapText", isWrap); +} + +void QExcel::setAutoFitRow(int row) +{ + QString rowsName; + rowsName.append(QString::number(row)); + rowsName.append(":"); + rowsName.append(QString::number(row)); + + QAxObject * rows = sheet->querySubObject("Rows(const QString &)", rowsName); + rows->dynamicCall("AutoFit()"); +} + +void QExcel::insertSheet(QString sheetName) +{ + sheets->querySubObject("Add()"); + QAxObject * a = sheets->querySubObject("Item(int)", 1); + a->setProperty("Name", sheetName); +} + +void QExcel::mergeSerialSameCellsInAColumn(int column, int topRow) +{ + int a,b,c,rowsCount; + getUsedRange(&a, &b, &rowsCount, &c); + + int aMergeStart = topRow, aMergeEnd = topRow + 1; + + QString value; + while(aMergeEnd <= rowsCount) + { + value = getCellValue(aMergeStart, column).toString(); + while(value == getCellValue(aMergeEnd, column).toString()) + { + clearCell(aMergeEnd, column); + aMergeEnd++; + } + aMergeEnd--; + mergeCells(aMergeStart, column, aMergeEnd, column); + + aMergeStart = aMergeEnd + 1; + aMergeEnd = aMergeStart + 1; + } +} + +void QExcel::clearCell(int row, int column) +{ + QString cell; + cell.append(QChar(column - 1 + 'A')); + cell.append(QString::number(row)); + + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->dynamicCall("ClearContents()"); +} + +void QExcel::clearCell(const QString& cell) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->dynamicCall("ClearContents()"); +} + +int QExcel::getUsedRowsCount() +{ + QAxObject *usedRange = sheet->querySubObject("UsedRange"); + int topRow = usedRange->property("Row").toInt(); + QAxObject *rows = usedRange->querySubObject("Rows"); + int bottomRow = topRow + rows->property("Count").toInt() - 1; + return bottomRow; +} + +void QExcel::setCellString(const QString& cell, const QString& value) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->dynamicCall("SetValue(const QString&)", value); +} + +void QExcel::setCellFontSize(const QString &cell, int size) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range = range->querySubObject("Font"); + range->setProperty("Size", size); +} + +void QExcel::setCellTextCenter(const QString &cell) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->setProperty("HorizontalAlignment", -4108);//xlCenter +} + +void QExcel::setCellFontBold(const QString &cell, bool isBold) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range = range->querySubObject("Font"); + range->setProperty("Bold", isBold); +} + +void QExcel::setCellTextWrap(const QString &cell, bool isWrap) +{ + QAxObject *range = sheet->querySubObject("Range(const QString&)", cell); + range->setProperty("WrapText", isWrap); +} + +void QExcel::setRowHeight(int row, int height) +{ + QString rowsName; + rowsName.append(QString::number(row)); + rowsName.append(":"); + rowsName.append(QString::number(row)); + + QAxObject * r = sheet->querySubObject("Rows(const QString &)", rowsName); + r->setProperty("RowHeight", height); +} diff --git a/LedOK/base/qexcel.h b/LedOK/base/qexcel.h index 02b5551..df8df12 100644 --- a/LedOK/base/qexcel.h +++ b/LedOK/base/qexcel.h @@ -1,82 +1,82 @@ -#ifndef QEXCEL_H -#define QEXCEL_H - -#include -#include - -class QAxObject; - -class QExcel : public QObject -{ -public: - QExcel(QString xlsFilePath, QObject *parent = 0); - ~QExcel(); - -public: - QAxObject * getWorkBooks(); - QAxObject * getWorkBook(); - QAxObject * getWorkSheets(); - QAxObject * getWorkSheet(); - int m_bSupportExcel=false; - -public: - /**************************************************************************/ - /* 工作表 */ - /**************************************************************************/ - void selectSheet(const QString& sheetName); - //sheetIndex 起始于 1 - void selectSheet(int sheetIndex); - void deleteSheet(const QString& sheetName); - void deleteSheet(int sheetIndex); - void insertSheet(QString sheetName); - int getSheetsCount(); - //在 selectSheet() 之后才可调用 - QString getSheetName(); - QString getSheetName(int sheetIndex); - - /**************************************************************************/ - /* 单元格 */ - /**************************************************************************/ - void setCellString(int row, int column, const QString& value); - //cell 例如 "A7" - void setCellString(const QString& cell, const QString& value); - //range 例如 "A5:C7" - void mergeCells(const QString& range); - void mergeCells(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn); - QVariant getCellValue(int row, int column); - void clearCell(int row, int column); - void clearCell(const QString& cell); - - /**************************************************************************/ - /* 布局格式 */ - /**************************************************************************/ - void getUsedRange(int *topLeftRow, int *topLeftColumn, int *bottomRightRow, int *bottomRightColumn); - void setColumnWidth(int column, int width); - void setRowHeight(int row, int height); - void setCellTextCenter(int row, int column); - void setCellTextCenter(const QString& cell); - void setCellTextWrap(int row, int column, bool isWrap); - void setCellTextWrap(const QString& cell, bool isWrap); - void setAutoFitRow(int row); - void mergeSerialSameCellsInAColumn(int column, int topRow); - int getUsedRowsCount(); - void setCellFontBold(int row, int column, bool isBold); - void setCellFontBold(const QString& cell, bool isBold); - void setCellFontSize(int row, int column, int size); - void setCellFontSize(const QString& cell, int size); - - /**************************************************************************/ - /* 文件 */ - /**************************************************************************/ - void save(); - void close(); - -private: - QAxObject * excel; - QAxObject * workBooks; - QAxObject * workBook; - QAxObject * sheets; - QAxObject * sheet; -}; - -#endif +#ifndef QEXCEL_H +#define QEXCEL_H + +#include +#include + +class QAxObject; + +class QExcel : public QObject +{ +public: + QExcel(QString xlsFilePath, QObject *parent = 0); + ~QExcel(); + +public: + QAxObject * getWorkBooks(); + QAxObject * getWorkBook(); + QAxObject * getWorkSheets(); + QAxObject * getWorkSheet(); + int m_bSupportExcel=false; + +public: + /**************************************************************************/ + /* 工作表 */ + /**************************************************************************/ + void selectSheet(const QString& sheetName); + //sheetIndex 起始于 1 + void selectSheet(int sheetIndex); + void deleteSheet(const QString& sheetName); + void deleteSheet(int sheetIndex); + void insertSheet(QString sheetName); + int getSheetsCount(); + //在 selectSheet() 之后才可调用 + QString getSheetName(); + QString getSheetName(int sheetIndex); + + /**************************************************************************/ + /* 单元格 */ + /**************************************************************************/ + void setCellString(int row, int column, const QString& value); + //cell 例如 "A7" + void setCellString(const QString& cell, const QString& value); + //range 例如 "A5:C7" + void mergeCells(const QString& range); + void mergeCells(int topLeftRow, int topLeftColumn, int bottomRightRow, int bottomRightColumn); + QVariant getCellValue(int row, int column); + void clearCell(int row, int column); + void clearCell(const QString& cell); + + /**************************************************************************/ + /* 布局格式 */ + /**************************************************************************/ + void getUsedRange(int *topLeftRow, int *topLeftColumn, int *bottomRightRow, int *bottomRightColumn); + void setColumnWidth(int column, int width); + void setRowHeight(int row, int height); + void setCellTextCenter(int row, int column); + void setCellTextCenter(const QString& cell); + void setCellTextWrap(int row, int column, bool isWrap); + void setCellTextWrap(const QString& cell, bool isWrap); + void setAutoFitRow(int row); + void mergeSerialSameCellsInAColumn(int column, int topRow); + int getUsedRowsCount(); + void setCellFontBold(int row, int column, bool isBold); + void setCellFontBold(const QString& cell, bool isBold); + void setCellFontSize(int row, int column, int size); + void setCellFontSize(const QString& cell, int size); + + /**************************************************************************/ + /* 文件 */ + /**************************************************************************/ + void save(); + void close(); + +private: + QAxObject * excel; + QAxObject * workBooks; + QAxObject * workBook; + QAxObject * sheets; + QAxObject * sheet; +}; + +#endif diff --git a/LedOK/base/qiplineedit.cpp b/LedOK/base/qiplineedit.cpp index 7b28763..ad0c89c 100644 --- a/LedOK/base/qiplineedit.cpp +++ b/LedOK/base/qiplineedit.cpp @@ -1,285 +1,285 @@ -/* - * 此类的封装参考了:博客网址:http://blog.csdn.net/u011417605,并在此基础上进行修改 - * 1.连续输入 - * 2.连续删除 - * 3.任意位置插入 - * 4.自适应大小变化 - * 5.正则匹配,每个值不大于255.设置IP值时,有正则验证是否是IP格式 - * 实现方法:使用一个大的QLineEdit嵌套四个小的QLineEdit,中间的点是使用paintEvent画出来的。操作是使用eventFilter来进行分发实现的 - * 修改: - * 用QWidget替换原先的__super - * 修改构造函数中的正则匹配 - * 修改小圆点位置和大小 - * 两个QLineEdit之间的空隙,在绘制小圆点之前,把空气用白色背景填充 - * 修改样式表加边框 - * 当输入类似192时,焦点自动跳转到下一个QLineEdit出 - * 修改text()的输出,使输出由原来的1921680127变为192.168.0.127 - **/ - -#include "qiplineedit.h" -#include -#include -#include -#include -#define SPACE 5 - -QIPLineEdit::QIPLineEdit(QWidget *parent) : QLineEdit(parent) { - QRegExp rx("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"); - pHBox = new QHBoxLayout(this); - pHBox->setSpacing(SPACE); - pHBox->setContentsMargins(0, 0, 0, 0); - for(int i = 0; i < 4; i++) { - m_lineEidt[i] = new QLineEdit(this); - m_lineEidt[i]->setFrame(false); - m_lineEidt[i]->setMaxLength(3); - m_lineEidt[i]->setAlignment(Qt::AlignCenter); - m_lineEidt[i]->installEventFilter(this); - m_lineEidt[i]->setValidator(new QRegExpValidator(rx, this)); - m_lineEidt[i]->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - switch (i) - { - case 0: - m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(0, 0, 0);\n" - "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-right: 0px;\n" - "border-right-color: rgbl(255, 255, 255,0);" "border-radius:0px")); - break; - case 1: - m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(255, 255, 255);\n" - "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-right: 0px;\n" "border-left: 0px;\n" - "border-right-color: rgb(255, 255, 255);" "border-radius:0px")); - break; - case 2: - m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(255, 255, 255);\n" - "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-right: 0px;\n" "border-left: 0px;\n" - "border-right-color: rgb(255, 255, 255);" "border-radius:0px")); - break; - case 3: - m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(255, 255, 255);\n" - "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-left: 0px;\n" - "border-right-color: rgb(0, 0, 0);" "border-radius:0px")); - break; - default: - break; - } - pHBox->addWidget(m_lineEidt[i]); - } - this->setReadOnly(true); - m_Color=Qt::white; - connect(m_lineEidt[0],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit1TextChanged(const QString &))); - connect(m_lineEidt[1],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit2TextChanged(const QString &))); - connect(m_lineEidt[2],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit3TextChanged(const QString &))); - connect(m_lineEidt[3],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit4TextChanged(const QString &))); -} - -QIPLineEdit::~QIPLineEdit() { - m_lineEidt[0]->deleteLater(); - m_lineEidt[1]->deleteLater(); - m_lineEidt[2]->deleteLater(); - m_lineEidt[3]->deleteLater(); - pHBox->deleteLater(); -} -void QIPLineEdit::MySetColor(QColor cr) -{ - m_Color=cr; -} -void QIPLineEdit::OnLineEdit1TextChanged(const QString & strtemp) -{ - if(strtemp.right(1)=="."||strtemp.right(1)=="。") - { - m_lineEidt[0]->setText(strtemp.left(strtemp.length()-1)); - m_lineEidt[0 + 1]->setFocus(); - m_lineEidt[0 + 1]->setCursorPosition(0); - } -} -void QIPLineEdit::OnLineEdit2TextChanged(const QString & strtemp) -{ - if(strtemp.right(1)=="."||strtemp.right(1)=="。") - { - m_lineEidt[1]->setText(strtemp.left(strtemp.length()-1)); - m_lineEidt[1 + 1]->setFocus(); - m_lineEidt[1 + 1]->setCursorPosition(0); - } -} -void QIPLineEdit::OnLineEdit3TextChanged(const QString & strtemp) -{ - if(strtemp.right(1)=="."||strtemp.right(1)=="。") - { - m_lineEidt[2]->setText(strtemp.left(strtemp.length()-1)); - m_lineEidt[2 + 1]->setFocus(); - m_lineEidt[2 + 1]->setCursorPosition(0); - } -} -void QIPLineEdit::OnLineEdit4TextChanged(const QString & strtemp) -{ - if(strtemp.right(1)=="."||strtemp.right(1)=="。") - { - m_lineEidt[3]->setText(strtemp.left(strtemp.length()-1)); - } -} -void QIPLineEdit::paintEvent(QPaintEvent *event) { - QWidget::paintEvent(event); - QPainter painter(this); - QBrush brush; - int width = 0; - for(int i = 0; i < 3; i++) { - brush.setStyle(Qt::BrushStyle::SolidPattern); - //将两个lineEdit之间的空隙绘制成白色 - brush.setColor(m_Color); - painter.setPen(m_Color); - painter.setBrush(brush); - painter.drawRect(m_lineEidt[i]->x() + m_lineEidt[i]->width(), m_lineEidt[i]->y(), SPACE, height()); - //绘制空隙的边框 - painter.setPen(Qt::black); - painter.drawLine(0, 0, this->width(), 0); - painter.drawLine(0, this->height() - 1, this->width(), this->height() - 1); - //绘制小黑点 - brush.setColor(Qt::black); - painter.setPen(QPen()); - painter.setBrush(brush); - width += m_lineEidt[i]->width() + (i == 0 ? 2 : SPACE);//布局的间隔 - painter.drawEllipse(width, height() / 2 + 4, 1, 1); - } -} - -int QIPLineEdit::getIndex(QLineEdit *pEdit){ - int index = -1; - for(int i = 0; i < 4; i++) if(pEdit == m_lineEidt[i]) index = i; - return index; -} - -bool QIPLineEdit::eventFilter(QObject *obj, QEvent *ev) { - if(children().contains(obj) && QEvent::KeyPress == ev->type()) { - QKeyEvent *keyEvent = dynamic_cast(ev); - QLineEdit *pEdit = qobject_cast(obj); - switch (keyEvent->key()) { - case Qt::Key_0: - case Qt::Key_1: - case Qt::Key_2: - case Qt::Key_3: - case Qt::Key_4: - case Qt::Key_5: - case Qt::Key_6: - case Qt::Key_7: - case Qt::Key_8: - case Qt::Key_9: - { - QString strText = pEdit->text(); - if (pEdit->selectedText().length()) - { - pEdit->text().replace(pEdit->selectedText(), QChar(keyEvent->key())); - } - else if (strText.length() == 2 || (strText.length() < 2 && strText.toInt() * 10 > 255)) - { - int index = getIndex(pEdit); - if (index != -1 && index != 3) - { - m_lineEidt[index + 1]->setFocus(); - m_lineEidt[index + 1]->selectAll(); - } - } - else if (strText.length() == 2 && strText.toInt() * 10 < 255) - { - if (Qt::Key_0 == keyEvent->key() && strText.toInt()) - { - pEdit->setText(strText.insert(pEdit->cursorPosition(), QChar(Qt::Key_0))); - } - } - return QWidget::eventFilter(obj, ev); - } - break; - case Qt::Key_Backspace: - { - QString strText = pEdit->text(); - if (!strText.length() || (strText.length() && !pEdit->cursorPosition())) - { - int index = getIndex(pEdit); - if (index != -1 && index != 0) - { - m_lineEidt[index - 1]->setFocus(); - int length = m_lineEidt[index - 1]->text().length(); - m_lineEidt[index - 1]->setCursorPosition(length ? length : 0); - } - } - return QWidget::eventFilter(obj, ev); - } - break; - case Qt::Key_Left: - { - if (!pEdit->cursorPosition()) - { - int index = getIndex(pEdit); - if (index != -1 && index != 0) - { - m_lineEidt[index - 1]->setFocus(); - int length = m_lineEidt[index - 1]->text().length(); - m_lineEidt[index - 1]->setCursorPosition(length ? length : 0); - } - } - return QWidget::eventFilter(obj, ev); - } - break; - case Qt::Key_Right: - { - if (pEdit->cursorPosition() == pEdit->text().length()) - { - int index = getIndex(pEdit); - if (index != -1 && index != 3) - { - m_lineEidt[index + 1]->setFocus(); - m_lineEidt[index + 1]->setCursorPosition(0); - } - } - return QWidget::eventFilter(obj, ev); - } - break; - default: - break; - } - } - return false; -} - -void QIPLineEdit::setText(const QString &strIP) -{ - if (!isTextValid(strIP)) - { - QMessageBox::warning(this, "Attention", "Your IP Address is Invalid!["+strIP+"]", QMessageBox::StandardButton::Ok); - return; - } - else - { - int i = 0; - QStringList ipList = strIP.split("."); - foreach (QString ip, ipList) - { - m_lineEidt[i]->setText(ip); - i++; - } - } -} - -bool QIPLineEdit::isTextValid(const QString &strIP) { - QRegExp rx2("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); - return rx2.exactMatch(strIP); -} - -QString QIPLineEdit::text() const -{ - QString strIP; - for (int i = 0; i < 4; i++) - { - strIP.append(m_lineEidt[i]->text()); - if (i < 3) - { - strIP.append("."); - } - } - return strIP; -} -void QIPLineEdit::MyClear() -{ - m_lineEidt[0]->clear(); - m_lineEidt[1]->clear(); - m_lineEidt[2]->clear(); - m_lineEidt[3]->clear(); -} +/* + * 此类的封装参考了:博客网址:http://blog.csdn.net/u011417605,并在此基础上进行修改 + * 1.连续输入 + * 2.连续删除 + * 3.任意位置插入 + * 4.自适应大小变化 + * 5.正则匹配,每个值不大于255.设置IP值时,有正则验证是否是IP格式 + * 实现方法:使用一个大的QLineEdit嵌套四个小的QLineEdit,中间的点是使用paintEvent画出来的。操作是使用eventFilter来进行分发实现的 + * 修改: + * 用QWidget替换原先的__super + * 修改构造函数中的正则匹配 + * 修改小圆点位置和大小 + * 两个QLineEdit之间的空隙,在绘制小圆点之前,把空气用白色背景填充 + * 修改样式表加边框 + * 当输入类似192时,焦点自动跳转到下一个QLineEdit出 + * 修改text()的输出,使输出由原来的1921680127变为192.168.0.127 + **/ + +#include "qiplineedit.h" +#include +#include +#include +#include +#define SPACE 5 + +QIPLineEdit::QIPLineEdit(QWidget *parent) : QLineEdit(parent) { + QRegExp rx("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"); + pHBox = new QHBoxLayout(this); + pHBox->setSpacing(SPACE); + pHBox->setContentsMargins(0, 0, 0, 0); + for(int i = 0; i < 4; i++) { + m_lineEidt[i] = new QLineEdit(this); + m_lineEidt[i]->setFrame(false); + m_lineEidt[i]->setMaxLength(3); + m_lineEidt[i]->setAlignment(Qt::AlignCenter); + m_lineEidt[i]->installEventFilter(this); + m_lineEidt[i]->setValidator(new QRegExpValidator(rx, this)); + m_lineEidt[i]->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + switch (i) + { + case 0: + m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(0, 0, 0);\n" + "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-right: 0px;\n" + "border-right-color: rgbl(255, 255, 255,0);" "border-radius:0px")); + break; + case 1: + m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(255, 255, 255);\n" + "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-right: 0px;\n" "border-left: 0px;\n" + "border-right-color: rgb(255, 255, 255);" "border-radius:0px")); + break; + case 2: + m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(255, 255, 255);\n" + "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-right: 0px;\n" "border-left: 0px;\n" + "border-right-color: rgb(255, 255, 255);" "border-radius:0px")); + break; + case 3: + m_lineEidt[i]->setStyleSheet(QLatin1String( "border:1px solid #536874;\n" "border-left-color: rgb(255, 255, 255);\n" + "border-top-color: rgb(0, 0, 0);\n" "border-bottom-color: rgb(0, 0, 0);\n" "border-left: 0px;\n" + "border-right-color: rgb(0, 0, 0);" "border-radius:0px")); + break; + default: + break; + } + pHBox->addWidget(m_lineEidt[i]); + } + this->setReadOnly(true); + m_Color=Qt::white; + connect(m_lineEidt[0],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit1TextChanged(const QString &))); + connect(m_lineEidt[1],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit2TextChanged(const QString &))); + connect(m_lineEidt[2],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit3TextChanged(const QString &))); + connect(m_lineEidt[3],SIGNAL(textChanged(const QString &)),this,SLOT(OnLineEdit4TextChanged(const QString &))); +} + +QIPLineEdit::~QIPLineEdit() { + m_lineEidt[0]->deleteLater(); + m_lineEidt[1]->deleteLater(); + m_lineEidt[2]->deleteLater(); + m_lineEidt[3]->deleteLater(); + pHBox->deleteLater(); +} +void QIPLineEdit::MySetColor(QColor cr) +{ + m_Color=cr; +} +void QIPLineEdit::OnLineEdit1TextChanged(const QString & strtemp) +{ + if(strtemp.right(1)=="."||strtemp.right(1)=="。") + { + m_lineEidt[0]->setText(strtemp.left(strtemp.length()-1)); + m_lineEidt[0 + 1]->setFocus(); + m_lineEidt[0 + 1]->setCursorPosition(0); + } +} +void QIPLineEdit::OnLineEdit2TextChanged(const QString & strtemp) +{ + if(strtemp.right(1)=="."||strtemp.right(1)=="。") + { + m_lineEidt[1]->setText(strtemp.left(strtemp.length()-1)); + m_lineEidt[1 + 1]->setFocus(); + m_lineEidt[1 + 1]->setCursorPosition(0); + } +} +void QIPLineEdit::OnLineEdit3TextChanged(const QString & strtemp) +{ + if(strtemp.right(1)=="."||strtemp.right(1)=="。") + { + m_lineEidt[2]->setText(strtemp.left(strtemp.length()-1)); + m_lineEidt[2 + 1]->setFocus(); + m_lineEidt[2 + 1]->setCursorPosition(0); + } +} +void QIPLineEdit::OnLineEdit4TextChanged(const QString & strtemp) +{ + if(strtemp.right(1)=="."||strtemp.right(1)=="。") + { + m_lineEidt[3]->setText(strtemp.left(strtemp.length()-1)); + } +} +void QIPLineEdit::paintEvent(QPaintEvent *event) { + QWidget::paintEvent(event); + QPainter painter(this); + QBrush brush; + int width = 0; + for(int i = 0; i < 3; i++) { + brush.setStyle(Qt::BrushStyle::SolidPattern); + //将两个lineEdit之间的空隙绘制成白色 + brush.setColor(m_Color); + painter.setPen(m_Color); + painter.setBrush(brush); + painter.drawRect(m_lineEidt[i]->x() + m_lineEidt[i]->width(), m_lineEidt[i]->y(), SPACE, height()); + //绘制空隙的边框 + painter.setPen(Qt::black); + painter.drawLine(0, 0, this->width(), 0); + painter.drawLine(0, this->height() - 1, this->width(), this->height() - 1); + //绘制小黑点 + brush.setColor(Qt::black); + painter.setPen(QPen()); + painter.setBrush(brush); + width += m_lineEidt[i]->width() + (i == 0 ? 2 : SPACE);//布局的间隔 + painter.drawEllipse(width, height() / 2 + 4, 1, 1); + } +} + +int QIPLineEdit::getIndex(QLineEdit *pEdit){ + int index = -1; + for(int i = 0; i < 4; i++) if(pEdit == m_lineEidt[i]) index = i; + return index; +} + +bool QIPLineEdit::eventFilter(QObject *obj, QEvent *ev) { + if(children().contains(obj) && QEvent::KeyPress == ev->type()) { + QKeyEvent *keyEvent = dynamic_cast(ev); + QLineEdit *pEdit = qobject_cast(obj); + switch (keyEvent->key()) { + case Qt::Key_0: + case Qt::Key_1: + case Qt::Key_2: + case Qt::Key_3: + case Qt::Key_4: + case Qt::Key_5: + case Qt::Key_6: + case Qt::Key_7: + case Qt::Key_8: + case Qt::Key_9: + { + QString strText = pEdit->text(); + if (pEdit->selectedText().length()) + { + pEdit->text().replace(pEdit->selectedText(), QChar(keyEvent->key())); + } + else if (strText.length() == 2 || (strText.length() < 2 && strText.toInt() * 10 > 255)) + { + int index = getIndex(pEdit); + if (index != -1 && index != 3) + { + m_lineEidt[index + 1]->setFocus(); + m_lineEidt[index + 1]->selectAll(); + } + } + else if (strText.length() == 2 && strText.toInt() * 10 < 255) + { + if (Qt::Key_0 == keyEvent->key() && strText.toInt()) + { + pEdit->setText(strText.insert(pEdit->cursorPosition(), QChar(Qt::Key_0))); + } + } + return QWidget::eventFilter(obj, ev); + } + break; + case Qt::Key_Backspace: + { + QString strText = pEdit->text(); + if (!strText.length() || (strText.length() && !pEdit->cursorPosition())) + { + int index = getIndex(pEdit); + if (index != -1 && index != 0) + { + m_lineEidt[index - 1]->setFocus(); + int length = m_lineEidt[index - 1]->text().length(); + m_lineEidt[index - 1]->setCursorPosition(length ? length : 0); + } + } + return QWidget::eventFilter(obj, ev); + } + break; + case Qt::Key_Left: + { + if (!pEdit->cursorPosition()) + { + int index = getIndex(pEdit); + if (index != -1 && index != 0) + { + m_lineEidt[index - 1]->setFocus(); + int length = m_lineEidt[index - 1]->text().length(); + m_lineEidt[index - 1]->setCursorPosition(length ? length : 0); + } + } + return QWidget::eventFilter(obj, ev); + } + break; + case Qt::Key_Right: + { + if (pEdit->cursorPosition() == pEdit->text().length()) + { + int index = getIndex(pEdit); + if (index != -1 && index != 3) + { + m_lineEidt[index + 1]->setFocus(); + m_lineEidt[index + 1]->setCursorPosition(0); + } + } + return QWidget::eventFilter(obj, ev); + } + break; + default: + break; + } + } + return false; +} + +void QIPLineEdit::setText(const QString &strIP) +{ + if (!isTextValid(strIP)) + { + QMessageBox::warning(this, "Attention", "Your IP Address is Invalid!["+strIP+"]", QMessageBox::StandardButton::Ok); + return; + } + else + { + int i = 0; + QStringList ipList = strIP.split("."); + foreach (QString ip, ipList) + { + m_lineEidt[i]->setText(ip); + i++; + } + } +} + +bool QIPLineEdit::isTextValid(const QString &strIP) { + QRegExp rx2("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + return rx2.exactMatch(strIP); +} + +QString QIPLineEdit::text() const +{ + QString strIP; + for (int i = 0; i < 4; i++) + { + strIP.append(m_lineEidt[i]->text()); + if (i < 3) + { + strIP.append("."); + } + } + return strIP; +} +void QIPLineEdit::MyClear() +{ + m_lineEidt[0]->clear(); + m_lineEidt[1]->clear(); + m_lineEidt[2]->clear(); + m_lineEidt[3]->clear(); +} diff --git a/LedOK/base/qiplineedit.h b/LedOK/base/qiplineedit.h index d53eaa6..083eeb5 100644 --- a/LedOK/base/qiplineedit.h +++ b/LedOK/base/qiplineedit.h @@ -1,37 +1,37 @@ -#ifndef QIPLINEEDIT_H -#define QIPLINEEDIT_H - -#include -#include -#include - -class QIPLineEdit : public QLineEdit { - Q_OBJECT -public: - QIPLineEdit(QWidget *parent = nullptr); - ~QIPLineEdit(); - - void setText(const QString &strIP); - QString text() const; - void MyClear(); - void MySetColor(QColor cr); - -protected: - void paintEvent(QPaintEvent *event); - bool eventFilter(QObject *obj, QEvent *ev); - - int getIndex(QLineEdit *pEdit); - bool isTextValid(const QString &strIP); -protected slots: - void OnLineEdit1TextChanged(const QString & strtemp); - void OnLineEdit2TextChanged(const QString & strtemp); - void OnLineEdit3TextChanged(const QString & strtemp); - void OnLineEdit4TextChanged(const QString & strtemp); - -private: - QLineEdit *m_lineEidt[4]; - QHBoxLayout *pHBox; - QColor m_Color; -}; - -#endif // QIPLINEEDIT_H +#ifndef QIPLINEEDIT_H +#define QIPLINEEDIT_H + +#include +#include +#include + +class QIPLineEdit : public QLineEdit { + Q_OBJECT +public: + QIPLineEdit(QWidget *parent = nullptr); + ~QIPLineEdit(); + + void setText(const QString &strIP); + QString text() const; + void MyClear(); + void MySetColor(QColor cr); + +protected: + void paintEvent(QPaintEvent *event); + bool eventFilter(QObject *obj, QEvent *ev); + + int getIndex(QLineEdit *pEdit); + bool isTextValid(const QString &strIP); +protected slots: + void OnLineEdit1TextChanged(const QString & strtemp); + void OnLineEdit2TextChanged(const QString & strtemp); + void OnLineEdit3TextChanged(const QString & strtemp); + void OnLineEdit4TextChanged(const QString & strtemp); + +private: + QLineEdit *m_lineEidt[4]; + QHBoxLayout *pHBox; + QColor m_Color; +}; + +#endif // QIPLINEEDIT_H diff --git a/LedOK/base/readexcel.cpp b/LedOK/base/readexcel.cpp index 302f608..bfd8fe8 100644 --- a/LedOK/base/readexcel.cpp +++ b/LedOK/base/readexcel.cpp @@ -1,169 +1,169 @@ -#include "readexcel.h" -#include -#include - -ReadExcel::ReadExcel() - :m_row(0), m_col(0), m_filename("") -{ - m_excel = new QAxObject("Excel.Application"); -} - -ReadExcel::~ReadExcel() -{ - if (!m_mapdata.empty()) { - m_mapdata.clear(); - } - delete m_excel; -} - -// -bool ReadExcel::openExcel(const QString &filename) -{ - if (filename.isEmpty()) { - m_row = 0; - m_col = 0; - return false; - } - QFile file(filename); - if (!file.exists()){ - m_row = 0; - m_col = 0; - return false; - }; - if (!m_mapdata.empty()) { - m_mapdata.clear(); - } - m_filename = filename; - try { - getALLfromExcel(); - - } catch (...) { - return false; - } - - return true; -} -void ReadExcel::getALLfromDirNormalExcel(QString strFileName) -{ - openExcelForWrite(strFileName); -} -bool ReadExcel::openExcelForWrite(const QString &filename) -{ - if (filename.isEmpty()) { - m_row = 0; - m_col = 0; - return false; - } - QFile file(filename); - if (!file.exists()){ - m_row = 0; - m_col = 0; - return false; - }; - if (!m_mapdata.empty()) { - m_mapdata.clear(); - } - m_filename = filename; - try { - WriteALLfromExcel(); - } catch (...) { - return false; - } - - return true; -} - -void ReadExcel::getInfo(int &row, int &col) const -{ - row = m_row; - col = m_col; -} - -std::string ReadExcel::getCellData(const int &row, const int &col) -{ - if (row >= 1 && row <= m_row && col >= 1 && col <= m_col) { - p.m_row = row; - p.m_col = col; - return m_mapdata[p]; - } else { - return nullptr; - } -} -int ReadExcel::WriteCellData(const int &row, const int &col,std::string strValue ) -{ - p.m_row = row; - p.m_col = col; - - m_mapdata[p]=strValue; - return 0; -} - -void ReadExcel::getALLfromExcel() -{ - m_excel->setProperty("Visible", 0); - QAxObject* workbooks = m_excel->querySubObject("WorkBooks"); - workbooks->dynamicCall("Open (const QString&)", m_filename); - QAxObject* workbook = m_excel->querySubObject("ActiveWorkBook"); - QAxObject* worksheets = workbook->querySubObject("WorkSheets"); - Q_UNUSED(worksheets) - QAxObject* worksheet = workbook->querySubObject("Worksheets(int)", 1); //worksheet number - QAxObject* usedrange = worksheet->querySubObject("UsedRange"); - QAxObject* rows = usedrange->querySubObject("Rows"); - QAxObject* columns = usedrange->querySubObject("Columns"); - int intRowStart = usedrange->property("Row").toInt(); - int intColStart = usedrange->property("Column").toInt(); - int intCols = columns->property("Count").toInt(); - int intRows = rows->property("Count").toInt(); - m_row = intRows; - m_col = intCols; - QAxObject * cell; - for (int i = intRowStart; i < intRowStart + intRows; i++) - { - for (int j = intColStart; j < intColStart + intCols; j++) - { - Position pos(i, j); - cell = m_excel->querySubObject("Cells(Int, Int)", i, j ); - QVariant cellValue = cell->dynamicCall("value"); - m_mapdata.insert(std::pair(pos, cellValue.toString().toStdString())); - } - } - m_excel->setProperty("DisplayAlerts", 0); - workbook->dynamicCall("Save(void)"); - workbook->dynamicCall("Close (Boolean)", false); - m_excel->setProperty("DisplayAlerts",1); -} -void ReadExcel::WriteALLfromExcel() -{ - m_excel->setProperty("Visible", 0); - QAxObject* workbooks = m_excel->querySubObject("WorkBooks"); - workbooks->dynamicCall("Open (const QString&)", m_filename); - QAxObject* workbook = m_excel->querySubObject("ActiveWorkBook"); - QAxObject* worksheets = workbook->querySubObject("WorkSheets"); - Q_UNUSED(worksheets) - QAxObject* worksheet = workbook->querySubObject("Worksheets(int)", 1); //worksheet number - QAxObject* usedrange = worksheet->querySubObject("UsedRange"); - QAxObject* rows = usedrange->querySubObject("Rows"); - QAxObject* columns = usedrange->querySubObject("Columns"); - int intRowStart = usedrange->property("Row").toInt(); - int intColStart = usedrange->property("Column").toInt(); - int intCols = columns->property("Count").toInt(); - int intRows = rows->property("Count").toInt(); - m_row = intRows; - m_col = intCols; - QAxObject * cell; - for (int i = intRowStart; i < intRowStart + intRows; i++) - { - for (int j = intColStart; j < intColStart + intCols; j++) - { - Position pos(i, j); - cell = m_excel->querySubObject("Cells(Int, Int)", i, j ); - QVariant cellValue = cell->dynamicCall("value"); - m_mapdata.insert(std::pair(pos, cellValue.toString().toStdString())); - } - } - - m_excel->setProperty("DisplayAlerts", 0); - workbook->dynamicCall("Save(void)"); - workbook->dynamicCall("Close (Boolean)", false); - m_excel->setProperty("DisplayAlerts",1); -} +#include "readexcel.h" +#include +#include + +ReadExcel::ReadExcel() + :m_row(0), m_col(0), m_filename("") +{ + m_excel = new QAxObject("Excel.Application"); +} + +ReadExcel::~ReadExcel() +{ + if (!m_mapdata.empty()) { + m_mapdata.clear(); + } + delete m_excel; +} + +// +bool ReadExcel::openExcel(const QString &filename) +{ + if (filename.isEmpty()) { + m_row = 0; + m_col = 0; + return false; + } + QFile file(filename); + if (!file.exists()){ + m_row = 0; + m_col = 0; + return false; + }; + if (!m_mapdata.empty()) { + m_mapdata.clear(); + } + m_filename = filename; + try { + getALLfromExcel(); + + } catch (...) { + return false; + } + + return true; +} +void ReadExcel::getALLfromDirNormalExcel(QString strFileName) +{ + openExcelForWrite(strFileName); +} +bool ReadExcel::openExcelForWrite(const QString &filename) +{ + if (filename.isEmpty()) { + m_row = 0; + m_col = 0; + return false; + } + QFile file(filename); + if (!file.exists()){ + m_row = 0; + m_col = 0; + return false; + }; + if (!m_mapdata.empty()) { + m_mapdata.clear(); + } + m_filename = filename; + try { + WriteALLfromExcel(); + } catch (...) { + return false; + } + + return true; +} + +void ReadExcel::getInfo(int &row, int &col) const +{ + row = m_row; + col = m_col; +} + +std::string ReadExcel::getCellData(const int &row, const int &col) +{ + if (row >= 1 && row <= m_row && col >= 1 && col <= m_col) { + p.m_row = row; + p.m_col = col; + return m_mapdata[p]; + } else { + return nullptr; + } +} +int ReadExcel::WriteCellData(const int &row, const int &col,std::string strValue ) +{ + p.m_row = row; + p.m_col = col; + + m_mapdata[p]=strValue; + return 0; +} + +void ReadExcel::getALLfromExcel() +{ + m_excel->setProperty("Visible", 0); + QAxObject* workbooks = m_excel->querySubObject("WorkBooks"); + workbooks->dynamicCall("Open (const QString&)", m_filename); + QAxObject* workbook = m_excel->querySubObject("ActiveWorkBook"); + QAxObject* worksheets = workbook->querySubObject("WorkSheets"); + Q_UNUSED(worksheets) + QAxObject* worksheet = workbook->querySubObject("Worksheets(int)", 1); //worksheet number + QAxObject* usedrange = worksheet->querySubObject("UsedRange"); + QAxObject* rows = usedrange->querySubObject("Rows"); + QAxObject* columns = usedrange->querySubObject("Columns"); + int intRowStart = usedrange->property("Row").toInt(); + int intColStart = usedrange->property("Column").toInt(); + int intCols = columns->property("Count").toInt(); + int intRows = rows->property("Count").toInt(); + m_row = intRows; + m_col = intCols; + QAxObject * cell; + for (int i = intRowStart; i < intRowStart + intRows; i++) + { + for (int j = intColStart; j < intColStart + intCols; j++) + { + Position pos(i, j); + cell = m_excel->querySubObject("Cells(Int, Int)", i, j ); + QVariant cellValue = cell->dynamicCall("value"); + m_mapdata.insert(std::pair(pos, cellValue.toString().toStdString())); + } + } + m_excel->setProperty("DisplayAlerts", 0); + workbook->dynamicCall("Save(void)"); + workbook->dynamicCall("Close (Boolean)", false); + m_excel->setProperty("DisplayAlerts",1); +} +void ReadExcel::WriteALLfromExcel() +{ + m_excel->setProperty("Visible", 0); + QAxObject* workbooks = m_excel->querySubObject("WorkBooks"); + workbooks->dynamicCall("Open (const QString&)", m_filename); + QAxObject* workbook = m_excel->querySubObject("ActiveWorkBook"); + QAxObject* worksheets = workbook->querySubObject("WorkSheets"); + Q_UNUSED(worksheets) + QAxObject* worksheet = workbook->querySubObject("Worksheets(int)", 1); //worksheet number + QAxObject* usedrange = worksheet->querySubObject("UsedRange"); + QAxObject* rows = usedrange->querySubObject("Rows"); + QAxObject* columns = usedrange->querySubObject("Columns"); + int intRowStart = usedrange->property("Row").toInt(); + int intColStart = usedrange->property("Column").toInt(); + int intCols = columns->property("Count").toInt(); + int intRows = rows->property("Count").toInt(); + m_row = intRows; + m_col = intCols; + QAxObject * cell; + for (int i = intRowStart; i < intRowStart + intRows; i++) + { + for (int j = intColStart; j < intColStart + intCols; j++) + { + Position pos(i, j); + cell = m_excel->querySubObject("Cells(Int, Int)", i, j ); + QVariant cellValue = cell->dynamicCall("value"); + m_mapdata.insert(std::pair(pos, cellValue.toString().toStdString())); + } + } + + m_excel->setProperty("DisplayAlerts", 0); + workbook->dynamicCall("Save(void)"); + workbook->dynamicCall("Close (Boolean)", false); + m_excel->setProperty("DisplayAlerts",1); +} diff --git a/LedOK/base/readexcel.h b/LedOK/base/readexcel.h index 2300d60..68bc5af 100644 --- a/LedOK/base/readexcel.h +++ b/LedOK/base/readexcel.h @@ -1,78 +1,78 @@ -#ifndef READEXCEL_H -#define READEXCEL_H - -#include -#include -#include -#include -#include -#include -#include - - -class Position -{ -public: - Position() { - m_row = 0; - m_col = 0; - } - - Position(int row, int col) { - m_row = row; - m_col = col; - } -public: - int m_row; - int m_col; - -public: - bool operator<(const Position & ct) const // 两个const是必需的。 - { - if (m_row < ct.m_row) { - return true; - } else if (m_row == ct.m_row) { - if ( m_col < ct.m_col ) { - return true; - } - } - return false; - } -}; - -class ReadExcel -{ -public: - ReadExcel(); - ~ReadExcel(); - -public: - //打开excel文件 - bool openExcel(const QString& filename); - void getALLfromDirNormalExcel(QString strFileName); - bool openExcelForWrite(const QString &filename); - //获取 指定单元格的数据 - std::string getCellData(const int& row, const int& col); - int WriteCellData(const int& row, const int& col,std::string strValue ); - //获取 行数,列数 - void getInfo(int& row, int& col) const; - -private: - void getALLfromExcel(); - void WriteALLfromExcel(); - -private: - int m_row; //行 - int m_col; //列 - QString m_filename; - QAxObject* m_excel; - int m_rowWrite; //行 - int m_colWrite; //列 - QAxObject* m_excelWrite; - - std::map m_mapdata; - std::map m_mapdataWrite; - Position p; -}; - -#endif // READEXCEL_H +#ifndef READEXCEL_H +#define READEXCEL_H + +#include +#include +#include +#include +#include +#include +#include + + +class Position +{ +public: + Position() { + m_row = 0; + m_col = 0; + } + + Position(int row, int col) { + m_row = row; + m_col = col; + } +public: + int m_row; + int m_col; + +public: + bool operator<(const Position & ct) const // 两个const是必需的。 + { + if (m_row < ct.m_row) { + return true; + } else if (m_row == ct.m_row) { + if ( m_col < ct.m_col ) { + return true; + } + } + return false; + } +}; + +class ReadExcel +{ +public: + ReadExcel(); + ~ReadExcel(); + +public: + //打开excel文件 + bool openExcel(const QString& filename); + void getALLfromDirNormalExcel(QString strFileName); + bool openExcelForWrite(const QString &filename); + //获取 指定单元格的数据 + std::string getCellData(const int& row, const int& col); + int WriteCellData(const int& row, const int& col,std::string strValue ); + //获取 行数,列数 + void getInfo(int& row, int& col) const; + +private: + void getALLfromExcel(); + void WriteALLfromExcel(); + +private: + int m_row; //行 + int m_col; //列 + QString m_filename; + QAxObject* m_excel; + int m_rowWrite; //行 + int m_colWrite; //列 + QAxObject* m_excelWrite; + + std::map m_mapdata; + std::map m_mapdataWrite; + Position p; +}; + +#endif // READEXCEL_H diff --git a/LedOK/base/softconfigdialog.cpp b/LedOK/base/softconfigdialog.cpp index 51a70c4..fb9d5e4 100644 --- a/LedOK/base/softconfigdialog.cpp +++ b/LedOK/base/softconfigdialog.cpp @@ -1,58 +1,58 @@ -#include "softconfigdialog.h" -#include "cfg.h" -#include "globaldefine.h" -#include -#include -#include -#include - -SoftConfigDialog::SoftConfigDialog(QWidget *parent) : BaseDlg(parent) { - resize(400, 300); - setWindowTitle(tr("Software Configuration")); - auto vbox = new QVBoxLayout(this); - - auto pushButton = new QPushButton("X"); - pushButton->setMinimumSize(30, 24); - connect(pushButton, &QPushButton::clicked, this, &QWidget::close); - vbox->addWidget(pushButton, 0, Qt::AlignRight); - - press_fd = new QCheckBox(tr("Video compress to")+" 720p"); - press_fd->setChecked(gVideoCompress); - vbox->addWidget(press_fd); - - trans_fd = new QCheckBox(tr("Video transcoding to")+" h264"); - trans_fd->setChecked(gVideoTranscoding); - vbox->addWidget(trans_fd); - - auto hbox = new QHBoxLayout(); - hbox->setContentsMargins(-1, 0, -1, -1); - anti_fd = new QCheckBox(tr("Text antialiasing")); - anti_fd->setChecked(gTextAntialiasing); - hbox->addWidget(anti_fd, 0, Qt::AlignTop); - - auto anti_tip = new QLabel(tr("TextAntilaTip")); - anti_tip->setStyleSheet("color:#FF0000;"); - anti_tip->setWordWrap(true); - hbox->addWidget(anti_tip); - - vbox->addLayout(hbox); - - vbox->addWidget(guangying_fd = new QCheckBox(tr("GuangYinPin"))); - guangying_fd->setChecked(gShowLoraScreen); - - vbox->addWidget(fdWidthSplit = new QCheckBox(tr("Width Split"))); - fdWidthSplit->setChecked(gWidthSplit); - - - auto ok_btn = new QPushButton(tr("OK")); - vbox->addWidget(ok_btn, 0, Qt::AlignCenter); - connect(ok_btn, &QPushButton::clicked, this, [this]() { - QSettings settings; - settings.setValue("VideoCompress", gVideoCompress = press_fd->isChecked()); - settings.setValue("VideoTranscoding", gVideoTranscoding = trans_fd->isChecked()); - settings.setValue("TextAntialiasing", gTextAntialiasing = anti_fd->isChecked()); - settings.setValue("GuangYingPin",gShowLoraScreen = guangying_fd->isChecked()); - settings.setValue("WidthSplit", gWidthSplit = fdWidthSplit->isChecked()); - accept(); - }); -} +#include "softconfigdialog.h" +#include "cfg.h" +#include "globaldefine.h" +#include +#include +#include +#include + +SoftConfigDialog::SoftConfigDialog(QWidget *parent) : BaseDlg(parent) { + resize(400, 300); + setWindowTitle(tr("Software Config")); + auto vbox = new QVBoxLayout(this); + + auto pushButton = new QPushButton("X"); + pushButton->setMinimumSize(30, 24); + connect(pushButton, &QPushButton::clicked, this, &QWidget::close); + vbox->addWidget(pushButton, 0, Qt::AlignRight); + + press_fd = new QCheckBox(tr("Video compress to")+" 720p"); + press_fd->setChecked(gVideoCompress); + vbox->addWidget(press_fd); + + trans_fd = new QCheckBox(tr("Video transcoding to")+" h264"); + trans_fd->setChecked(gVideoTranscoding); + vbox->addWidget(trans_fd); + + auto hbox = new QHBoxLayout(); + hbox->setContentsMargins(-1, 0, -1, -1); + anti_fd = new QCheckBox(tr("Text antialiasing")); + anti_fd->setChecked(gTextAntialiasing); + hbox->addWidget(anti_fd, 0, Qt::AlignTop); + + auto anti_tip = new QLabel(tr("TextAntilaTip")); + anti_tip->setStyleSheet("color:#FF0000;"); + anti_tip->setWordWrap(true); + hbox->addWidget(anti_tip); + + vbox->addLayout(hbox); + + vbox->addWidget(guangying_fd = new QCheckBox(tr("GuangYinPin"))); + guangying_fd->setChecked(gShowLoraScreen); + + vbox->addWidget(fdWidthSplit = new QCheckBox(tr("Width Split"))); + fdWidthSplit->setChecked(gWidthSplit); + + + auto ok_btn = new QPushButton(tr("OK")); + vbox->addWidget(ok_btn, 0, Qt::AlignCenter); + connect(ok_btn, &QPushButton::clicked, this, [this]() { + QSettings settings; + settings.setValue("VideoCompress", gVideoCompress = press_fd->isChecked()); + settings.setValue("VideoTranscoding", gVideoTranscoding = trans_fd->isChecked()); + settings.setValue("TextAntialiasing", gTextAntialiasing = anti_fd->isChecked()); + settings.setValue("GuangYingPin",gShowLoraScreen = guangying_fd->isChecked()); + settings.setValue("WidthSplit", gWidthSplit = fdWidthSplit->isChecked()); + accept(); + }); +} diff --git a/LedOK/base/softconfigdialog.h b/LedOK/base/softconfigdialog.h index ae7d2fa..c1f4f13 100644 --- a/LedOK/base/softconfigdialog.h +++ b/LedOK/base/softconfigdialog.h @@ -1,15 +1,15 @@ -#ifndef SOFTCONFIGDIALOG_H -#define SOFTCONFIGDIALOG_H - -#include "basedlg.h" -#include - -class SoftConfigDialog : public BaseDlg { - Q_OBJECT -public: - explicit SoftConfigDialog(QWidget *parent = nullptr); - - QCheckBox *press_fd, *trans_fd, *anti_fd, *guangying_fd, *fdWidthSplit; -}; - -#endif // SOFTCONFIGDIALOG_H +#ifndef SOFTCONFIGDIALOG_H +#define SOFTCONFIGDIALOG_H + +#include "basedlg.h" +#include + +class SoftConfigDialog : public BaseDlg { + Q_OBJECT +public: + explicit SoftConfigDialog(QWidget *parent = nullptr); + + QCheckBox *press_fd, *trans_fd, *anti_fd, *guangying_fd, *fdWidthSplit; +}; + +#endif // SOFTCONFIGDIALOG_H diff --git a/LedOK/base/switchcontrol.cpp b/LedOK/base/switchcontrol.cpp index d5784a9..a7f9fa3 100644 --- a/LedOK/base/switchcontrol.cpp +++ b/LedOK/base/switchcontrol.cpp @@ -1,484 +1,484 @@ -#include "switchcontrol.h" -#include "qpainter.h" -#include -#include "qevent.h" -#include "qtimer.h" -#include "qdebug.h" - -SwitchControl::SwitchControl(QWidget *parent): QWidget(parent) -{ - checked = false; - buttonStyle = ButtonStyle_Rect; - - bgColorOff = QColor(225, 225, 225); - bgColorOn = QColor(250, 250, 250); - - sliderColorOff = QColor(100, 100, 100); - sliderColorOn = QColor(100, 184, 255); - - textColorOff = QColor(255, 255, 255); - textColorOn = QColor(10, 10, 10); - - textOff = ""; - textOn = ""; - - imageOff = ":/image/btncheckoff1.png"; - imageOn = ":/image/btncheckon1.png"; - - space = 2; - rectRadius = 5; - - step = width() / 50; - startX = 0; - endX = 0; - - timer = new QTimer(this); - timer->setInterval(5); - connect(timer, SIGNAL(timeout()), this, SLOT(updateValue())); - - setFont(QFont("Microsoft Yahei", 10)); -} - -SwitchControl::~SwitchControl() -{ - -} - -void SwitchControl::mousePressEvent(QMouseEvent *) -{ - checked = !checked; - - //每次移动的步长为宽度的 50分之一 - step = width() / 50; - - //状态切换改变后自动计算终点坐标 - if (checked) { - if (buttonStyle == ButtonStyle_Rect) { - endX = width() - width() / 2; - } else if (buttonStyle == ButtonStyle_CircleIn) { - endX = width() - height(); - } else if (buttonStyle == ButtonStyle_CircleOut) { - endX = width() - height() + space; - } - } else { - endX = 0; - } - - timer->start(); - emit checkedChanged(checked); -} - -void SwitchControl::resizeEvent(QResizeEvent *) -{ - //每次移动的步长为宽度的 50分之一 - step = width() / 50; - - //尺寸大小改变后自动设置起点坐标为终点 - if (checked) { - if (buttonStyle == ButtonStyle_Rect) { - startX = width() - width() / 2; - } else if (buttonStyle == ButtonStyle_CircleIn) { - startX = width() - height(); - } else if (buttonStyle == ButtonStyle_CircleOut) { - startX = width() - height() + space; - } - } else { - startX = 0; - } - - update(); -} - -void SwitchControl::paintEvent(QPaintEvent *) -{ - //绘制准备工作,启用反锯齿 - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - - if (buttonStyle == ButtonStyle_Image) { - //绘制图片 - drawImage(&painter); - } else { - //绘制背景 - drawBg(&painter); - //绘制滑块 - drawSlider(&painter); - //绘制文字 - drawText(&painter); - } -} - -void SwitchControl::drawBg(QPainter *painter) -{ - painter->save(); - painter->setPen(Qt::NoPen); - - if (!checked) { - painter->setBrush(bgColorOff); - } else { - painter->setBrush(bgColorOn); - } - - if (buttonStyle == ButtonStyle_Rect) { - painter->drawRoundedRect(rect(), rectRadius, rectRadius); - } else if (buttonStyle == ButtonStyle_CircleIn) { - QRect rect(0, 0, width(), height()); - //半径为高度的一半 - int radius = rect.height() / 2; - //圆的宽度为高度 - int circleWidth = rect.height(); - - QPainterPath path; - path.moveTo(radius, rect.left()); - path.arcTo(QRectF(rect.left(), rect.top(), circleWidth, circleWidth), 90, 180); - path.lineTo(rect.width() - radius, rect.height()); - path.arcTo(QRectF(rect.width() - rect.height(), rect.top(), circleWidth, circleWidth), 270, 180); - path.lineTo(radius, rect.top()); - - painter->drawPath(path); - } else if (buttonStyle == ButtonStyle_CircleOut) { - QRect rect(space, space, width() - space * 2, height() - space * 2); - painter->drawRoundedRect(rect, rectRadius, rectRadius); - } - - painter->restore(); -} - -void SwitchControl::drawSlider(QPainter *painter) -{ - painter->save(); - painter->setPen(Qt::NoPen); - - if (!checked) { - painter->setBrush(sliderColorOff); - } else { - painter->setBrush(sliderColorOn); - } - - if (buttonStyle == ButtonStyle_Rect) { - int sliderWidth = width() / 2 - space * 2; - int sliderHeight = height() - space * 2; - QRect sliderRect(startX + space, space, sliderWidth , sliderHeight); - painter->drawRoundedRect(sliderRect, rectRadius, rectRadius); - } else if (buttonStyle == ButtonStyle_CircleIn) { - QRect rect(0, 0, width(), height()); - int sliderWidth = rect.height() - space * 2; - QRect sliderRect(startX + space, space, sliderWidth, sliderWidth); - painter->drawEllipse(sliderRect); - } else if (buttonStyle == ButtonStyle_CircleOut) { - QRect rect(0, 0, width() - space, height() - space); - int sliderWidth = rect.height(); - QRect sliderRect(startX, space / 2, sliderWidth, sliderWidth); - painter->drawEllipse(sliderRect); - } - - painter->restore(); -} - -void SwitchControl::drawText(QPainter *painter) -{ - painter->save(); - - if (!checked) { - painter->setPen(textColorOff); - painter->drawText(width() / 2, 0, width() / 2 - space, height(), Qt::AlignCenter, textOff); - } else { - painter->setPen(textColorOn); - painter->drawText(0, 0, width() / 2 + space * 2, height(), Qt::AlignCenter, textOn); - } - - painter->restore(); -} - -void SwitchControl::drawImage(QPainter *painter) -{ - painter->save(); - - QPixmap pix; - - if (!checked) { - pix = QPixmap(imageOff); - } else { - pix = QPixmap(imageOn); - } - - //自动等比例平滑缩放居中显示 - int targetWidth = pix.width(); - int targetHeight = pix.height(); - pix = pix.scaled(targetWidth, targetHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - int pixX = rect().center().x() - targetWidth / 2; - int pixY = rect().center().y() - targetHeight / 2; - QPoint point(pixX, pixY); - painter->drawPixmap(point, pix); - - painter->restore(); -} - -void SwitchControl::updateValue() -{ - if (checked) { - if (startX < endX) { - startX = startX + step; - } else { - startX = endX; - timer->stop(); - } - } else { - if (startX > endX) { - startX = startX - step; - } else { - startX = endX; - timer->stop(); - } - } - - update(); -} - -void SwitchControl::setChecked(bool checked) -{ - if (this->checked != checked) { - this->checked = checked; - emit checkedChanged(checked); - update(); - } -} -void SwitchControl::setCheckedStatus(bool checked) -{ - if (this->checked != checked) { - this->checked = checked; - - } - update(); - step = width() / 50; - //状态切换改变后自动计算终点坐标 - if (checked) { - if (buttonStyle == ButtonStyle_Rect) { - endX = width() - width() / 2; - } else if (buttonStyle == ButtonStyle_CircleIn) { - endX = width() - height(); - } else if (buttonStyle == ButtonStyle_CircleOut) { - endX = width() - height() + space; - } - } else { - endX = 0; - } - - timer->start(); - -} -void SwitchControl::setButtonStyle(SwitchControl::ButtonStyle buttonStyle) -{ - this->buttonStyle = buttonStyle; - update(); -} - -void SwitchControl::setBgColor(QColor bgColorOff, QColor bgColorOn) -{ - this->bgColorOff = bgColorOff; - this->bgColorOn = bgColorOn; - update(); -} - -void SwitchControl::setSliderColor(QColor sliderColorOff, QColor sliderColorOn) -{ - this->sliderColorOff = sliderColorOff; - this->sliderColorOn = sliderColorOn; - update(); -} - -void SwitchControl::setTextColor(QColor textColorOff, QColor textColorOn) -{ - this->textColorOff = textColorOff; - this->textColorOn = textColorOn; - update(); -} - -void SwitchControl::setText(QString textOff, QString textOn) -{ - this->textOff = textOff; - this->textOn = textOn; - update(); -} - -void SwitchControl::setImage(QString imageOff, QString imageOn) -{ - this->imageOff = imageOff; - this->imageOn = imageOn; - update(); -} - -void SwitchControl::setSpace(int space) -{ - this->space = space; - update(); -} - -void SwitchControl::setRectRadius(int rectRadius) -{ - this->rectRadius = rectRadius; - update(); -} -/*#include -#include - - -SwitchControl::SwitchControl(QWidget *parent) - : QWidget(parent) -{ - m_nHeight=16; - m_bChecked=false; - m_radius=8.0; - m_nMargin=5; - m_checkedColor=QColor(0, 150, 136); - m_thumbColor=Qt::white; - m_disabledColor=QColor(190, 190, 190); - m_background=Qt::black; - setAttribute(Qt::WA_DeleteOnClose); - // 鼠标滑过光标形状 - 手型 - setCursor(Qt::PointingHandCursor); - - // 连接信号槽 - connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimeout())); -} - -// 绘制开关 -void SwitchControl::paintEvent(QPaintEvent *event) -{ - Q_UNUSED(event); - - QPainter painter(this); - painter.setPen(Qt::NoPen); - painter.setRenderHint(QPainter::Antialiasing); - - QPainterPath path; - QColor background; - QColor thumbColor; - qreal dOpacity; - if (isEnabled()) { // 可用状态 - if (m_bChecked) { // 打开状态 - background = m_checkedColor; - thumbColor = m_checkedColor; - dOpacity = 0.600; - } else { //关闭状态 - background = m_background; - thumbColor = m_thumbColor; - dOpacity = 0.800; - } - } else { // 不可用状态 - background = m_background; - dOpacity = 0.260; - thumbColor = m_disabledColor; - } - // 绘制大椭圆 - painter.setBrush(background); - painter.setOpacity(dOpacity); - path.addRoundedRect(QRectF(m_nMargin, m_nMargin, width() - 2 * m_nMargin-(m_nHeight / 2), height() - 2 * m_nMargin), m_radius, m_radius); - painter.drawPath(path.simplified()); - - // 绘制小椭圆 - painter.setBrush(thumbColor); - painter.setOpacity(1.0); - painter.drawEllipse(QRectF(m_nX - (m_nHeight / 2), m_nY - (m_nHeight / 2), height(), height())); -} - -// 鼠标按下事件 -void SwitchControl::mousePressEvent(QMouseEvent *event) -{ - if (isEnabled()) { - if (event->buttons() & Qt::LeftButton) { - event->accept(); - } else { - event->ignore(); - } - } -} - -// 鼠标释放事件 - 切换开关状态、发射toggled()信号 -void SwitchControl::mouseReleaseEvent(QMouseEvent *event) -{ - if (isEnabled()) { - if ((event->type() == QMouseEvent::MouseButtonRelease) && (event->button() == Qt::LeftButton)) { - event->accept(); - m_bChecked = !m_bChecked; - emit toggled(m_bChecked); - m_timer.start(10); - } else { - event->ignore(); - } - } -} - -// 大小改变事件 -void SwitchControl::resizeEvent(QResizeEvent *event) -{ - m_nX = m_nHeight / 2; - m_nY = m_nHeight / 2; - QWidget::resizeEvent(event); -} - -// 默认大小 -QSize SwitchControl::sizeHint() const -{ - return minimumSizeHint(); -} - -// 最小大小 -QSize SwitchControl::minimumSizeHint() const -{ - return QSize(2 * (m_nHeight + m_nMargin), m_nHeight + 2 * m_nMargin); -} - -// 切换状态 - 滑动 -void SwitchControl::onTimeout() -{ - if (m_bChecked) { - m_nX += 1; - if (m_nX >= width() - m_nHeight*2) - m_timer.stop(); - } else { - m_nX -= 1; - if (m_nX <= m_nHeight / 2) - m_timer.stop(); - } - update(); -} - -// 返回开关状态 - 打开:true 关闭:false -bool SwitchControl::isToggled() const -{ - return m_bChecked; -} - -// 设置开关状态 -void SwitchControl::setToggle(bool checked) -{ - m_bChecked = checked; - m_timer.start(10); -} - -// 设置背景颜色 -void SwitchControl::setBackgroundColor(QColor color) -{ - m_background = color; -} -// 设置拇指颜色 -void SwitchControl::setthumbColor(QColor color) -{ - //拇指颜色 - m_thumbColor = color; -} - -// 设置选中颜色 -void SwitchControl::setCheckedColor(QColor color) -{ - m_checkedColor = color; -} - -// 设置不可用颜色 -void SwitchControl::setDisbaledColor(QColor color) -{ - m_disabledColor = color; -} -*/ +#include "switchcontrol.h" +#include "qpainter.h" +#include +#include "qevent.h" +#include "qtimer.h" +#include "qdebug.h" + +SwitchControl::SwitchControl(QWidget *parent): QWidget(parent) +{ + checked = false; + buttonStyle = ButtonStyle_Rect; + + bgColorOff = QColor(225, 225, 225); + bgColorOn = QColor(250, 250, 250); + + sliderColorOff = QColor(100, 100, 100); + sliderColorOn = QColor(100, 184, 255); + + textColorOff = QColor(255, 255, 255); + textColorOn = QColor(10, 10, 10); + + textOff = ""; + textOn = ""; + + imageOff = ":/image/btncheckoff1.png"; + imageOn = ":/image/btncheckon1.png"; + + space = 2; + rectRadius = 5; + + step = width() / 50; + startX = 0; + endX = 0; + + timer = new QTimer(this); + timer->setInterval(5); + connect(timer, SIGNAL(timeout()), this, SLOT(updateValue())); + + setFont(QFont("Microsoft Yahei", 10)); +} + +SwitchControl::~SwitchControl() +{ + +} + +void SwitchControl::mousePressEvent(QMouseEvent *) +{ + checked = !checked; + + //每次移动的步长为宽度的 50分之一 + step = width() / 50; + + //状态切换改变后自动计算终点坐标 + if (checked) { + if (buttonStyle == ButtonStyle_Rect) { + endX = width() - width() / 2; + } else if (buttonStyle == ButtonStyle_CircleIn) { + endX = width() - height(); + } else if (buttonStyle == ButtonStyle_CircleOut) { + endX = width() - height() + space; + } + } else { + endX = 0; + } + + timer->start(); + emit checkedChanged(checked); +} + +void SwitchControl::resizeEvent(QResizeEvent *) +{ + //每次移动的步长为宽度的 50分之一 + step = width() / 50; + + //尺寸大小改变后自动设置起点坐标为终点 + if (checked) { + if (buttonStyle == ButtonStyle_Rect) { + startX = width() - width() / 2; + } else if (buttonStyle == ButtonStyle_CircleIn) { + startX = width() - height(); + } else if (buttonStyle == ButtonStyle_CircleOut) { + startX = width() - height() + space; + } + } else { + startX = 0; + } + + update(); +} + +void SwitchControl::paintEvent(QPaintEvent *) +{ + //绘制准备工作,启用反锯齿 + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + + if (buttonStyle == ButtonStyle_Image) { + //绘制图片 + drawImage(&painter); + } else { + //绘制背景 + drawBg(&painter); + //绘制滑块 + drawSlider(&painter); + //绘制文字 + drawText(&painter); + } +} + +void SwitchControl::drawBg(QPainter *painter) +{ + painter->save(); + painter->setPen(Qt::NoPen); + + if (!checked) { + painter->setBrush(bgColorOff); + } else { + painter->setBrush(bgColorOn); + } + + if (buttonStyle == ButtonStyle_Rect) { + painter->drawRoundedRect(rect(), rectRadius, rectRadius); + } else if (buttonStyle == ButtonStyle_CircleIn) { + QRect rect(0, 0, width(), height()); + //半径为高度的一半 + int radius = rect.height() / 2; + //圆的宽度为高度 + int circleWidth = rect.height(); + + QPainterPath path; + path.moveTo(radius, rect.left()); + path.arcTo(QRectF(rect.left(), rect.top(), circleWidth, circleWidth), 90, 180); + path.lineTo(rect.width() - radius, rect.height()); + path.arcTo(QRectF(rect.width() - rect.height(), rect.top(), circleWidth, circleWidth), 270, 180); + path.lineTo(radius, rect.top()); + + painter->drawPath(path); + } else if (buttonStyle == ButtonStyle_CircleOut) { + QRect rect(space, space, width() - space * 2, height() - space * 2); + painter->drawRoundedRect(rect, rectRadius, rectRadius); + } + + painter->restore(); +} + +void SwitchControl::drawSlider(QPainter *painter) +{ + painter->save(); + painter->setPen(Qt::NoPen); + + if (!checked) { + painter->setBrush(sliderColorOff); + } else { + painter->setBrush(sliderColorOn); + } + + if (buttonStyle == ButtonStyle_Rect) { + int sliderWidth = width() / 2 - space * 2; + int sliderHeight = height() - space * 2; + QRect sliderRect(startX + space, space, sliderWidth , sliderHeight); + painter->drawRoundedRect(sliderRect, rectRadius, rectRadius); + } else if (buttonStyle == ButtonStyle_CircleIn) { + QRect rect(0, 0, width(), height()); + int sliderWidth = rect.height() - space * 2; + QRect sliderRect(startX + space, space, sliderWidth, sliderWidth); + painter->drawEllipse(sliderRect); + } else if (buttonStyle == ButtonStyle_CircleOut) { + QRect rect(0, 0, width() - space, height() - space); + int sliderWidth = rect.height(); + QRect sliderRect(startX, space / 2, sliderWidth, sliderWidth); + painter->drawEllipse(sliderRect); + } + + painter->restore(); +} + +void SwitchControl::drawText(QPainter *painter) +{ + painter->save(); + + if (!checked) { + painter->setPen(textColorOff); + painter->drawText(width() / 2, 0, width() / 2 - space, height(), Qt::AlignCenter, textOff); + } else { + painter->setPen(textColorOn); + painter->drawText(0, 0, width() / 2 + space * 2, height(), Qt::AlignCenter, textOn); + } + + painter->restore(); +} + +void SwitchControl::drawImage(QPainter *painter) +{ + painter->save(); + + QPixmap pix; + + if (!checked) { + pix = QPixmap(imageOff); + } else { + pix = QPixmap(imageOn); + } + + //自动等比例平滑缩放居中显示 + int targetWidth = pix.width(); + int targetHeight = pix.height(); + pix = pix.scaled(targetWidth, targetHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + + int pixX = rect().center().x() - targetWidth / 2; + int pixY = rect().center().y() - targetHeight / 2; + QPoint point(pixX, pixY); + painter->drawPixmap(point, pix); + + painter->restore(); +} + +void SwitchControl::updateValue() +{ + if (checked) { + if (startX < endX) { + startX = startX + step; + } else { + startX = endX; + timer->stop(); + } + } else { + if (startX > endX) { + startX = startX - step; + } else { + startX = endX; + timer->stop(); + } + } + + update(); +} + +void SwitchControl::setChecked(bool checked) +{ + if (this->checked != checked) { + this->checked = checked; + emit checkedChanged(checked); + update(); + } +} +void SwitchControl::setCheckedStatus(bool checked) +{ + if (this->checked != checked) { + this->checked = checked; + + } + update(); + step = width() / 50; + //状态切换改变后自动计算终点坐标 + if (checked) { + if (buttonStyle == ButtonStyle_Rect) { + endX = width() - width() / 2; + } else if (buttonStyle == ButtonStyle_CircleIn) { + endX = width() - height(); + } else if (buttonStyle == ButtonStyle_CircleOut) { + endX = width() - height() + space; + } + } else { + endX = 0; + } + + timer->start(); + +} +void SwitchControl::setButtonStyle(SwitchControl::ButtonStyle buttonStyle) +{ + this->buttonStyle = buttonStyle; + update(); +} + +void SwitchControl::setBgColor(QColor bgColorOff, QColor bgColorOn) +{ + this->bgColorOff = bgColorOff; + this->bgColorOn = bgColorOn; + update(); +} + +void SwitchControl::setSliderColor(QColor sliderColorOff, QColor sliderColorOn) +{ + this->sliderColorOff = sliderColorOff; + this->sliderColorOn = sliderColorOn; + update(); +} + +void SwitchControl::setTextColor(QColor textColorOff, QColor textColorOn) +{ + this->textColorOff = textColorOff; + this->textColorOn = textColorOn; + update(); +} + +void SwitchControl::setText(QString textOff, QString textOn) +{ + this->textOff = textOff; + this->textOn = textOn; + update(); +} + +void SwitchControl::setImage(QString imageOff, QString imageOn) +{ + this->imageOff = imageOff; + this->imageOn = imageOn; + update(); +} + +void SwitchControl::setSpace(int space) +{ + this->space = space; + update(); +} + +void SwitchControl::setRectRadius(int rectRadius) +{ + this->rectRadius = rectRadius; + update(); +} +/*#include +#include + + +SwitchControl::SwitchControl(QWidget *parent) + : QWidget(parent) +{ + m_nHeight=16; + m_bChecked=false; + m_radius=8.0; + m_nMargin=5; + m_checkedColor=QColor(0, 150, 136); + m_thumbColor=Qt::white; + m_disabledColor=QColor(190, 190, 190); + m_background=Qt::black; + setAttribute(Qt::WA_DeleteOnClose); + // 鼠标滑过光标形状 - 手型 + setCursor(Qt::PointingHandCursor); + + // 连接信号槽 + connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimeout())); +} + +// 绘制开关 +void SwitchControl::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + + QPainter painter(this); + painter.setPen(Qt::NoPen); + painter.setRenderHint(QPainter::Antialiasing); + + QPainterPath path; + QColor background; + QColor thumbColor; + qreal dOpacity; + if (isEnabled()) { // 可用状态 + if (m_bChecked) { // 打开状态 + background = m_checkedColor; + thumbColor = m_checkedColor; + dOpacity = 0.600; + } else { //关闭状态 + background = m_background; + thumbColor = m_thumbColor; + dOpacity = 0.800; + } + } else { // 不可用状态 + background = m_background; + dOpacity = 0.260; + thumbColor = m_disabledColor; + } + // 绘制大椭圆 + painter.setBrush(background); + painter.setOpacity(dOpacity); + path.addRoundedRect(QRectF(m_nMargin, m_nMargin, width() - 2 * m_nMargin-(m_nHeight / 2), height() - 2 * m_nMargin), m_radius, m_radius); + painter.drawPath(path.simplified()); + + // 绘制小椭圆 + painter.setBrush(thumbColor); + painter.setOpacity(1.0); + painter.drawEllipse(QRectF(m_nX - (m_nHeight / 2), m_nY - (m_nHeight / 2), height(), height())); +} + +// 鼠标按下事件 +void SwitchControl::mousePressEvent(QMouseEvent *event) +{ + if (isEnabled()) { + if (event->buttons() & Qt::LeftButton) { + event->accept(); + } else { + event->ignore(); + } + } +} + +// 鼠标释放事件 - 切换开关状态、发射toggled()信号 +void SwitchControl::mouseReleaseEvent(QMouseEvent *event) +{ + if (isEnabled()) { + if ((event->type() == QMouseEvent::MouseButtonRelease) && (event->button() == Qt::LeftButton)) { + event->accept(); + m_bChecked = !m_bChecked; + emit toggled(m_bChecked); + m_timer.start(10); + } else { + event->ignore(); + } + } +} + +// 大小改变事件 +void SwitchControl::resizeEvent(QResizeEvent *event) +{ + m_nX = m_nHeight / 2; + m_nY = m_nHeight / 2; + QWidget::resizeEvent(event); +} + +// 默认大小 +QSize SwitchControl::sizeHint() const +{ + return minimumSizeHint(); +} + +// 最小大小 +QSize SwitchControl::minimumSizeHint() const +{ + return QSize(2 * (m_nHeight + m_nMargin), m_nHeight + 2 * m_nMargin); +} + +// 切换状态 - 滑动 +void SwitchControl::onTimeout() +{ + if (m_bChecked) { + m_nX += 1; + if (m_nX >= width() - m_nHeight*2) + m_timer.stop(); + } else { + m_nX -= 1; + if (m_nX <= m_nHeight / 2) + m_timer.stop(); + } + update(); +} + +// 返回开关状态 - 打开:true 关闭:false +bool SwitchControl::isToggled() const +{ + return m_bChecked; +} + +// 设置开关状态 +void SwitchControl::setToggle(bool checked) +{ + m_bChecked = checked; + m_timer.start(10); +} + +// 设置背景颜色 +void SwitchControl::setBackgroundColor(QColor color) +{ + m_background = color; +} +// 设置拇指颜色 +void SwitchControl::setthumbColor(QColor color) +{ + //拇指颜色 + m_thumbColor = color; +} + +// 设置选中颜色 +void SwitchControl::setCheckedColor(QColor color) +{ + m_checkedColor = color; +} + +// 设置不可用颜色 +void SwitchControl::setDisbaledColor(QColor color) +{ + m_disabledColor = color; +} +*/ diff --git a/LedOK/base/switchcontrol.h b/LedOK/base/switchcontrol.h index e65a198..88dd274 100644 --- a/LedOK/base/switchcontrol.h +++ b/LedOK/base/switchcontrol.h @@ -1,230 +1,230 @@ -#ifndef SWITCHCONTROL_H -#define SWITCHCONTROL_H -/** - * 作者:feiyangqingyun(QQ:517216493) 2016-11-6 - * 1:可设置开关按钮的样式 圆角矩形/内圆形/外圆形/图片 - * 2:可设置选中和未选中时的背景颜色 - * 3:可设置选中和未选中时的滑块颜色 - * 4:可设置显示的文本 - * 5:可设置滑块离背景的间隔 - * 6:可设置圆角角度 - */ - -#include - -class QTimer; - -class SwitchControl: public QWidget -{ - Q_OBJECT -public: - enum ButtonStyle { - ButtonStyle_Rect = 0, //圆角矩形 - ButtonStyle_CircleIn = 1, //内圆形 - ButtonStyle_CircleOut = 2,//外圆形 - ButtonStyle_Image = 3 //图片 - }; - - SwitchControl(QWidget *parent = 0); - ~SwitchControl(); - -protected: - void mousePressEvent(QMouseEvent *); - void resizeEvent(QResizeEvent *); - void paintEvent(QPaintEvent *); - void drawBg(QPainter *painter); - void drawSlider(QPainter *painter); - void drawText(QPainter *painter); - void drawImage(QPainter *painter); - -private: - bool checked; //是否选中 - ButtonStyle buttonStyle; //开关按钮样式 - - QColor bgColorOff; //关闭时背景颜色 - QColor bgColorOn; //打开时背景颜色 - - QColor sliderColorOff; //关闭时滑块颜色 - QColor sliderColorOn; //打开时滑块颜色 - - QColor textColorOff; //关闭时文本颜色 - QColor textColorOn; //打开时文本颜色 - - QString textOff; //关闭时显示的文字 - QString textOn; //打开时显示的文字 - - QString imageOff; //关闭时显示的图片 - QString imageOn; //打开时显示的图片 - - int space; //滑块离背景间隔 - int rectRadius; //圆角角度 - - int step; //每次移动的步长 - int startX; //滑块开始X轴坐标 - int endX; //滑块结束X轴坐标 - QTimer *timer; //定时器绘制 - -private slots: - void updateValue(); - -public: - bool getChecked()const - { - return checked; - } - ButtonStyle getButtonStyle()const - { - return buttonStyle; - } - - QColor getBgColorOff()const - { - return bgColorOff; - } - QColor getBgColorOn()const - { - return bgColorOn; - } - - QColor getSliderColorOff()const - { - return sliderColorOff; - } - QColor getSliderColorOn()const - { - return sliderColorOn; - } - - QColor getTextColorOff()const - { - return textColorOff; - } - QColor getTextColorOn()const - { - return textColorOn; - } - - QString getTextOff()const - { - return textOff; - } - QString getTextOn()const - { - return textOn; - } - - QString getImageOff()const - { - return imageOff; - } - QString getImageOn()const - { - return imageOn; - } - - int getSpace()const - { - return space; - } - int getRectRadius()const - { - return rectRadius; - } - -public slots: - //设置是否选中 - void setChecked(bool checked); - void setCheckedStatus(bool checked); - //设置风格样式 - void setButtonStyle(ButtonStyle buttonStyle); - - //设置背景颜色 - void setBgColor(QColor bgColorOff, QColor bgColorOn); - //设置滑块颜色 - void setSliderColor(QColor sliderColorOff, QColor sliderColorOn); - //设置文本颜色 - void setTextColor(QColor textColorOff, QColor textColorOn); - - //设置文本 - void setText(QString textOff, QString textOn); - - //设置背景图片 - void setImage(QString imageOff, QString imageOn); - - //设置间隔 - void setSpace(int space); - //设置圆角角度 - void setRectRadius(int rectRadius); - -signals: - void checkedChanged(bool checked); -}; - -/* -#include -#include - -class SwitchControl : public QWidget -{ - Q_OBJECT - -public: - explicit SwitchControl(QWidget *parent = nullptr); - - // 返回开关状态 - 打开:true 关闭:false - bool isToggled() const; - - // 设置开关状态 - void setToggle(bool checked); - - // 设置背景颜色 - void setBackgroundColor(QColor color); - - // 设置选中颜色 - void setCheckedColor(QColor color); - - // 设置不可用颜色 - void setDisbaledColor(QColor color); - // 设置拇指颜色 - void setthumbColor(QColor color); -protected: - // 绘制开关 - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; - - // 鼠标按下事件 - void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; - - // 鼠标释放事件 - 切换开关状态、发射toggled()信号 - void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; - - // 大小改变事件 - void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; - - // 缺省大小 - QSize sizeHint() const Q_DECL_OVERRIDE; - QSize minimumSizeHint() const Q_DECL_OVERRIDE; - -signals: - // 状态改变时,发射信号 - void toggled(bool checked); - -private slots: - // 状态切换时,用于产生滑动效果 - void onTimeout(); - -private: - bool m_bChecked=false; //是否选中 - QColor m_background; //背景颜色 - QColor m_checkedColor; //选中颜色 - QColor m_disabledColor; //不可用颜色 - QColor m_thumbColor; //拇指颜色 - qreal m_radius; //圆角 - qreal m_nX; //x点坐标 - qreal m_nY; //y点坐标 - qint16 m_nHeight=20; //高度 - qint16 m_nMargin=5; //外边距 - QTimer m_timer; //定时器 - -};*/ - -#endif // SWITCHCONTROL_H +#ifndef SWITCHCONTROL_H +#define SWITCHCONTROL_H +/** + * 作者:feiyangqingyun(QQ:517216493) 2016-11-6 + * 1:可设置开关按钮的样式 圆角矩形/内圆形/外圆形/图片 + * 2:可设置选中和未选中时的背景颜色 + * 3:可设置选中和未选中时的滑块颜色 + * 4:可设置显示的文本 + * 5:可设置滑块离背景的间隔 + * 6:可设置圆角角度 + */ + +#include + +class QTimer; + +class SwitchControl: public QWidget +{ + Q_OBJECT +public: + enum ButtonStyle { + ButtonStyle_Rect = 0, //圆角矩形 + ButtonStyle_CircleIn = 1, //内圆形 + ButtonStyle_CircleOut = 2,//外圆形 + ButtonStyle_Image = 3 //图片 + }; + + SwitchControl(QWidget *parent = 0); + ~SwitchControl(); + +protected: + void mousePressEvent(QMouseEvent *); + void resizeEvent(QResizeEvent *); + void paintEvent(QPaintEvent *); + void drawBg(QPainter *painter); + void drawSlider(QPainter *painter); + void drawText(QPainter *painter); + void drawImage(QPainter *painter); + +private: + bool checked; //是否选中 + ButtonStyle buttonStyle; //开关按钮样式 + + QColor bgColorOff; //关闭时背景颜色 + QColor bgColorOn; //打开时背景颜色 + + QColor sliderColorOff; //关闭时滑块颜色 + QColor sliderColorOn; //打开时滑块颜色 + + QColor textColorOff; //关闭时文本颜色 + QColor textColorOn; //打开时文本颜色 + + QString textOff; //关闭时显示的文字 + QString textOn; //打开时显示的文字 + + QString imageOff; //关闭时显示的图片 + QString imageOn; //打开时显示的图片 + + int space; //滑块离背景间隔 + int rectRadius; //圆角角度 + + int step; //每次移动的步长 + int startX; //滑块开始X轴坐标 + int endX; //滑块结束X轴坐标 + QTimer *timer; //定时器绘制 + +private slots: + void updateValue(); + +public: + bool getChecked()const + { + return checked; + } + ButtonStyle getButtonStyle()const + { + return buttonStyle; + } + + QColor getBgColorOff()const + { + return bgColorOff; + } + QColor getBgColorOn()const + { + return bgColorOn; + } + + QColor getSliderColorOff()const + { + return sliderColorOff; + } + QColor getSliderColorOn()const + { + return sliderColorOn; + } + + QColor getTextColorOff()const + { + return textColorOff; + } + QColor getTextColorOn()const + { + return textColorOn; + } + + QString getTextOff()const + { + return textOff; + } + QString getTextOn()const + { + return textOn; + } + + QString getImageOff()const + { + return imageOff; + } + QString getImageOn()const + { + return imageOn; + } + + int getSpace()const + { + return space; + } + int getRectRadius()const + { + return rectRadius; + } + +public slots: + //设置是否选中 + void setChecked(bool checked); + void setCheckedStatus(bool checked); + //设置风格样式 + void setButtonStyle(ButtonStyle buttonStyle); + + //设置背景颜色 + void setBgColor(QColor bgColorOff, QColor bgColorOn); + //设置滑块颜色 + void setSliderColor(QColor sliderColorOff, QColor sliderColorOn); + //设置文本颜色 + void setTextColor(QColor textColorOff, QColor textColorOn); + + //设置文本 + void setText(QString textOff, QString textOn); + + //设置背景图片 + void setImage(QString imageOff, QString imageOn); + + //设置间隔 + void setSpace(int space); + //设置圆角角度 + void setRectRadius(int rectRadius); + +signals: + void checkedChanged(bool checked); +}; + +/* +#include +#include + +class SwitchControl : public QWidget +{ + Q_OBJECT + +public: + explicit SwitchControl(QWidget *parent = nullptr); + + // 返回开关状态 - 打开:true 关闭:false + bool isToggled() const; + + // 设置开关状态 + void setToggle(bool checked); + + // 设置背景颜色 + void setBackgroundColor(QColor color); + + // 设置选中颜色 + void setCheckedColor(QColor color); + + // 设置不可用颜色 + void setDisbaledColor(QColor color); + // 设置拇指颜色 + void setthumbColor(QColor color); +protected: + // 绘制开关 + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; + + // 鼠标按下事件 + void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + + // 鼠标释放事件 - 切换开关状态、发射toggled()信号 + void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + + // 大小改变事件 + void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; + + // 缺省大小 + QSize sizeHint() const Q_DECL_OVERRIDE; + QSize minimumSizeHint() const Q_DECL_OVERRIDE; + +signals: + // 状态改变时,发射信号 + void toggled(bool checked); + +private slots: + // 状态切换时,用于产生滑动效果 + void onTimeout(); + +private: + bool m_bChecked=false; //是否选中 + QColor m_background; //背景颜色 + QColor m_checkedColor; //选中颜色 + QColor m_disabledColor; //不可用颜色 + QColor m_thumbColor; //拇指颜色 + qreal m_radius; //圆角 + qreal m_nX; //x点坐标 + qreal m_nY; //y点坐标 + qint16 m_nHeight=20; //高度 + qint16 m_nMargin=5; //外边距 + QTimer m_timer; //定时器 + +};*/ + +#endif // SWITCHCONTROL_H diff --git a/LedOK/base/table.cpp b/LedOK/base/table.cpp deleted file mode 100644 index d2392db..0000000 --- a/LedOK/base/table.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "table.h" - -int Table::sizeHintForColumn(int column) const { - auto item = horizontalHeaderItem(column); - if(!item) return QTableWidget::sizeHintForColumn(column); - int width = item->data(0x99).toInt(); - if(!width) return QTableWidget::sizeHintForColumn(column); - auto header = horizontalHeader(); - if(header->sectionResizeMode(column)!=QHeaderView::ResizeToContents) return QTableWidget::sizeHintForColumn(column); - int colCnt = columnCount(); - int remainWidth = header->width(), stretchWidth = width; - for(int cc=0; ccsectionResizeMode(cc)==QHeaderView::ResizeToContents) stretchWidth += item->data(0x99).toInt(); - else remainWidth -= item->data(0x99).toInt(); - } - if(remainWidth<=0) return QTableWidget::sizeHintForColumn(column); - return width * remainWidth / stretchWidth; -} diff --git a/LedOK/base/table.h b/LedOK/base/table.h deleted file mode 100644 index dce2383..0000000 --- a/LedOK/base/table.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef TABLE_H -#define TABLE_H - -#include -#include - -struct ColAttr { - QString field; - QString text; - int width{0}; -}; -class Table : public QTableWidget { - Q_OBJECT -public: - explicit Table(QWidget *parent = nullptr) : QTableWidget{parent} {} - Table(std::initializer_list colAttrs, QWidget *parent = nullptr) : QTableWidget{0, (int)colAttrs.size(), parent} { - int i = 0; - for(typename std::initializer_list::const_iterator it = colAttrs.begin(); it != colAttrs.end(); ++it) { - auto item = horizontalHeaderItem(i); - if(!item) { - item = new QTableWidgetItem(); - item->setData(0x99, it->width); - setHorizontalHeaderItem(i, item); - } - item->setText(it->text); - if(it->width>0) horizontalHeader()->resizeSection(i, it->width); - mFieldMap.insert(it->field, i++); - } - } - - Table *setDefs() { - setSelectionBehavior(QTableWidget::SelectRows); - setEditTriggers(QAbstractItemView::NoEditTriggers); - setAlternatingRowColors(true); - horizontalHeader()->setBackgroundRole(QPalette::Window); - return this; - } - - auto item(int row, QString column) { - auto col = mFieldMap[column]; - return QTableWidget::item(row, col); - } - void setItem(int row, QString column, QTableWidgetItem *item) { - auto col = mFieldMap[column]; - QTableWidget::setItem(row, col, item); - } - void setValue(int row, QString column, const QString &text) { - auto col = mFieldMap[column]; - QTableWidget::setItem(row, col, new QTableWidgetItem(text)); - } - - auto cellWidget(int row, QString column) { - auto col = mFieldMap[column]; - return QTableWidget::cellWidget(row, col); - } - void setCellWidget(int row, QString column, QWidget *widget) { - auto col = mFieldMap[column]; - QTableWidget::setCellWidget(row, col, widget); - } - - QMap mFieldMap; - -protected: - int sizeHintForColumn(int column) const override; -}; - -#endif // TABLE_H diff --git a/LedOK/base/taesclass.cpp b/LedOK/base/taesclass.cpp index 8bf19c6..74e385e 100644 --- a/LedOK/base/taesclass.cpp +++ b/LedOK/base/taesclass.cpp @@ -1,472 +1,472 @@ -#include "taesclass.h" - -Aes::~Aes() -{ - -} -Aes::Aes() -{ - -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//构造函数 -Aes::Aes(int keysize,unsigned char* keyBytes) -{ - SetNbNkNr(keysize); //设置密钥块数,轮数 - memcpy(key,keyBytes,keysize); //字符串拷贝函数,把keyBytes的keysize个字符复制到key中 - KeyExpansion(); //密钥扩展,必须提前做的初始化 -} -//////////////////////////////////////////////////////////////////////////////////////////////// -void Aes::SetNbNkNr(int keySize) -{ - Nb=4; - if(keySize==Bits128) - { - Nk=4; //4*4字节,128位密钥,10轮加密 - Nr=10; - } - else if(keySize==Bits192) - { - Nk=6; //6*4字节,192位密钥,12轮加密 - Nr=12; - } - else if(keySize==Bits256) - { - Nk=8; //8*4字节,256位密钥,14轮加密 - Nr=14; - } -} -//////////////////////////////////////////////////////////////////////////////////////////////// -void Aes::KeyExpansion() -{ - - memset(w,0,16*15); - for(int row=0;row 6 && (row % Nk == 4) ) //这个还没有搞清楚 - { - temp = SubWord(temp); - } - - // w[row] = w[row-Nk] xor temp - w[4*row+0] = (byte) ( (int) w[4*(row-Nk)+0] ^ (int)temp[0] ); - w[4*row+1] = (byte) ( (int) w[4*(row-Nk)+1] ^ (int)temp[1] ); - w[4*row+2] = (byte) ( (int) w[4*(row-Nk)+2] ^ (int)temp[2] ); - w[4*row+3] = (byte) ( (int) w[4*(row-Nk)+3] ^ (int)temp[3] ); - } // for loop - -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//密钥移位函数 -unsigned char* Aes::RotWord(unsigned char* word) -{ - byte* temp = new byte[4]; - temp[0] = word[1]; - temp[1] = word[2]; - temp[2] = word[3]; - temp[3] = word[0]; - return temp; -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//密钥字代换函数 -unsigned char* Aes::SubWord(unsigned char* word) -{ - byte* temp = new byte[4]; - for(int j=0;j<4;j++) - { - temp[j] = AesSbox[16*(word[j] >> 4)+(word[j] & 0x0f)]; //实际上也可以写成AesSbox[[j]];因为两者相等 - } - return temp; - -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//Aes加密函数 -void Aes::Cipher(unsigned char* input, unsigned char* output) -{ - memset(&State[0][0],0,16); - for(int i=0;i<4*Nb;i++) //这里是先写列后写行的,即输入是一列一列的进来的 - { - State[i%4][i/4]=input[i]; //换成先写行后写列也是可以的,只要在输出时也是这样就可以了 - } - AddRoundKey(0); //轮密钥加 - - for (int round = 1; round <= (Nr - 1); round++) // main round loop - { - SubBytes(); //字节代换 - ShiftRows(); //行移位 - MixColumns(); //列混淆 - AddRoundKey(round); //轮密钥加 - } // main round loop - - SubBytes(); //字节代换 - ShiftRows(); //行移位 - AddRoundKey(Nr); //轮密钥加 - - // output = state - for (int i = 0; i < (4 * Nb); i++) - { - output[i] = State[i % 4][ i / 4]; - } - -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//Aes解密函数 -void Aes::InvCipher(unsigned char* input,unsigned char* output) -{ - memset(&State[0][0],0,16); - for (int i = 0; i < (4 * Nb); i++) - { - State[i % 4][ i / 4] = input[i]; - } - - AddRoundKey(Nr); - - for (int round = Nr-1; round >= 1; round--) // main round loop - { - InvShiftRows(); - InvSubBytes(); - AddRoundKey(round); - InvMixColumns(); - } // end main round loop for InvCipher - - InvShiftRows(); - InvSubBytes(); - AddRoundKey(0); - - // output = state - for (int i = 0; i < (4 * Nb); i++) - { - output[i] = State[i % 4][ i / 4]; - } -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//轮密钥加 -void Aes::AddRoundKey(int round) -{ - int i,j; //i行 j列 //因为密钥w是一列一列排列的,即 k0 k4 k8 k12 - for(j=0;j<4;j++) // k1 k5 k9 k13 - { // k2 k6 k10k14 - for(i=0;i<4;i++) // k3 k7 k11k15 - { // 所以i行j列的下标是4*((round*4)+j)+i即16*round+4*j+i - State[i][j]=(unsigned char)((int)State[i][j]^(int)w[4*((round*4)+j)+i]); - } - } -} -//////////////////////////////////////////////////////////////////////////////////////////////// -//字节代换函数 -void Aes::SubBytes() //Page 103 -{ - int i,j; - for(j=0;j<4;j++) - { - for(i=0;i<4;i++) - { - State[i][j]=AesSbox[State[i][j]]; - //因为 16*(State[i][j]>>4)+State[i][j]&0x0f=State[i][j] - - - } - } -} - -void Aes::InvSubBytes() -{ - int i,j; - for(j=0;j<4;j++) - { - for(i=0;i<4;i++) - { - State[i][j]=AesiSbox[State[i][j]]; //因为 16*(State[i][j]>>4)+State[i][j]&0x0f=State[i][j] - } - } - -} -//////////////////////////////////////////////////////////////////////////////////////////////// -void Aes::ShiftRows() -{ - unsigned char temp[4*4]; //Page105 - int i,j; - for(j=0;j<4;j++) - { - for(i=0;i<4;i++) - { - temp[4*i+j]=State[i][j]; - } - } - for(i=1;i<4;i++) - { - for(j=0;j<4;j++) - { - if(i==1)State[i][j]=temp[4*i+(j+1)%4]; //第一行左移1位 - else if(i==2)State[i][j]=temp[4*i+(j+2)%4]; //第二行左移2位 - else if(i==3)State[i][j]=temp[4*i+(j+3)%4]; //第三行左移3位 - } - } - -} -void Aes::InvShiftRows() -{ - unsigned char temp[4*4]; - int i,j; - for(j=0;j<4;j++) - { - for(i=0;i<4;i++) - { - temp[4*i+j]=State[i][j]; - } - } - for(i=1;i<4;i++) - { - for(j=0;j<4;j++) - { - //if(i==1)State[i][j]=temp[4*i+(j-1)%4]; 在此犯了一个错误 -1%4=-1 而不是3,所以采用了下面再加一个4的做法 - if(i==1)State[i][j]=temp[4*i+(j+3)%4]; //第一行右移1位 j-1+4=j+3 - else if(i==2)State[i][j]=temp[4*i+(j+2)%4]; //第二行右移2位 j-2+4=j+2 - else if(i==3)State[i][j]=temp[4*i+(j+1)%4]; //第三行右移3位 j-3+4=j+2 - } - } - -} -//////////////////////////////////////////////////////////////////////////////////////////////// -void Aes::MixColumns() -{ - unsigned char temp[4*4]; - int i,j; - for(j=0;j<4;j++) //2 3 1 1 列混淆矩阵 Page107 - { //1 2 3 1 - for(i=0;i<4;i++) //1 1 2 3 - { //3 1 1 2 - temp[4*i+j]=State[i][j]; - } - } - for(j=0;j<4;j++) - { - State[0][j] = (unsigned char) ( (int)gfmultby02(temp[0+j]) ^ (int)gfmultby03(temp[4*1+j]) ^ - (int)gfmultby01(temp[4*2+j]) ^ (int)gfmultby01(temp[4*3+j]) ); - State[1][j] = (unsigned char) ( (int)gfmultby01(temp[0+j]) ^ (int)gfmultby02(temp[4*1+j]) ^ - (int)gfmultby03(temp[4*2+j]) ^ (int)gfmultby01(temp[4*3+j]) ); - State[2][j] = (unsigned char) ( (int)gfmultby01(temp[0+j]) ^ (int)gfmultby01(temp[4*1+j]) ^ - (int)gfmultby02(temp[4*2+j]) ^ (int)gfmultby03(temp[4*3+j]) ); - State[3][j] = (unsigned char) ( (int)gfmultby03(temp[0+j]) ^ (int)gfmultby01(temp[4*1+j]) ^ - (int)gfmultby01(temp[4*2+j]) ^ (int)gfmultby02(temp[4*3+j]) ); - } - -} -void Aes::InvMixColumns() -{ - unsigned char temp[4*4]; - int i,j; - for (i = 0; i < 4; i++) // copy State into temp[] - { - for (j = 0; j < 4; j++) //0e 0b 0d 09 逆变换矩阵 Page108 - { //09 0e 0b 0d - temp[4*i+j] = State[i][j]; //0d 09 0e 0b - } //0b 0d 09 0e - } - - for (j = 0; j < 4; j++) - { - State[0][j] = (unsigned char) ( (int)gfmultby0e(temp[j]) ^ (int)gfmultby0b(temp[4+j]) ^ - (int)gfmultby0d(temp[4*2+j]) ^ (int)gfmultby09(temp[4*3+j]) ); - State[1][j] = (unsigned char) ( (int)gfmultby09(temp[j]) ^ (int)gfmultby0e(temp[4+j]) ^ - (int)gfmultby0b(temp[4*2+j]) ^ (int)gfmultby0d(temp[4*3+j]) ); - State[2][j] = (unsigned char) ( (int)gfmultby0d(temp[j]) ^ (int)gfmultby09(temp[4+j]) ^ - (int)gfmultby0e(temp[4*2+j]) ^ (int)gfmultby0b(temp[4*3+j]) ); - State[3][j] = (unsigned char) ( (int)gfmultby0b(temp[j]) ^ (int)gfmultby0d(temp[4+j]) ^ - (int)gfmultby09(temp[4*2+j]) ^ (int)gfmultby0e(temp[4*3+j]) ); - } -} -//////////////////////////////////////////////////////////////////////////////////////////////// -unsigned char Aes::gfmultby01(unsigned char b) -{ - return b; -} -unsigned char Aes::gfmultby02(unsigned char b) -{ - if (b < 0x80) - return (unsigned char)(int)(b <<1); - else - return (unsigned char)( (int)(b << 1) ^ (int)(0x1b) ); -} - -unsigned char Aes::gfmultby03(unsigned char b) -{ - return (unsigned char) ( (int)gfmultby02(b) ^ (int)b ); -} - -unsigned char Aes::gfmultby09(unsigned char b) -{ - return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ (int)b ); -} - -unsigned char Aes::gfmultby0b(unsigned char b) -{ - return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ - (int)gfmultby02(b) ^ (int)b ); -} - -unsigned char Aes::gfmultby0d(unsigned char b) -{ - return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ - (int)gfmultby02(gfmultby02(b)) ^ (int)(b) ); -} - -unsigned char Aes::gfmultby0e(unsigned char b) -{ - return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ - (int)gfmultby02(gfmultby02(b)) ^(int)gfmultby02(b) ); -} - -TAesClass::TAesClass() -{ - m_lpAes=NULL; - InitializePrivateKey(16,(unsigned char*)"\x79\x76\x68\x6B\x77\x66\x6E\x68\x72\x65\x73\x63\x6C\x6B\x70\x6E"); -} - -TAesClass::~TAesClass() -{ - if (m_lpAes!=NULL) - { - delete m_lpAes; - } -} -//------------------------------------------------------------------------------------------------------------ -// 编写人员:wfnhddd -// -// 函数名称:InitializeAes -// -// 函数描述:初始化AES 密钥,密钥用于加密解密 -// -// 调用参数:详细说明参考 MSDN 中的相关描述或相关的开发文档 -// -// 返回数值:无 -// -// 最近修改:2009 年 08 月 07 日 -//------------------------------------------------------------------------------------------------------------ - - -VOID TAesClass::InitializePrivateKey(DWORD KeySize,UCHAR *KeyBytes) -{ - if (m_lpAes) - { - delete m_lpAes; - m_lpAes=NULL; - } - m_lpAes=new Aes(KeySize,KeyBytes); - -} - -//------------------------------------------------------------------------------------------------------------ -// 编写人员:wfnhddd -// -// 函数名称:OnAesEncrypt -// -// 函数描述:用AES加密算法加密数据 -// -// 调用参数:详细说明参考 MSDN 中的相关描述或相关的开发文档 -// -// 返回数值:加密后的数据大小 ,错误返回值 0 -// -// 最近修改:2009 年 08 月 07 日 -//------------------------------------------------------------------------------------------------------------ - -DWORD TAesClass::OnAesEncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer) -{ - DWORD OutLength=0; - if (m_lpAes==NULL||OutBuffer==NULL) - { - return 0; - } - - UCHAR *lpCurInBuff=(UCHAR *)InBuffer; - UCHAR *lpCurOutBuff=(UCHAR *)OutBuffer; - long blocknum=InLength/16; - long leftnum=InLength%16; - for(long i=0;iCipher(lpCurInBuff,lpCurOutBuff); - lpCurInBuff+=16; - lpCurOutBuff+=16; - OutLength+=16; - } - if(leftnum) //多余出leftnum 字节 则加密时 多出16-leftnum 个字节 - { - UCHAR inbuff[16]; - memset(inbuff,0,16); - memcpy(inbuff,lpCurInBuff,leftnum); - m_lpAes->Cipher(inbuff,lpCurOutBuff); - lpCurOutBuff+=16; - OutLength+=16; - } - //新增16个字节,用以确定增加的字节数 - UCHAR extrabuff[16]; - memset(extrabuff,0,16); - *((LPDWORD)extrabuff)=16+(16-leftnum)%16; //多出16+(16-leftnum)%16个字节 - m_lpAes->Cipher(extrabuff,lpCurOutBuff); - OutLength+=16; - return OutLength; - -} - - -//------------------------------------------------------------------------------------------------------------ -// 编写人员:wfnhddd -// -// 函数名称:OnAesUncrypt -// -// 函数描述:用AES加密算法解密数据 -// -// 调用参数:详细说明参考 MSDN 中的相关描述或相关的开发文档 -// -// 返回数值:解密后的数据大小 ,错误返回值 0 -// -// 最近修改:2009 年 08 月 07 日 -//------------------------------------------------------------------------------------------------------------ -DWORD TAesClass::OnAesUncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer) -{ - DWORD OutLength=0; - if (m_lpAes==NULL||OutBuffer==NULL) - { - return 0; - } - UCHAR *lpCurInBuff=(UCHAR *)InBuffer; - UCHAR *lpCurOutBuff=(UCHAR *)OutBuffer; - long blocknum=InLength/16; - long leftnum=InLength%16; - if(leftnum) - { - return 0; - } - for(long i=0;iInvCipher(lpCurInBuff,lpCurOutBuff); - lpCurInBuff+=16; - lpCurOutBuff+=16; - OutLength+=16; - } - - UCHAR *lpExtraInBuff=lpCurOutBuff-16; - DWORD dwExtraBytes=*((LPDWORD)lpExtraInBuff); - return (OutLength-dwExtraBytes); - -} +#include "taesclass.h" + +Aes::~Aes() +{ + +} +Aes::Aes() +{ + +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//构造函数 +Aes::Aes(int keysize,unsigned char* keyBytes) +{ + SetNbNkNr(keysize); //设置密钥块数,轮数 + memcpy(key,keyBytes,keysize); //字符串拷贝函数,把keyBytes的keysize个字符复制到key中 + KeyExpansion(); //密钥扩展,必须提前做的初始化 +} +//////////////////////////////////////////////////////////////////////////////////////////////// +void Aes::SetNbNkNr(int keySize) +{ + Nb=4; + if(keySize==Bits128) + { + Nk=4; //4*4字节,128位密钥,10轮加密 + Nr=10; + } + else if(keySize==Bits192) + { + Nk=6; //6*4字节,192位密钥,12轮加密 + Nr=12; + } + else if(keySize==Bits256) + { + Nk=8; //8*4字节,256位密钥,14轮加密 + Nr=14; + } +} +//////////////////////////////////////////////////////////////////////////////////////////////// +void Aes::KeyExpansion() +{ + + memset(w,0,16*15); + for(int row=0;row 6 && (row % Nk == 4) ) //这个还没有搞清楚 + { + temp = SubWord(temp); + } + + // w[row] = w[row-Nk] xor temp + w[4*row+0] = (byte) ( (int) w[4*(row-Nk)+0] ^ (int)temp[0] ); + w[4*row+1] = (byte) ( (int) w[4*(row-Nk)+1] ^ (int)temp[1] ); + w[4*row+2] = (byte) ( (int) w[4*(row-Nk)+2] ^ (int)temp[2] ); + w[4*row+3] = (byte) ( (int) w[4*(row-Nk)+3] ^ (int)temp[3] ); + } // for loop + +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//密钥移位函数 +unsigned char* Aes::RotWord(unsigned char* word) +{ + byte* temp = new byte[4]; + temp[0] = word[1]; + temp[1] = word[2]; + temp[2] = word[3]; + temp[3] = word[0]; + return temp; +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//密钥字代换函数 +unsigned char* Aes::SubWord(unsigned char* word) +{ + byte* temp = new byte[4]; + for(int j=0;j<4;j++) + { + temp[j] = AesSbox[16*(word[j] >> 4)+(word[j] & 0x0f)]; //实际上也可以写成AesSbox[[j]];因为两者相等 + } + return temp; + +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//Aes加密函数 +void Aes::Cipher(unsigned char* input, unsigned char* output) +{ + memset(&State[0][0],0,16); + for(int i=0;i<4*Nb;i++) //这里是先写列后写行的,即输入是一列一列的进来的 + { + State[i%4][i/4]=input[i]; //换成先写行后写列也是可以的,只要在输出时也是这样就可以了 + } + AddRoundKey(0); //轮密钥加 + + for (int round = 1; round <= (Nr - 1); round++) // main round loop + { + SubBytes(); //字节代换 + ShiftRows(); //行移位 + MixColumns(); //列混淆 + AddRoundKey(round); //轮密钥加 + } // main round loop + + SubBytes(); //字节代换 + ShiftRows(); //行移位 + AddRoundKey(Nr); //轮密钥加 + + // output = state + for (int i = 0; i < (4 * Nb); i++) + { + output[i] = State[i % 4][ i / 4]; + } + +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//Aes解密函数 +void Aes::InvCipher(unsigned char* input,unsigned char* output) +{ + memset(&State[0][0],0,16); + for (int i = 0; i < (4 * Nb); i++) + { + State[i % 4][ i / 4] = input[i]; + } + + AddRoundKey(Nr); + + for (int round = Nr-1; round >= 1; round--) // main round loop + { + InvShiftRows(); + InvSubBytes(); + AddRoundKey(round); + InvMixColumns(); + } // end main round loop for InvCipher + + InvShiftRows(); + InvSubBytes(); + AddRoundKey(0); + + // output = state + for (int i = 0; i < (4 * Nb); i++) + { + output[i] = State[i % 4][ i / 4]; + } +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//轮密钥加 +void Aes::AddRoundKey(int round) +{ + int i,j; //i行 j列 //因为密钥w是一列一列排列的,即 k0 k4 k8 k12 + for(j=0;j<4;j++) // k1 k5 k9 k13 + { // k2 k6 k10k14 + for(i=0;i<4;i++) // k3 k7 k11k15 + { // 所以i行j列的下标是4*((round*4)+j)+i即16*round+4*j+i + State[i][j]=(unsigned char)((int)State[i][j]^(int)w[4*((round*4)+j)+i]); + } + } +} +//////////////////////////////////////////////////////////////////////////////////////////////// +//字节代换函数 +void Aes::SubBytes() //Page 103 +{ + int i,j; + for(j=0;j<4;j++) + { + for(i=0;i<4;i++) + { + State[i][j]=AesSbox[State[i][j]]; + //因为 16*(State[i][j]>>4)+State[i][j]&0x0f=State[i][j] + + + } + } +} + +void Aes::InvSubBytes() +{ + int i,j; + for(j=0;j<4;j++) + { + for(i=0;i<4;i++) + { + State[i][j]=AesiSbox[State[i][j]]; //因为 16*(State[i][j]>>4)+State[i][j]&0x0f=State[i][j] + } + } + +} +//////////////////////////////////////////////////////////////////////////////////////////////// +void Aes::ShiftRows() +{ + unsigned char temp[4*4]; //Page105 + int i,j; + for(j=0;j<4;j++) + { + for(i=0;i<4;i++) + { + temp[4*i+j]=State[i][j]; + } + } + for(i=1;i<4;i++) + { + for(j=0;j<4;j++) + { + if(i==1)State[i][j]=temp[4*i+(j+1)%4]; //第一行左移1位 + else if(i==2)State[i][j]=temp[4*i+(j+2)%4]; //第二行左移2位 + else if(i==3)State[i][j]=temp[4*i+(j+3)%4]; //第三行左移3位 + } + } + +} +void Aes::InvShiftRows() +{ + unsigned char temp[4*4]; + int i,j; + for(j=0;j<4;j++) + { + for(i=0;i<4;i++) + { + temp[4*i+j]=State[i][j]; + } + } + for(i=1;i<4;i++) + { + for(j=0;j<4;j++) + { + //if(i==1)State[i][j]=temp[4*i+(j-1)%4]; 在此犯了一个错误 -1%4=-1 而不是3,所以采用了下面再加一个4的做法 + if(i==1)State[i][j]=temp[4*i+(j+3)%4]; //第一行右移1位 j-1+4=j+3 + else if(i==2)State[i][j]=temp[4*i+(j+2)%4]; //第二行右移2位 j-2+4=j+2 + else if(i==3)State[i][j]=temp[4*i+(j+1)%4]; //第三行右移3位 j-3+4=j+2 + } + } + +} +//////////////////////////////////////////////////////////////////////////////////////////////// +void Aes::MixColumns() +{ + unsigned char temp[4*4]; + int i,j; + for(j=0;j<4;j++) //2 3 1 1 列混淆矩阵 Page107 + { //1 2 3 1 + for(i=0;i<4;i++) //1 1 2 3 + { //3 1 1 2 + temp[4*i+j]=State[i][j]; + } + } + for(j=0;j<4;j++) + { + State[0][j] = (unsigned char) ( (int)gfmultby02(temp[0+j]) ^ (int)gfmultby03(temp[4*1+j]) ^ + (int)gfmultby01(temp[4*2+j]) ^ (int)gfmultby01(temp[4*3+j]) ); + State[1][j] = (unsigned char) ( (int)gfmultby01(temp[0+j]) ^ (int)gfmultby02(temp[4*1+j]) ^ + (int)gfmultby03(temp[4*2+j]) ^ (int)gfmultby01(temp[4*3+j]) ); + State[2][j] = (unsigned char) ( (int)gfmultby01(temp[0+j]) ^ (int)gfmultby01(temp[4*1+j]) ^ + (int)gfmultby02(temp[4*2+j]) ^ (int)gfmultby03(temp[4*3+j]) ); + State[3][j] = (unsigned char) ( (int)gfmultby03(temp[0+j]) ^ (int)gfmultby01(temp[4*1+j]) ^ + (int)gfmultby01(temp[4*2+j]) ^ (int)gfmultby02(temp[4*3+j]) ); + } + +} +void Aes::InvMixColumns() +{ + unsigned char temp[4*4]; + int i,j; + for (i = 0; i < 4; i++) // copy State into temp[] + { + for (j = 0; j < 4; j++) //0e 0b 0d 09 逆变换矩阵 Page108 + { //09 0e 0b 0d + temp[4*i+j] = State[i][j]; //0d 09 0e 0b + } //0b 0d 09 0e + } + + for (j = 0; j < 4; j++) + { + State[0][j] = (unsigned char) ( (int)gfmultby0e(temp[j]) ^ (int)gfmultby0b(temp[4+j]) ^ + (int)gfmultby0d(temp[4*2+j]) ^ (int)gfmultby09(temp[4*3+j]) ); + State[1][j] = (unsigned char) ( (int)gfmultby09(temp[j]) ^ (int)gfmultby0e(temp[4+j]) ^ + (int)gfmultby0b(temp[4*2+j]) ^ (int)gfmultby0d(temp[4*3+j]) ); + State[2][j] = (unsigned char) ( (int)gfmultby0d(temp[j]) ^ (int)gfmultby09(temp[4+j]) ^ + (int)gfmultby0e(temp[4*2+j]) ^ (int)gfmultby0b(temp[4*3+j]) ); + State[3][j] = (unsigned char) ( (int)gfmultby0b(temp[j]) ^ (int)gfmultby0d(temp[4+j]) ^ + (int)gfmultby09(temp[4*2+j]) ^ (int)gfmultby0e(temp[4*3+j]) ); + } +} +//////////////////////////////////////////////////////////////////////////////////////////////// +unsigned char Aes::gfmultby01(unsigned char b) +{ + return b; +} +unsigned char Aes::gfmultby02(unsigned char b) +{ + if (b < 0x80) + return (unsigned char)(int)(b <<1); + else + return (unsigned char)( (int)(b << 1) ^ (int)(0x1b) ); +} + +unsigned char Aes::gfmultby03(unsigned char b) +{ + return (unsigned char) ( (int)gfmultby02(b) ^ (int)b ); +} + +unsigned char Aes::gfmultby09(unsigned char b) +{ + return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ (int)b ); +} + +unsigned char Aes::gfmultby0b(unsigned char b) +{ + return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ + (int)gfmultby02(b) ^ (int)b ); +} + +unsigned char Aes::gfmultby0d(unsigned char b) +{ + return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ + (int)gfmultby02(gfmultby02(b)) ^ (int)(b) ); +} + +unsigned char Aes::gfmultby0e(unsigned char b) +{ + return (unsigned char)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ + (int)gfmultby02(gfmultby02(b)) ^(int)gfmultby02(b) ); +} + +TAesClass::TAesClass() +{ + m_lpAes=NULL; + InitializePrivateKey(16,(unsigned char*)"\x79\x76\x68\x6B\x77\x66\x6E\x68\x72\x65\x73\x63\x6C\x6B\x70\x6E"); +} + +TAesClass::~TAesClass() +{ + if (m_lpAes!=NULL) + { + delete m_lpAes; + } +} +//------------------------------------------------------------------------------------------------------------ +// 编写人员:wfnhddd +// +// 函数名称:InitializeAes +// +// 函数描述:初始化AES 密钥,密钥用于加密解密 +// +// 调用参数:详细说明参考 MSDN 中的相关描述或相关的开发文档 +// +// 返回数值:无 +// +// 最近修改:2009 年 08 月 07 日 +//------------------------------------------------------------------------------------------------------------ + + +VOID TAesClass::InitializePrivateKey(DWORD KeySize,UCHAR *KeyBytes) +{ + if (m_lpAes) + { + delete m_lpAes; + m_lpAes=NULL; + } + m_lpAes=new Aes(KeySize,KeyBytes); + +} + +//------------------------------------------------------------------------------------------------------------ +// 编写人员:wfnhddd +// +// 函数名称:OnAesEncrypt +// +// 函数描述:用AES加密算法加密数据 +// +// 调用参数:详细说明参考 MSDN 中的相关描述或相关的开发文档 +// +// 返回数值:加密后的数据大小 ,错误返回值 0 +// +// 最近修改:2009 年 08 月 07 日 +//------------------------------------------------------------------------------------------------------------ + +DWORD TAesClass::OnAesEncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer) +{ + DWORD OutLength=0; + if (m_lpAes==NULL||OutBuffer==NULL) + { + return 0; + } + + UCHAR *lpCurInBuff=(UCHAR *)InBuffer; + UCHAR *lpCurOutBuff=(UCHAR *)OutBuffer; + long blocknum=InLength/16; + long leftnum=InLength%16; + for(long i=0;iCipher(lpCurInBuff,lpCurOutBuff); + lpCurInBuff+=16; + lpCurOutBuff+=16; + OutLength+=16; + } + if(leftnum) //多余出leftnum 字节 则加密时 多出16-leftnum 个字节 + { + UCHAR inbuff[16]; + memset(inbuff,0,16); + memcpy(inbuff,lpCurInBuff,leftnum); + m_lpAes->Cipher(inbuff,lpCurOutBuff); + lpCurOutBuff+=16; + OutLength+=16; + } + //新增16个字节,用以确定增加的字节数 + UCHAR extrabuff[16]; + memset(extrabuff,0,16); + *((LPDWORD)extrabuff)=16+(16-leftnum)%16; //多出16+(16-leftnum)%16个字节 + m_lpAes->Cipher(extrabuff,lpCurOutBuff); + OutLength+=16; + return OutLength; + +} + + +//------------------------------------------------------------------------------------------------------------ +// 编写人员:wfnhddd +// +// 函数名称:OnAesUncrypt +// +// 函数描述:用AES加密算法解密数据 +// +// 调用参数:详细说明参考 MSDN 中的相关描述或相关的开发文档 +// +// 返回数值:解密后的数据大小 ,错误返回值 0 +// +// 最近修改:2009 年 08 月 07 日 +//------------------------------------------------------------------------------------------------------------ +DWORD TAesClass::OnAesUncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer) +{ + DWORD OutLength=0; + if (m_lpAes==NULL||OutBuffer==NULL) + { + return 0; + } + UCHAR *lpCurInBuff=(UCHAR *)InBuffer; + UCHAR *lpCurOutBuff=(UCHAR *)OutBuffer; + long blocknum=InLength/16; + long leftnum=InLength%16; + if(leftnum) + { + return 0; + } + for(long i=0;iInvCipher(lpCurInBuff,lpCurOutBuff); + lpCurInBuff+=16; + lpCurOutBuff+=16; + OutLength+=16; + } + + UCHAR *lpExtraInBuff=lpCurOutBuff-16; + DWORD dwExtraBytes=*((LPDWORD)lpExtraInBuff); + return (OutLength-dwExtraBytes); + +} diff --git a/LedOK/base/taesclass.h b/LedOK/base/taesclass.h index 6d69cd1..0fdaeec 100644 --- a/LedOK/base/taesclass.h +++ b/LedOK/base/taesclass.h @@ -1,133 +1,133 @@ -#ifndef TAESCLASS_H -#define TAESCLASS_H -#include -#include -#include -#include - -typedef unsigned long DWORD; -typedef unsigned char UCHAR,*PUCHAR; -typedef void *PVOID,*LPVOID; -typedef unsigned char byte; -typedef DWORD *PDWORD,*LPDWORD; - -#ifndef VOID -#define VOID void -#endif - -//#pragma once - -//enum KeySize { Bits128, Bits192, Bits256 }; // key size, in bits, for construtor -#define Bits128 16 -#define Bits192 24 -#define Bits256 32 - -unsigned char AesSbox[16*16]= -{// populate the Sbox matrix - /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ - /*0*/ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - /*1*/ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - /*2*/ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - /*3*/ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - /*4*/ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - /*5*/ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - /*6*/ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - /*7*/ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - /*8*/ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - /*9*/ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - /*a*/ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - /*b*/ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - /*c*/ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - /*d*/ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - /*e*/ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - /*f*/ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 -}; - -unsigned char AesiSbox[16*16]= -{ - // populate the iSbox matrix - /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ - /*0*/ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, - /*1*/ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, - /*2*/ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, - /*3*/ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, - /*4*/ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, - /*5*/ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, - /*6*/ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, - /*7*/ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, - /*8*/ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, - /*9*/ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, - /*a*/ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, - /*b*/ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, - /*c*/ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, - /*d*/ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, - /*e*/ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, - /*f*/ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d -}; -unsigned char AesRcon[11*4]= -{ - 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, - 0x02, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, - 0x08, 0x00, 0x00, 0x00, - 0x10, 0x00, 0x00, 0x00, - 0x20, 0x00, 0x00, 0x00, - 0x40, 0x00, 0x00, 0x00, - 0x80, 0x00, 0x00, 0x00, - 0x1b, 0x00, 0x00, 0x00, - 0x36, 0x00, 0x00, 0x00 -}; - - -class Aes // Advanced Encryption Standard -{ -public: - ~Aes(); - Aes(); - Aes(int keySize, unsigned char* keyBytes); - unsigned char State[4][4]; - void Cipher(unsigned char* input, unsigned char* output); // encipher 16-bit input - void InvCipher(unsigned char* input, unsigned char* output); // decipher 16-bit input -private: - int Nb; // block size in 32-bit words. Always 4 for AES. (128 bits). - int Nk; // key size in 32-bit words. 4, 6, 8. (128, 192, 256 bits). - int Nr; // number of rounds. 10, 12, 14. - - unsigned char key[32]; - unsigned char w[16*15]; - - void SetNbNkNr(int keySize); - void AddRoundKey(int round); //轮密钥加 - void SubBytes(); //S盒字节代换 - void InvSubBytes(); //逆S盒字节代换 - void ShiftRows(); //行移位 - void InvShiftRows(); - void MixColumns(); //列混淆 - void InvMixColumns(); - unsigned char gfmultby01(unsigned char b); - unsigned char gfmultby02(unsigned char b); - unsigned char gfmultby03(unsigned char b); - unsigned char gfmultby09(unsigned char b); - unsigned char gfmultby0b(unsigned char b); - unsigned char gfmultby0d(unsigned char b); - unsigned char gfmultby0e(unsigned char b); - void KeyExpansion(); //密钥扩展 - unsigned char* SubWord(unsigned char* word); //密钥S盒字代换 - unsigned char* RotWord(unsigned char* word); //密钥移位 - -}; - -class TAesClass -{ -public: - TAesClass(); - ~TAesClass(); - void InitializePrivateKey(DWORD KeySize,UCHAR *KeyBytes); //AES 密钥初始化 - DWORD OnAesEncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 加密数据 - DWORD OnAesUncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 解密数据 -private: - Aes * m_lpAes; -}; - -#endif +#ifndef TAESCLASS_H +#define TAESCLASS_H +#include +#include +#include +#include + +typedef unsigned long DWORD; +typedef unsigned char UCHAR,*PUCHAR; +typedef void *PVOID,*LPVOID; +typedef unsigned char byte; +typedef DWORD *PDWORD,*LPDWORD; + +#ifndef VOID +#define VOID void +#endif + +//#pragma once + +//enum KeySize { Bits128, Bits192, Bits256 }; // key size, in bits, for construtor +#define Bits128 16 +#define Bits192 24 +#define Bits256 32 + +unsigned char AesSbox[16*16]= +{// populate the Sbox matrix + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + /*0*/ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + /*1*/ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + /*2*/ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + /*3*/ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + /*4*/ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + /*5*/ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + /*6*/ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + /*7*/ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + /*8*/ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + /*9*/ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + /*a*/ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + /*b*/ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + /*c*/ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + /*d*/ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + /*e*/ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + /*f*/ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 +}; + +unsigned char AesiSbox[16*16]= +{ + // populate the iSbox matrix + /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ + /*0*/ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + /*1*/ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + /*2*/ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + /*3*/ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + /*4*/ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + /*5*/ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + /*6*/ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + /*7*/ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + /*8*/ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + /*9*/ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + /*a*/ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + /*b*/ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + /*c*/ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + /*d*/ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + /*e*/ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + /*f*/ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d +}; +unsigned char AesRcon[11*4]= +{ + 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, + 0x08, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x00, 0x00, + 0x40, 0x00, 0x00, 0x00, + 0x80, 0x00, 0x00, 0x00, + 0x1b, 0x00, 0x00, 0x00, + 0x36, 0x00, 0x00, 0x00 +}; + + +class Aes // Advanced Encryption Standard +{ +public: + ~Aes(); + Aes(); + Aes(int keySize, unsigned char* keyBytes); + unsigned char State[4][4]; + void Cipher(unsigned char* input, unsigned char* output); // encipher 16-bit input + void InvCipher(unsigned char* input, unsigned char* output); // decipher 16-bit input +private: + int Nb; // block size in 32-bit words. Always 4 for AES. (128 bits). + int Nk; // key size in 32-bit words. 4, 6, 8. (128, 192, 256 bits). + int Nr; // number of rounds. 10, 12, 14. + + unsigned char key[32]; + unsigned char w[16*15]; + + void SetNbNkNr(int keySize); + void AddRoundKey(int round); //轮密钥加 + void SubBytes(); //S盒字节代换 + void InvSubBytes(); //逆S盒字节代换 + void ShiftRows(); //行移位 + void InvShiftRows(); + void MixColumns(); //列混淆 + void InvMixColumns(); + unsigned char gfmultby01(unsigned char b); + unsigned char gfmultby02(unsigned char b); + unsigned char gfmultby03(unsigned char b); + unsigned char gfmultby09(unsigned char b); + unsigned char gfmultby0b(unsigned char b); + unsigned char gfmultby0d(unsigned char b); + unsigned char gfmultby0e(unsigned char b); + void KeyExpansion(); //密钥扩展 + unsigned char* SubWord(unsigned char* word); //密钥S盒字代换 + unsigned char* RotWord(unsigned char* word); //密钥移位 + +}; + +class TAesClass +{ +public: + TAesClass(); + ~TAesClass(); + void InitializePrivateKey(DWORD KeySize,UCHAR *KeyBytes); //AES 密钥初始化 + DWORD OnAesEncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 加密数据 + DWORD OnAesUncrypt(LPVOID InBuffer,DWORD InLength,LPVOID OutBuffer); //AES 解密数据 +private: + Aes * m_lpAes; +}; + +#endif diff --git a/LedOK/base/updateledset3dialog.cpp b/LedOK/base/updateledset3dialog.cpp index 52665f9..494ca56 100644 --- a/LedOK/base/updateledset3dialog.cpp +++ b/LedOK/base/updateledset3dialog.cpp @@ -1,81 +1,81 @@ -#include "updateledset3dialog.h" -#include "ui_updateledset3dialog.h" -#include -#include - -extern const QString DEFS_LEDSET_URL = "https://www.ledok.cn/download/definitions/ledset3updates.json"; - -UpdateLedset3Dialog::UpdateLedset3Dialog(QWidget *parent) : - BaseDlg(parent), - ui(new Ui::UpdateLedset3Dialog) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - ui->pushButton_2->setVisible(false); - - QString strCurApkVersion=""; - QSettings settings; - strCurApkVersion = settings.value(DEFS_LEDSET_URL).toString(); - if(strCurApkVersion.isEmpty()) strCurApkVersion="0.0.0"; - strCurApkVersion="0.0.0"; - - ui->label_2->setText(tr("CurVersion")+":"+strCurApkVersion); - ui->label_2->setVisible(false); - - QSimpleUpdater *m_updater=QSimpleUpdater::getInstance(); - connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(OnCheckForUpdates())); - connect(m_updater,SIGNAL(checkingFinished(QString)),this,SLOT(updateChangelog(QString))); - connect(m_updater,SIGNAL(downloadFinished(QString,QString)),this,SLOT(OnDownloadFinished(QString,QString))); - - m_updater->getInstance()->setModuleVersion(DEFS_LEDSET_URL,strCurApkVersion); - m_updater->getInstance()->setNotifyOnUpdate(DEFS_LEDSET_URL,false); - m_updater->getInstance()->setNotifyOnFinish(DEFS_LEDSET_URL,false); - m_updater->getInstance()->setCompareBySameString(DEFS_LEDSET_URL,true); - m_updater->getInstance()->checkForUpdates(DEFS_LEDSET_URL); - ui->pushButton->setProperty("ssType", "progManageTool"); - ui->pushButton_2->setProperty("ssType", "progManageTool"); -} - -UpdateLedset3Dialog::~UpdateLedset3Dialog() -{ - delete ui; -} -void UpdateLedset3Dialog::OnDownloadFinished( QString url, QString filepath) -{ - ui->label_2->setText(tr("CurVersion")+":"+m_updater->getInstance()->getLatestVersion(DEFS_LEDSET_URL)); - ui->textEdit->setText(tr("Apk is download finished from internet,you can select LED Screen SYNC firmware now!")); - ui->pushButton_2->setVisible(false); - QSettings settings; - settings.setValue(url, m_strLastestVersion); - settings.setValue("ledset", filepath); -} - -void UpdateLedset3Dialog::OnCheckForUpdates() -{ - m_updater->getInstance()->setNotifyOnUpdate(DEFS_LEDSET_URL,true); - m_updater->getInstance()->setNotifyOnFinish(DEFS_LEDSET_URL,false); - // m_updater->getInstance()->setUseCustomInstallProcedures(DEFS_LEDSET_URL,true); - m_updater->getInstance()->setNoNotifyDownload(DEFS_LEDSET_URL,true); - m_updater->getInstance()->setCompareBySameString(DEFS_LEDSET_URL,true); - m_updater->getInstance()->setMandatoryUpdate(DEFS_LEDSET_URL,false); - m_updater->getInstance()->checkForUpdates(DEFS_LEDSET_URL); - -} -void UpdateLedset3Dialog::updateChangelog(QString strTip) -{ - Q_UNUSED(strTip) - - if(m_updater->getInstance()->getUpdateAvailable(DEFS_LEDSET_URL)) - { - QString strtip=tr("LatestVersion:"); - m_strLastestVersion=m_updater->getInstance()->getLatestVersion(DEFS_LEDSET_URL); - strtip+= m_strLastestVersion +"\r\n"; - strtip+= tr("Update log:")+"\r\n"+m_updater->getInstance()->getChangelog (DEFS_LEDSET_URL) ; - ui->textEdit->setText(strtip); - ui->pushButton_2->setVisible(true); - } - else { - ui->textEdit->setText(tr("The current version is already the latest version,,you can select LED Screen SYNC firmware now!")); - } - disconnect(m_updater,SIGNAL(checkingFinished(QString)),this,SLOT(updateChangelog(QString))); -} +#include "updateledset3dialog.h" +#include "ui_updateledset3dialog.h" +#include +#include + +extern const QString DEFS_LEDSET_URL = "https://www.ledok.cn/download/definitions/ledset3updates.json"; + +UpdateLedset3Dialog::UpdateLedset3Dialog(QWidget *parent) : + BaseDlg(parent), + ui(new Ui::UpdateLedset3Dialog) +{ + setAttribute(Qt::WA_DeleteOnClose); + ui->setupUi(this); + ui->pushButton_2->setVisible(false); + + QString strCurApkVersion=""; + QSettings settings; + strCurApkVersion = settings.value(DEFS_LEDSET_URL).toString(); + if(strCurApkVersion.isEmpty()) strCurApkVersion="0.0.0"; + strCurApkVersion="0.0.0"; + + ui->label_2->setText(tr("CurVersion")+":"+strCurApkVersion); + ui->label_2->setVisible(false); + + QSimpleUpdater *m_updater=QSimpleUpdater::getInstance(); + connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(OnCheckForUpdates())); + connect(m_updater,SIGNAL(checkingFinished(QString)),this,SLOT(updateChangelog(QString))); + connect(m_updater,SIGNAL(downloadFinished(QString,QString)),this,SLOT(OnDownloadFinished(QString,QString))); + + m_updater->getInstance()->setModuleVersion(DEFS_LEDSET_URL,strCurApkVersion); + m_updater->getInstance()->setNotifyOnUpdate(DEFS_LEDSET_URL,false); + m_updater->getInstance()->setNotifyOnFinish(DEFS_LEDSET_URL,false); + m_updater->getInstance()->setCompareBySameString(DEFS_LEDSET_URL,true); + m_updater->getInstance()->checkForUpdates(DEFS_LEDSET_URL); + ui->pushButton->setProperty("ssType", "progManageTool"); + ui->pushButton_2->setProperty("ssType", "progManageTool"); +} + +UpdateLedset3Dialog::~UpdateLedset3Dialog() +{ + delete ui; +} +void UpdateLedset3Dialog::OnDownloadFinished( QString url, QString filepath) +{ + ui->label_2->setText(tr("CurVersion")+":"+m_updater->getInstance()->getLatestVersion(DEFS_LEDSET_URL)); + ui->textEdit->setText(tr("Apk is download finished from internet,you can select LED Screen SYNC firmware now!")); + ui->pushButton_2->setVisible(false); + QSettings settings; + settings.setValue(url, m_strLastestVersion); + settings.setValue("ledset", filepath); +} + +void UpdateLedset3Dialog::OnCheckForUpdates() +{ + m_updater->getInstance()->setNotifyOnUpdate(DEFS_LEDSET_URL,true); + m_updater->getInstance()->setNotifyOnFinish(DEFS_LEDSET_URL,false); + // m_updater->getInstance()->setUseCustomInstallProcedures(DEFS_LEDSET_URL,true); + m_updater->getInstance()->setNoNotifyDownload(DEFS_LEDSET_URL,true); + m_updater->getInstance()->setCompareBySameString(DEFS_LEDSET_URL,true); + m_updater->getInstance()->setMandatoryUpdate(DEFS_LEDSET_URL,false); + m_updater->getInstance()->checkForUpdates(DEFS_LEDSET_URL); + +} +void UpdateLedset3Dialog::updateChangelog(QString strTip) +{ + Q_UNUSED(strTip) + + if(m_updater->getInstance()->getUpdateAvailable(DEFS_LEDSET_URL)) + { + QString strtip=tr("LatestVersion:"); + m_strLastestVersion=m_updater->getInstance()->getLatestVersion(DEFS_LEDSET_URL); + strtip+= m_strLastestVersion +"\r\n"; + strtip+= tr("Update log:")+"\r\n"+m_updater->getInstance()->getChangelog (DEFS_LEDSET_URL) ; + ui->textEdit->setText(strtip); + ui->pushButton_2->setVisible(true); + } + else { + ui->textEdit->setText(tr("The current version is already the latest version,,you can select LED Screen SYNC firmware now!")); + } + disconnect(m_updater,SIGNAL(checkingFinished(QString)),this,SLOT(updateChangelog(QString))); +} diff --git a/LedOK/base/updateledset3dialog.h b/LedOK/base/updateledset3dialog.h index 2458b2c..716a9f4 100644 --- a/LedOK/base/updateledset3dialog.h +++ b/LedOK/base/updateledset3dialog.h @@ -1,30 +1,30 @@ -#ifndef UPDATELEDSET3DIALOG_H -#define UPDATELEDSET3DIALOG_H - -#include -#include - -namespace Ui { -class UpdateLedset3Dialog; -} - -class UpdateLedset3Dialog : public BaseDlg -{ - Q_OBJECT - -public: - explicit UpdateLedset3Dialog(QWidget *parent = nullptr); - ~UpdateLedset3Dialog(); - -private: - Ui::UpdateLedset3Dialog *ui; - QSimpleUpdater *m_updater; - QString m_strLastestVersion=""; -protected slots: - void OnCheckForUpdates() ; - void updateChangelog(QString); - void OnDownloadFinished( QString url, QString filepath); - -}; - -#endif // UPDATELEDSET3DIALOG_H +#ifndef UPDATELEDSET3DIALOG_H +#define UPDATELEDSET3DIALOG_H + +#include +#include + +namespace Ui { +class UpdateLedset3Dialog; +} + +class UpdateLedset3Dialog : public BaseDlg +{ + Q_OBJECT + +public: + explicit UpdateLedset3Dialog(QWidget *parent = nullptr); + ~UpdateLedset3Dialog(); + +private: + Ui::UpdateLedset3Dialog *ui; + QSimpleUpdater *m_updater; + QString m_strLastestVersion=""; +protected slots: + void OnCheckForUpdates() ; + void updateChangelog(QString); + void OnDownloadFinished( QString url, QString filepath); + +}; + +#endif // UPDATELEDSET3DIALOG_H diff --git a/LedOK/base/updateledset3dialog.ui b/LedOK/base/updateledset3dialog.ui index 86c3828..1ddf1e9 100644 --- a/LedOK/base/updateledset3dialog.ui +++ b/LedOK/base/updateledset3dialog.ui @@ -1,204 +1,204 @@ - - - UpdateLedset3Dialog - - - - 0 - 0 - 381 - 272 - - - - - - 0 - 0 - 382 - 275 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - 0 - - - - - LedSet3.0 Update - - - Qt::AlignCenter - - - - - - - - 30 - 24 - - - - X - - - - - - - - - border-top: 2px solid gray; - - - Qt::Horizontal - - - - - - - - - - - - 0 - 0 - - - - - 64 - 64 - - - - image: url(:/res/ledset.png); - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - 0 - 0 - - - - - 14 - - - - V1.0.0 - - - Qt::AlignCenter - - - - - - - true - - - - - - - - 0 - 0 - - - - - 80 - 0 - - - - - 80 - 16777215 - - - - Update - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - pushButton - clicked() - UpdateLedset3Dialog - close() - - - 355 - 22 - - - 190 - 135 - - - - - + + + UpdateLedset3Dialog + + + + 0 + 0 + 381 + 272 + + + + + + 0 + 0 + 382 + 275 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 0 + + + + + LedSet3.0 Update + + + Qt::AlignCenter + + + + + + + + 30 + 24 + + + + X + + + + + + + + + border-top: 2px solid gray; + + + Qt::Horizontal + + + + + + + + + + + + 0 + 0 + + + + + 64 + 64 + + + + image: url(:/res/ledset.png); + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + 0 + 0 + + + + + 14 + + + + V1.0.0 + + + Qt::AlignCenter + + + + + + + true + + + + + + + + 0 + 0 + + + + + 80 + 0 + + + + + 80 + 16777215 + + + + Update + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + pushButton + clicked() + UpdateLedset3Dialog + close() + + + 355 + 22 + + + 190 + 135 + + + + + diff --git a/LedOK/base/updaterdialog.cpp b/LedOK/base/updaterdialog.cpp deleted file mode 100644 index 23a1b46..0000000 --- a/LedOK/base/updaterdialog.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "updaterdialog.h" -#include "cfg.h" -#include "ui_updaterdialog.h" - -UpdaterDialog::UpdaterDialog(QWidget *parent) : BaseDlg(parent), ui(new Ui::UpdaterDialog) { - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - ui->pushButton_2->setVisible(false); - ui->label_2->setText(tr("CurVersion")+":"+APP_VERSION); - QSimpleUpdater *m_updater = QSimpleUpdater::getInstance(); - connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(OnCheckForUpdates())); - connect(m_updater, SIGNAL(checkingFinished(QString)), this, SLOT(updateChangelog(QString))); - m_updater->setModuleVersion(UpdVerUrl, APP_VERSION); - m_updater->setNotifyOnUpdate(UpdVerUrl, false); - m_updater->setNotifyOnFinish(UpdVerUrl, false); - m_updater->checkForUpdates(UpdVerUrl); -} - -UpdaterDialog::~UpdaterDialog(){ - delete ui; -} -void UpdaterDialog::OnCheckForUpdates(){ - QSimpleUpdater::getInstance()->setNotifyOnUpdate(UpdVerUrl, true); - QSimpleUpdater::getInstance()->setNotifyOnFinish(UpdVerUrl, false); - QSimpleUpdater::getInstance()->setMandatoryUpdate(UpdVerUrl, true); - QSimpleUpdater::getInstance()->checkForUpdates(UpdVerUrl); -} -void UpdaterDialog::updateChangelog(QString){ - if(QSimpleUpdater::getInstance()->getUpdateAvailable(UpdVerUrl)){ - QString strtip = tr("LatestVersion:") + QSimpleUpdater::getInstance()->getLatestVersion(UpdVerUrl) + "\r\n" - + tr("Update log:") + "\r\n" + QSimpleUpdater::getInstance()->getChangelog(UpdVerUrl); - ui->textEdit->setText(strtip); - ui->pushButton_2->setVisible(true); - } else { - ui->textEdit->setText(tr("The current version is already the latest version") + "\r\n\r\n" - + tr("Update log:") + "\r\n" + QSimpleUpdater::getInstance()->getChangelog(UpdVerUrl)); - } -} diff --git a/LedOK/base/updaterdialog.h b/LedOK/base/updaterdialog.h deleted file mode 100644 index 202f0e8..0000000 --- a/LedOK/base/updaterdialog.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef UPDATERDIALOG_H -#define UPDATERDIALOG_H - -#include -#include - -namespace Ui { -class UpdaterDialog; -} - -class UpdaterDialog : public BaseDlg -{ - Q_OBJECT - -public: - explicit UpdaterDialog(QWidget *parent = nullptr); - ~UpdaterDialog(); -private: - Ui::UpdaterDialog *ui; - -protected slots: - void OnCheckForUpdates() ; - void updateChangelog(QString); -}; - -#endif // UPDATERDIALOG_H diff --git a/LedOK/base/updaterdialog.ui b/LedOK/base/updaterdialog.ui deleted file mode 100644 index 93a2b69..0000000 --- a/LedOK/base/updaterdialog.ui +++ /dev/null @@ -1,193 +0,0 @@ - - - UpdaterDialog - - - - 0 - 0 - 500 - 400 - - - - - 0 - 0 - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - 0 - - - - - Software Update - - - Qt::AlignCenter - - - - - - - - 30 - 24 - - - - X - - - - - - - - - border-top: 2px solid gray; - - - Qt::Horizontal - - - - - - - - - - - - 0 - 0 - - - - - 64 - 64 - - - - image: url(:/res/Logo.png); - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - 0 - 0 - - - - - 14 - - - - V1.0 - - - Qt::AlignCenter - - - - - - - true - - - - - - - - 0 - 0 - - - - - 80 - 0 - - - - - 80 - 16777215 - - - - Update - - - - - - - - - - - - - - - - pushButton - clicked() - UpdaterDialog - close() - - - 364 - 29 - - - 199 - 78 - - - - - diff --git a/LedOK/base/waitingdlg.cpp b/LedOK/base/waitingdlg.cpp index 4e3ade1..0174a08 100644 --- a/LedOK/base/waitingdlg.cpp +++ b/LedOK/base/waitingdlg.cpp @@ -1,50 +1,61 @@ -#include "waitingdlg.h" -#include -#include - -WaitingDlg::WaitingDlg(QWidget *parent, QString text, QString sucText) : BaseDlg{parent}, sucText(sucText) { - setAttribute(Qt::WA_DeleteOnClose); - setModal(true); - - auto pal = palette(); - pal.setBrush(QPalette::Window, QColor(0xdddddd)); - setPalette(pal); - - auto vBox = new QVBoxLayout(this); - vBox->addStretch(); - - mIndicator = new CustomProgressIndicator(this); - mIndicator->setDisplayModel(1); - mIndicator->setColor(QColor(0x0088dd)); - mIndicator->startAnimation(); - vBox->addWidget(mIndicator, 0, Qt::AlignCenter); - - vBox->addStretch(); - - fdText = new QLabel(text); - fdText->setAlignment(Qt::AlignCenter); - auto font = fdText->font(); - font.setPixelSize(18); - font.setBold(true); - fdText->setFont(font); - pal = fdText->palette(); - pal.setBrush(QPalette::WindowText, QColor(0x0088dd)); - fdText->setPalette(pal); - vBox->addWidget(fdText); - - vBox->addStretch(); -} - -void WaitingDlg::timerEvent(QTimerEvent *event) { - if(closeTimerId==event->timerId()) { - killTimer(closeTimerId); - closeTimerId = 0; - close(); - } else BaseDlg::timerEvent(event); -} -void WaitingDlg::success() { - fdText->setText(sucText.isEmpty() ? tr("Success") : sucText); - mIndicator->setBackground(":/res/success.png"); - mIndicator->stopAnimation(); - closeTimerId = startTimer(800); -} +#include "waitingdlg.h" +#include +#include +#include + +WaitingDlg::WaitingDlg(QWidget *parent, QString text, QString sucText) : BaseDlg{parent}, sucText(sucText) { + setAttribute(Qt::WA_DeleteOnClose); + setModal(true); + + auto pal = palette(); + pal.setBrush(QPalette::Window, QColor(0xdddddd)); + setPalette(pal); + + auto vBox = new QVBoxLayout(this); + vBox->setContentsMargins(6, 3, 6, 6); + vBox->addStretch(); + + btnAbort = new QPushButton("X"); + btnAbort->setStyleSheet(R"rrr( +QPushButton {border-radius: 4px; padding: 2px 6px; background: transparent;} +QPushButton:hover {background: rgba(0,0,0,0.2);} +QPushButton:pressed {background: rgba(0,0,0,0.3);} +)rrr"); + connect(btnAbort, &QPushButton::clicked, this, &QDialog::reject); + vBox->addWidget(btnAbort, 0, Qt::AlignRight); + + mIndicator = new CustomProgressIndicator(this); + mIndicator->setDisplayModel(1); + mIndicator->setColor(QColor(0x0088dd)); + mIndicator->startAnimation(); + vBox->addWidget(mIndicator, 0, Qt::AlignCenter); + + vBox->addStretch(); + + fdText = new QLabel(text); + fdText->setAlignment(Qt::AlignCenter); + auto font = fdText->font(); + font.setPixelSize(18); + font.setBold(true); + fdText->setFont(font); + pal = fdText->palette(); + pal.setBrush(QPalette::WindowText, QColor(0x0088dd)); + fdText->setPalette(pal); + vBox->addWidget(fdText); + + vBox->addStretch(); +} + +void WaitingDlg::timerEvent(QTimerEvent *event) { + if(closeTimerId==event->timerId()) { + killTimer(closeTimerId); + closeTimerId = 0; + close(); + } else BaseDlg::timerEvent(event); +} +void WaitingDlg::success() { + fdText->setText(sucText.isEmpty() ? tr("Success") : sucText); + mIndicator->setBackground(":/res/success.png"); + mIndicator->stopAnimation(); + closeTimerId = startTimer(800); +} diff --git a/LedOK/base/waitingdlg.h b/LedOK/base/waitingdlg.h index 4799136..cccab19 100644 --- a/LedOK/base/waitingdlg.h +++ b/LedOK/base/waitingdlg.h @@ -1,25 +1,25 @@ -#ifndef WAITINGDLG_H -#define WAITINGDLG_H - -#include "basedlg.h" -#include "base/customprogressindicator.h" -#include - -class WaitingDlg : public BaseDlg { - Q_OBJECT -public: - explicit WaitingDlg(QWidget *parent = nullptr, QString text = 0, QString sucText = 0); - - QLabel *fdText; - QString sucText; - CustomProgressIndicator *mIndicator; -public slots: - void success(); - -protected: - void timerEvent(QTimerEvent *) override; -private: - int closeTimerId{0}; -}; - -#endif // WAITINGDLG_H +#ifndef WAITINGDLG_H +#define WAITINGDLG_H + +#include "basedlg.h" +#include "base/customprogressindicator.h" +#include + +class WaitingDlg : public BaseDlg { + Q_OBJECT +public: + explicit WaitingDlg(QWidget *parent = nullptr, QString text = 0, QString sucText = 0); + + QPushButton *btnAbort; + QLabel *fdText; + QString sucText; + CustomProgressIndicator *mIndicator; +public slots: + void success(); +protected: + void timerEvent(QTimerEvent *) override; +private: + int closeTimerId{0}; +}; + +#endif // WAITINGDLG_H diff --git a/LedOK/base/x_checkboxdelegate.cpp b/LedOK/base/x_checkboxdelegate.cpp index 4489bc5..9ba27d8 100644 --- a/LedOK/base/x_checkboxdelegate.cpp +++ b/LedOK/base/x_checkboxdelegate.cpp @@ -1,116 +1,116 @@ -/* - delegate.cpp - - A delegate that allows the user to change integer values from the model - using a spin box widget. -*/ - -#include "x_checkboxdelegate.h" - -#include -#include -#include -X_CheckBoxDelegate::X_CheckBoxDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ - -} - -QWidget *X_CheckBoxDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem & option , - const QModelIndex & index ) const -{ -// if(index.column()>=3&&index.column()<=9) -// { -// QCheckBox *editor = new QCheckBox(parent); -// // editor->setFrame(false); - -// ///editor->setAlignment(Qt::AlignHCenter); -// // editor->setDisplayFormat("hh:mm"); - -// return editor; - -// } - - if(index.column()>=3&&index.column()<=9) - { - QCheckBox *editor=new QCheckBox(parent); - editor->installEventFilter(const_cast(this)); - return editor; - } - else - return QStyledItemDelegate::createEditor(parent,option,index); - - return nullptr; -} - -//void X_CheckBoxDelegate::setEditorData(QWidget *editor, -// const QModelIndex &index) const -//{ -// if(index.column()>=3&&index.column()<=9) -// { -// bool data = index.model()->data(index, Qt::UserRole).toBool(); -// QCheckBox *checkBox = static_cast(editor); -// checkBox->setChecked(data); - -// } -// else -// QStyledItemDelegate::setEditorData(editor,index); - -//} - -//void X_CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, -// const QModelIndex &index) const -//{ -// QCheckBox *checkBox = static_cast(editor); -// bool value = checkBox->isChecked(); -// model->setData(index, value, Qt::UserRole); -//} -// 绘制复选框 -void X_CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - QStyleOptionViewItem viewOption(option); - initStyleOption(&viewOption, index); - if (option.state.testFlag(QStyle::State_HasFocus)) - viewOption.state = viewOption.state ^ QStyle::State_HasFocus; - - QStyledItemDelegate::paint(painter, viewOption, index); - - if (index.column()>=3&&index.column()<=9) - { - bool data = index.model()->data(index, Qt::UserRole).toBool(); - - QStyleOptionButton checkBoxStyle; - checkBoxStyle.state = data ? QStyle::State_On : QStyle::State_Off; - checkBoxStyle.state |= QStyle::State_Enabled; - checkBoxStyle.iconSize = QSize(20, 20); - checkBoxStyle.rect = option.rect; - - QCheckBox checkBox; - QApplication::style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &checkBoxStyle, painter, &checkBox); - } -} - -// 响应鼠标事件,更新数据 -bool X_CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) -{ - QRect decorationRect = option.rect; - - QMouseEvent *mouseEvent = static_cast(event); - if (event->type() == QEvent::MouseButtonPress && decorationRect.contains(mouseEvent->pos())) - { - if (index.column()>=3&&index.column()<=9) - { - bool data = model->data(index, Qt::UserRole).toBool(); - model->setData(index, !data, Qt::UserRole); - } - } - - return QStyledItemDelegate::editorEvent(event, model, option, index); -} -void X_CheckBoxDelegate::updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &/* index */) const -{ - editor->setGeometry(option.rect); -} - +/* + delegate.cpp + + A delegate that allows the user to change integer values from the model + using a spin box widget. +*/ + +#include "x_checkboxdelegate.h" + +#include +#include +#include +X_CheckBoxDelegate::X_CheckBoxDelegate(QObject *parent) + : QStyledItemDelegate(parent) +{ + +} + +QWidget *X_CheckBoxDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem & option , + const QModelIndex & index ) const +{ +// if(index.column()>=3&&index.column()<=9) +// { +// QCheckBox *editor = new QCheckBox(parent); +// // editor->setFrame(false); + +// ///editor->setAlignment(Qt::AlignHCenter); +// // editor->setDisplayFormat("hh:mm"); + +// return editor; + +// } + + if(index.column()>=3&&index.column()<=9) + { + QCheckBox *editor=new QCheckBox(parent); + editor->installEventFilter(const_cast(this)); + return editor; + } + else + return QStyledItemDelegate::createEditor(parent,option,index); + + return nullptr; +} + +//void X_CheckBoxDelegate::setEditorData(QWidget *editor, +// const QModelIndex &index) const +//{ +// if(index.column()>=3&&index.column()<=9) +// { +// bool data = index.model()->data(index, Qt::UserRole).toBool(); +// QCheckBox *checkBox = static_cast(editor); +// checkBox->setChecked(data); + +// } +// else +// QStyledItemDelegate::setEditorData(editor,index); + +//} + +//void X_CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, +// const QModelIndex &index) const +//{ +// QCheckBox *checkBox = static_cast(editor); +// bool value = checkBox->isChecked(); +// model->setData(index, value, Qt::UserRole); +//} +// 绘制复选框 +void X_CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + QStyleOptionViewItem viewOption(option); + initStyleOption(&viewOption, index); + if (option.state.testFlag(QStyle::State_HasFocus)) + viewOption.state = viewOption.state ^ QStyle::State_HasFocus; + + QStyledItemDelegate::paint(painter, viewOption, index); + + if (index.column()>=3&&index.column()<=9) + { + bool data = index.model()->data(index, Qt::UserRole).toBool(); + + QStyleOptionButton checkBoxStyle; + checkBoxStyle.state = data ? QStyle::State_On : QStyle::State_Off; + checkBoxStyle.state |= QStyle::State_Enabled; + checkBoxStyle.iconSize = QSize(20, 20); + checkBoxStyle.rect = option.rect; + + QCheckBox checkBox; + QApplication::style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &checkBoxStyle, painter, &checkBox); + } +} + +// 响应鼠标事件,更新数据 +bool X_CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) +{ + QRect decorationRect = option.rect; + + QMouseEvent *mouseEvent = static_cast(event); + if (event->type() == QEvent::MouseButtonPress && decorationRect.contains(mouseEvent->pos())) + { + if (index.column()>=3&&index.column()<=9) + { + bool data = model->data(index, Qt::UserRole).toBool(); + model->setData(index, !data, Qt::UserRole); + } + } + + return QStyledItemDelegate::editorEvent(event, model, option, index); +} +void X_CheckBoxDelegate::updateEditorGeometry(QWidget *editor, + const QStyleOptionViewItem &option, const QModelIndex &/* index */) const +{ + editor->setGeometry(option.rect); +} + diff --git a/LedOK/base/x_checkboxdelegate.h b/LedOK/base/x_checkboxdelegate.h index 6f2297b..b227936 100644 --- a/LedOK/base/x_checkboxdelegate.h +++ b/LedOK/base/x_checkboxdelegate.h @@ -1,73 +1,73 @@ -#ifndef X_CHECKBOXDELEGATE_H -#define X_CHECKBOXDELEGATE_H -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, 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 The Qt Company Ltd 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 - -//! [0] -class X_CheckBoxDelegate : public QStyledItemDelegate -{ - Q_OBJECT - -public: - X_CheckBoxDelegate(QObject *parent = nullptr); - QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; -// void setEditorData(QWidget *editor, const QModelIndex &index) const override; -// void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override; - - -}; -//! [0] - -#endif // X_CHECKBOXDELEGATE_H +#ifndef X_CHECKBOXDELEGATE_H +#define X_CHECKBOXDELEGATE_H +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, 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 The Qt Company Ltd 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 + +//! [0] +class X_CheckBoxDelegate : public QStyledItemDelegate +{ + Q_OBJECT + +public: + X_CheckBoxDelegate(QObject *parent = nullptr); + QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; +// void setEditorData(QWidget *editor, const QModelIndex &index) const override; +// void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override; + + +}; +//! [0] + +#endif // X_CHECKBOXDELEGATE_H diff --git a/LedOK/base/x_spinboxdelegate.cpp b/LedOK/base/x_spinboxdelegate.cpp index 06f0383..c20f789 100644 --- a/LedOK/base/x_spinboxdelegate.cpp +++ b/LedOK/base/x_spinboxdelegate.cpp @@ -1,35 +1,35 @@ -#include "x_spinboxdelegate.h" -/* - A delegate that allows the user to change integer values from the model - using a spin box widget. -*/ -#include - -SpinBoxDelegate::SpinBoxDelegate(QObject *parent, int iFlag) : QStyledItemDelegate(parent) { - m_iFlag=iFlag; -} - -QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const { - if(index.column()!=0) return 0; - QSpinBox *editor = new QSpinBox(parent); - editor->setFrame(false); - editor->setMinimum(0); - if(m_iFlag==0) editor->setMaximum(100);//亮度最大值 - else if(m_iFlag==1) editor->setMaximum(15);//音量最大值 - editor->setAlignment(Qt::AlignHCenter); - return editor; -} -void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{ - int value = index.model()->data(index, Qt::EditRole).toInt(); - QSpinBox *spinBox = static_cast(editor); - spinBox->setValue(value); -} -void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ - QSpinBox *spinBox = static_cast(editor); - spinBox->interpretText(); - int value = spinBox->value(); - model->setData(index, value, Qt::EditRole); -} -void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const { - editor->setGeometry(option.rect); -} +#include "x_spinboxdelegate.h" +/* + A delegate that allows the user to change integer values from the model + using a spin box widget. +*/ +#include + +SpinBoxDelegate::SpinBoxDelegate(QObject *parent, int iFlag) : QStyledItemDelegate(parent) { + m_iFlag=iFlag; +} + +QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const { + if(index.column()!=0) return 0; + QSpinBox *editor = new QSpinBox(parent); + editor->setFrame(false); + editor->setMinimum(0); + if(m_iFlag==0) editor->setMaximum(100);//亮度最大值 + else if(m_iFlag==1) editor->setMaximum(15);//音量最大值 + editor->setAlignment(Qt::AlignHCenter); + return editor; +} +void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{ + int value = index.model()->data(index, Qt::EditRole).toInt(); + QSpinBox *spinBox = static_cast(editor); + spinBox->setValue(value); +} +void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ + QSpinBox *spinBox = static_cast(editor); + spinBox->interpretText(); + int value = spinBox->value(); + model->setData(index, value, Qt::EditRole); +} +void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const { + editor->setGeometry(option.rect); +} diff --git a/LedOK/base/x_spinboxdelegate.h b/LedOK/base/x_spinboxdelegate.h index 4561f88..90d67d4 100644 --- a/LedOK/base/x_spinboxdelegate.h +++ b/LedOK/base/x_spinboxdelegate.h @@ -1,67 +1,67 @@ -#ifndef X_SPINBOXDELEGATE_H -#define X_SPINBOXDELEGATE_H -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, 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 The Qt Company Ltd 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 -#include -class SpinBoxDelegate : public QStyledItemDelegate { - Q_OBJECT -public: - SpinBoxDelegate(QObject *parent = 0,int iFlag=0); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; -public: - int m_iFlag=0; -}; -#endif // X_SPINBOXDELEGATE_H +#ifndef X_SPINBOXDELEGATE_H +#define X_SPINBOXDELEGATE_H +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, 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 The Qt Company Ltd 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 +#include +class SpinBoxDelegate : public QStyledItemDelegate { + Q_OBJECT +public: + SpinBoxDelegate(QObject *parent = 0,int iFlag=0); + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; + void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; +public: + int m_iFlag=0; +}; +#endif // X_SPINBOXDELEGATE_H diff --git a/LedOK/base/x_timeeditdelegate.cpp b/LedOK/base/x_timeeditdelegate.cpp index 4b9306b..7bc424d 100644 --- a/LedOK/base/x_timeeditdelegate.cpp +++ b/LedOK/base/x_timeeditdelegate.cpp @@ -1,62 +1,62 @@ -#include "X_timeEditDelegate.h" -/* - delegate.cpp - - A delegate that allows the user to change integer values from the model - using a spin box widget. -*/ - -#include "X_timeEditDelegate.h" - -#include - -X_timeEditDelegate::X_timeEditDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} - -QWidget *X_timeEditDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &/* option */, - const QModelIndex & index ) const -{ - if(index.column()==1||index.column()==2) - { - QTimeEdit *editor = new QTimeEdit(parent); - editor->setFrame(false); - - editor->setAlignment(Qt::AlignHCenter); - editor->setDisplayFormat("hh:mm"); - - return editor; - - } - return nullptr; -} - -void X_timeEditDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const -{ - QString value = index.model()->data(index, Qt::EditRole).toString(); - - QTimeEdit *spinBoxTimeEdit = static_cast(editor); - QTime qtime=QTime::fromString(value,"hh:mm"); - spinBoxTimeEdit->setTime(qtime); - -} - -void X_timeEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const -{ - QTimeEdit *spinBoxTimeEdit = static_cast(editor); - spinBoxTimeEdit->interpretText(); - QString value = spinBoxTimeEdit->time().toString("hh:mm"); - - model->setData(index, value, Qt::EditRole); -} - -void X_timeEditDelegate::updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &/* index */) const -{ - editor->setGeometry(option.rect); -} - +#include "X_timeEditDelegate.h" +/* + delegate.cpp + + A delegate that allows the user to change integer values from the model + using a spin box widget. +*/ + +#include "X_timeEditDelegate.h" + +#include + +X_timeEditDelegate::X_timeEditDelegate(QObject *parent) + : QStyledItemDelegate(parent) +{ +} + +QWidget *X_timeEditDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem &/* option */, + const QModelIndex & index ) const +{ + if(index.column()==1||index.column()==2) + { + QTimeEdit *editor = new QTimeEdit(parent); + editor->setFrame(false); + + editor->setAlignment(Qt::AlignHCenter); + editor->setDisplayFormat("hh:mm"); + + return editor; + + } + return nullptr; +} + +void X_timeEditDelegate::setEditorData(QWidget *editor, + const QModelIndex &index) const +{ + QString value = index.model()->data(index, Qt::EditRole).toString(); + + QTimeEdit *spinBoxTimeEdit = static_cast(editor); + QTime qtime=QTime::fromString(value,"hh:mm"); + spinBoxTimeEdit->setTime(qtime); + +} + +void X_timeEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const +{ + QTimeEdit *spinBoxTimeEdit = static_cast(editor); + spinBoxTimeEdit->interpretText(); + QString value = spinBoxTimeEdit->time().toString("hh:mm"); + + model->setData(index, value, Qt::EditRole); +} + +void X_timeEditDelegate::updateEditorGeometry(QWidget *editor, + const QStyleOptionViewItem &option, const QModelIndex &/* index */) const +{ + editor->setGeometry(option.rect); +} + diff --git a/LedOK/base/x_timeeditdelegate.h b/LedOK/base/x_timeeditdelegate.h index 5f98dc3..0595724 100644 --- a/LedOK/base/x_timeeditdelegate.h +++ b/LedOK/base/x_timeeditdelegate.h @@ -1,75 +1,75 @@ -#ifndef X_TIMEEDITDELEGATE_H -#define X_TIMEEDITDELEGATE_H -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, 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 The Qt Company Ltd 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 - -//! [0] -class X_timeEditDelegate : public QStyledItemDelegate -{ - Q_OBJECT - -public: - X_timeEditDelegate(QObject *parent = 0); - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; - - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; - - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; -}; -//! [0] - -#endif // X_TIMEEDITDELEGATE_H +#ifndef X_TIMEEDITDELEGATE_H +#define X_TIMEEDITDELEGATE_H +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, 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 The Qt Company Ltd 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 + +//! [0] +class X_timeEditDelegate : public QStyledItemDelegate +{ + Q_OBJECT + +public: + X_timeEditDelegate(QObject *parent = 0); + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; + + void setEditorData(QWidget *editor, const QModelIndex &index) const override; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const override; + + void updateEditorGeometry(QWidget *editor, + const QStyleOptionViewItem &option, const QModelIndex &index) const override; +}; +//! [0] + +#endif // X_TIMEEDITDELEGATE_H diff --git a/LedOK/base/x_uimsgboxok.cpp b/LedOK/base/x_uimsgboxok.cpp index f6dc786..29a92b5 100644 --- a/LedOK/base/x_uimsgboxok.cpp +++ b/LedOK/base/x_uimsgboxok.cpp @@ -1,60 +1,60 @@ -#include "x_uimsgboxok.h" -#include "ui_x_uimsgboxok.h" -#include -#include - -X_UIMsgBoxOk::X_UIMsgBoxOk(QWidget *parent) : - BaseDlg(parent), - ui(new Ui::X_UIMsgBoxOk) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - m_bExitTypeFlag=0; -} - -X_UIMsgBoxOk::~X_UIMsgBoxOk() -{ - delete ui; -} -X_UIMsgBoxOk::X_UIMsgBoxOk(QString strTitle,QString text, QWidget *parent) : - BaseDlg(parent), - ui(new Ui::X_UIMsgBoxOk) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - ui->lInfoTip->adjustSize(); - ui->label_3->setText(strTitle); - //让QLabel能够自动判断并换行显示: -// ui->lInfoTip->setGeometry(QRect(328, 240, 329, 27*4)); //四倍行距 - ui->lInfoTip->setWordWrap(true); - ui->lInfoTip->setAlignment(Qt::AlignTop); - ui->lInfoTip->setText(text); - ui->pushButton_3->setVisible(false); - m_bExitTypeFlag=0; - ui->pushButton->setProperty("ssType", "progManageTool"); - ui->pushButton_2->setProperty("ssType", "progManageTool"); - ui->pushButton_3->setProperty("ssType", "progManageTool"); -} -X_UIMsgBoxOk::X_UIMsgBoxOk(QString strTitle,QString text, QWidget *parent,int iType) : - BaseDlg(parent), - ui(new Ui::X_UIMsgBoxOk) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - m_bExitTypeFlag=0; - ui->lInfoTip->adjustSize(); - ui->label_3->setText(strTitle); - //让QLabel能够自动判断并换行显示: -// ui->lInfoTip->setGeometry(QRect(328, 240, 329, 27*4)); //四倍行距 - ui->lInfoTip->setWordWrap(true); - ui->lInfoTip->setAlignment(Qt::AlignTop); - ui->lInfoTip->setText(text); - ui->pushButton_3->setVisible(false); - if(iType==1) { - ui->lInfoTip->setStyleSheet("background:rgba(206,206,206,1)"); - ui->frame->setStyleSheet("QFrame{background:rgba(206,206,206,1)}"); - setStyleSheet("X_UIMsgBoxOk{background:rgba(206,206,206,1)}"); - ui->pushButton->setProperty("ssType", "progManageTool"); - ui->pushButton_2->setProperty("ssType", "progManageTool"); - } -} +#include "x_uimsgboxok.h" +#include "ui_x_uimsgboxok.h" +#include +#include + +X_UIMsgBoxOk::X_UIMsgBoxOk(QWidget *parent) : + BaseDlg(parent), + ui(new Ui::X_UIMsgBoxOk) +{ + setAttribute(Qt::WA_DeleteOnClose); + ui->setupUi(this); + m_bExitTypeFlag=0; +} + +X_UIMsgBoxOk::~X_UIMsgBoxOk() +{ + delete ui; +} +X_UIMsgBoxOk::X_UIMsgBoxOk(QString strTitle,QString text, QWidget *parent) : + BaseDlg(parent), + ui(new Ui::X_UIMsgBoxOk) +{ + setAttribute(Qt::WA_DeleteOnClose); + ui->setupUi(this); + ui->lInfoTip->adjustSize(); + ui->label_3->setText(strTitle); + //让QLabel能够自动判断并换行显示: +// ui->lInfoTip->setGeometry(QRect(328, 240, 329, 27*4)); //四倍行距 + ui->lInfoTip->setWordWrap(true); + ui->lInfoTip->setAlignment(Qt::AlignTop); + ui->lInfoTip->setText(text); + ui->pushButton_3->setVisible(false); + m_bExitTypeFlag=0; + ui->pushButton->setProperty("ssType", "progManageTool"); + ui->pushButton_2->setProperty("ssType", "progManageTool"); + ui->pushButton_3->setProperty("ssType", "progManageTool"); +} +X_UIMsgBoxOk::X_UIMsgBoxOk(QString strTitle,QString text, QWidget *parent,int iType) : + BaseDlg(parent), + ui(new Ui::X_UIMsgBoxOk) +{ + setAttribute(Qt::WA_DeleteOnClose); + ui->setupUi(this); + m_bExitTypeFlag=0; + ui->lInfoTip->adjustSize(); + ui->label_3->setText(strTitle); + //让QLabel能够自动判断并换行显示: +// ui->lInfoTip->setGeometry(QRect(328, 240, 329, 27*4)); //四倍行距 + ui->lInfoTip->setWordWrap(true); + ui->lInfoTip->setAlignment(Qt::AlignTop); + ui->lInfoTip->setText(text); + ui->pushButton_3->setVisible(false); + if(iType==1) { + ui->lInfoTip->setStyleSheet("background:rgba(206,206,206,1)"); + ui->frame->setStyleSheet("QFrame{background:rgba(206,206,206,1)}"); + setStyleSheet("X_UIMsgBoxOk{background:rgba(206,206,206,1)}"); + ui->pushButton->setProperty("ssType", "progManageTool"); + ui->pushButton_2->setProperty("ssType", "progManageTool"); + } +} diff --git a/LedOK/base/x_uimsgboxok.h b/LedOK/base/x_uimsgboxok.h index a8a9697..da5cb6c 100644 --- a/LedOK/base/x_uimsgboxok.h +++ b/LedOK/base/x_uimsgboxok.h @@ -1,24 +1,24 @@ -#ifndef X_UIMSGBOXOK_H -#define X_UIMSGBOXOK_H - -#include -namespace Ui { -class X_UIMsgBoxOk; -} - -class X_UIMsgBoxOk : public BaseDlg -{ - Q_OBJECT - -public: - explicit X_UIMsgBoxOk(QWidget *parent = nullptr); - X_UIMsgBoxOk(QString strTitle, QString text, QWidget *parent = nullptr); - X_UIMsgBoxOk(QString strTitle, QString text, QWidget *parent = nullptr,int iType=0); - ~X_UIMsgBoxOk(); - int m_bExitTypeFlag=0; - -private: - Ui::X_UIMsgBoxOk *ui; -}; - -#endif // X_UIMSGBOXOK_H +#ifndef X_UIMSGBOXOK_H +#define X_UIMSGBOXOK_H + +#include +namespace Ui { +class X_UIMsgBoxOk; +} + +class X_UIMsgBoxOk : public BaseDlg +{ + Q_OBJECT + +public: + explicit X_UIMsgBoxOk(QWidget *parent = nullptr); + X_UIMsgBoxOk(QString strTitle, QString text, QWidget *parent = nullptr); + X_UIMsgBoxOk(QString strTitle, QString text, QWidget *parent = nullptr,int iType=0); + ~X_UIMsgBoxOk(); + int m_bExitTypeFlag=0; + +private: + Ui::X_UIMsgBoxOk *ui; +}; + +#endif // X_UIMSGBOXOK_H diff --git a/LedOK/base/x_uimsgboxok.ui b/LedOK/base/x_uimsgboxok.ui index 332fc76..109d6d4 100644 --- a/LedOK/base/x_uimsgboxok.ui +++ b/LedOK/base/x_uimsgboxok.ui @@ -1,243 +1,243 @@ - - - X_UIMsgBoxOk - - - - 0 - 0 - 426 - 200 - - - - - 0 - 0 - - - - - - - true - - - - 0 - 0 - - - - QFrame::Box - - - - - - - - - - - 0 - 0 - - - - QFrame::Sunken - - - 0 - - - TextLabel - - - Qt::AlignCenter - - - - - - - - 31 - 23 - - - - X - - - - - - - - - border-top: 2px solid gray; - - - 1 - - - 0 - - - Qt::Horizontal - - - - - - - - - - - - 0 - 0 - - - - - 32 - 32 - - - - image: url(:/res/tip.png); - - - QFrame::NoFrame - - - QFrame::Plain - - - 0 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - 0 - 0 - - - - TextLabel - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - OK - - - - - - - Cancel - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - - pushButton - clicked() - X_UIMsgBoxOk - accept() - - - 128 - 119 - - - 127 - 75 - - - - - pushButton_2 - clicked() - X_UIMsgBoxOk - close() - - - 220 - 31 - - - 127 - 75 - - - - - + + + X_UIMsgBoxOk + + + + 0 + 0 + 426 + 200 + + + + + 0 + 0 + + + + + + + true + + + + 0 + 0 + + + + QFrame::Box + + + + + + + + + + + 0 + 0 + + + + QFrame::Sunken + + + 0 + + + TextLabel + + + Qt::AlignCenter + + + + + + + + 31 + 23 + + + + X + + + + + + + + + border-top: 2px solid gray; + + + 1 + + + 0 + + + Qt::Horizontal + + + + + + + + + + + + 0 + 0 + + + + + 32 + 32 + + + + image: url(:/res/tip.png); + + + QFrame::NoFrame + + + QFrame::Plain + + + 0 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + 0 + 0 + + + + TextLabel + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + OK + + + + + + + Cancel + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + pushButton + clicked() + X_UIMsgBoxOk + accept() + + + 128 + 119 + + + 127 + 75 + + + + + pushButton_2 + clicked() + X_UIMsgBoxOk + close() + + + 220 + 31 + + + 127 + 75 + + + + + diff --git a/LedOK/basedlg.cpp b/LedOK/basedlg.cpp index 2f3b661..74dc2ab 100644 --- a/LedOK/basedlg.cpp +++ b/LedOK/basedlg.cpp @@ -48,7 +48,7 @@ bool BaseDlg::nativeEvent(const QByteArray &eventType, void *message, long *){ MSG *msg = (MSG*)message; if(msg->message==WM_NCACTIVATE){ isActive = msg->wParam; - repaint(); + update(); } } return false; diff --git a/LedOK/basewin.cpp b/LedOK/basewin.cpp index 8844959..b64c42e 100644 --- a/LedOK/basewin.cpp +++ b/LedOK/basewin.cpp @@ -122,7 +122,7 @@ bool BaseWin::nativeEvent(const QByteArray &eventType, void *message, long *){ MSG *msg = (MSG*)message; if(msg->message==WM_NCACTIVATE){ isActive = msg->wParam; - repaint(); + update(); } } return false; diff --git a/LedOK/communication/hpptclient.cpp b/LedOK/communication/hpptclient.cpp index beb2586..5c9b787 100644 --- a/LedOK/communication/hpptclient.cpp +++ b/LedOK/communication/hpptclient.cpp @@ -1,193 +1,193 @@ -#include "hpptclient.h" - -//HpptClient* HpptClient::gInstance = nullptr; -HpptClient::HpptClient(QObject *p): QObject(p) { - connect(&mNetAccessManager, &QNetworkAccessManager::finished, this, [this](QNetworkReply *reply) { - if(reply->property("data").isValid()) onHttpPostRspFinished(reply); - else onHttpGetRspFinished(reply); - }); -} -void HpptClient::clearRp(QNetworkReply *rp) { - if(rp) - { - QString url = rp->request().url().toString(); - QString postMD5 = rp->property("postMD5").toString(); - QString postData = rp->property("data").toByteArray(); - - if(postMD5.isEmpty()) - { - //清理对应缓存 - mDownloadDataCache.remove(url); - - //解除正在处理状态 - mProcessingRq.remove(url); - } - else - { - //清理对应缓存 - mDownloadDataCache.remove(postMD5); - - - //解除正在处理状态 - mProcessingRq.remove(postMD5); - } - - mRedirectMap.remove(url); - mRedirectMap.remove(postMD5); - - //qDebug() << "delete cache, url:" << url << " postMOD5:" << postMD5; - rp->deleteLater(); - } -} - -void HpptClient::onHttpGetRspProgress(qint64 bytesReceived, qint64 bytesTotal) -{ - Q_UNUSED(bytesReceived) - if(sender() == NULL) - { - return ; - } - - QNetworkReply* rp = qobject_cast(sender()); - if(rp == NULL) - { - return; - } - - //qDebug() << "http get rsp progress:" << rp->url().toString() << bytesReceived << "/" << bytesTotal; - if(bytesTotal <= 0) - { - return; - } - - QString url = rp->url().toString(); - - mDownloadDataCache[url].append(rp->readAll()); - -} - -void HpptClient::onHttpGetRspFinished(QNetworkReply *reply) { - QByteArray rpData; - QString url = reply->url().toString(); - int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - QString strUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); - - switch(statusCode) { - case 200: { - rpData = mDownloadDataCache[reply->url().toString()]; - QString redirectUrl = mRedirectMap[url];//重定向的url地址 - if(redirectUrl.isEmpty()) emit httpGetRspReady(url, rpData); - else emit httpGetRspReady(redirectUrl, rpData); - } - break; - case 301: - case 302: { - if(!strUrl.isEmpty()) { - QString turl = mRedirectMap[url]; - if(turl.isEmpty()) mRedirectMap[strUrl] = url; - else mRedirectMap[strUrl] = turl; - httpGet(strUrl); - } - } - break; - default: // error - { - qDebug() << url << "[get error:" << statusCode << "]"; - QString redirectUrl = mRedirectMap[url]; - if(redirectUrl.isEmpty()) emit httpGetRspReady(url, QByteArray()); - else emit httpGetRspReady(redirectUrl, QByteArray()); - } - break; - } - clearRp(reply); -} - -void HpptClient::onHttpPostRspProgress(qint64, qint64 bytesTotal){ - if(sender() == NULL) return; - QNetworkReply* rp = qobject_cast(sender()); - if(rp == NULL) return; - if(bytesTotal <= 0) return; - mDownloadDataCache[rp->property("postMD5").toString()].append(rp->readAll()); -} - -void HpptClient::onHttpPostRspFinished(QNetworkReply *reply) { - QString url = reply->url().toString(); - QString postMD5 = reply->property("postMD5").toString(); - - int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - switch(statusCode) { - case 200: { - auto rpData = mDownloadDataCache[postMD5]; - QString redirectMD5 = mRedirectMap[postMD5]; - QString redirectUrl = mRedirectMap[url]; - if(redirectMD5.isEmpty() || redirectUrl.isEmpty()) emit httpPostRspReady(url, postMD5, rpData); - else emit httpPostRspReady(redirectUrl, redirectMD5, rpData); - } - break; - case 301: - case 302: { - auto redireUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); - if(!redireUrl.isEmpty()) { - QString turl = mRedirectMap[url];//direct by - if(turl.isEmpty()) mRedirectMap[redireUrl] = url; - else mRedirectMap[redireUrl] = turl; - - QByteArray postData = reply->property("data").toByteArray(); - QByteArray d = redireUrl.toUtf8() + postData; - QString md5 = QCryptographicHash::hash(d, QCryptographicHash::Md5); - QString tPostMD5 = mRedirectMap[md5];//direct by - if(tPostMD5.isEmpty()) mRedirectMap[md5] = postMD5; - else mRedirectMap[md5] = tPostMD5; - httpPost(redireUrl, postData); - } - } - break; - default: - QString redirectMD5 = mRedirectMap[postMD5]; - QString redirectUrl = mRedirectMap[url]; - if(redirectMD5.isEmpty() || redirectUrl.isEmpty()) - { - emit httpPostRspReady(url, postMD5, QByteArray()); - } - else - { - emit httpPostRspReady(redirectUrl, redirectMD5, QByteArray()); - } - break; - } - clearRp(reply); -} - - -void HpptClient::httpGet(const QString &url) { - if(mProcessingRq.value(url, false)) return;//ignore when rq processing - auto values = mRedirectMap.values(); - for(int i = 0; i < values.count(); i++) if(values[i] == url) return;//ignore when redirect processing - mProcessingRq.insert(url, true); - - QNetworkRequest request{url}; - QSslConfiguration config = request.sslConfiguration(); - config.setPeerVerifyMode(QSslSocket::VerifyNone); - config.setProtocol(QSsl::TlsV1SslV3); - request.setSslConfiguration(config); - - QNetworkReply* rp = mNetAccessManager.get(request); - connect(rp, &QNetworkReply::downloadProgress, this, &HpptClient::onHttpGetRspProgress); -} - -QByteArray HpptClient::httpPost(const QString &url, const QByteArray &data) { - QByteArray md5 = QCryptographicHash::hash(url.toUtf8() + data, QCryptographicHash::Md5); - if(mProcessingRq.value(md5, false)) return md5;//ignore when rq processing - auto values = mRedirectMap.values(); - for(int i=0; i < values.count(); i++) if(values[i] == md5) return md5; //ignore when redirect processing - mProcessingRq.insert(md5, true); - - QNetworkRequest request{url}; - request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");//add by alahover 20200304 - QNetworkReply* reply = mNetAccessManager.post(request, data); - reply->setProperty("postMD5", md5); - reply->setProperty("url", url); - reply->setProperty("data", data); - connect(reply, &QNetworkReply::downloadProgress, this, &HpptClient::onHttpPostRspProgress); - return md5; -} +#include "hpptclient.h" + +//HpptClient* HpptClient::gInstance = nullptr; +HpptClient::HpptClient(QObject *p): QObject(p) { + connect(&mNetAccessManager, &QNetworkAccessManager::finished, this, [this](QNetworkReply *reply) { + if(reply->property("data").isValid()) onHttpPostRspFinished(reply); + else onHttpGetRspFinished(reply); + }); +} +void HpptClient::clearRp(QNetworkReply *rp) { + if(rp) + { + QString url = rp->request().url().toString(); + QString postMD5 = rp->property("postMD5").toString(); + QString postData = rp->property("data").toByteArray(); + + if(postMD5.isEmpty()) + { + //清理对应缓存 + mDownloadDataCache.remove(url); + + //解除正在处理状态 + mProcessingRq.remove(url); + } + else + { + //清理对应缓存 + mDownloadDataCache.remove(postMD5); + + + //解除正在处理状态 + mProcessingRq.remove(postMD5); + } + + mRedirectMap.remove(url); + mRedirectMap.remove(postMD5); + + //qDebug() << "delete cache, url:" << url << " postMOD5:" << postMD5; + rp->deleteLater(); + } +} + +void HpptClient::onHttpGetRspProgress(qint64 bytesReceived, qint64 bytesTotal) +{ + Q_UNUSED(bytesReceived) + if(sender() == NULL) + { + return ; + } + + QNetworkReply* rp = qobject_cast(sender()); + if(rp == NULL) + { + return; + } + + //qDebug() << "http get rsp progress:" << rp->url().toString() << bytesReceived << "/" << bytesTotal; + if(bytesTotal <= 0) + { + return; + } + + QString url = rp->url().toString(); + + mDownloadDataCache[url].append(rp->readAll()); + +} + +void HpptClient::onHttpGetRspFinished(QNetworkReply *reply) { + QByteArray rpData; + QString url = reply->url().toString(); + int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + QString strUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); + + switch(statusCode) { + case 200: { + rpData = mDownloadDataCache[reply->url().toString()]; + QString redirectUrl = mRedirectMap[url];//重定向的url地址 + if(redirectUrl.isEmpty()) emit httpGetRspReady(url, rpData); + else emit httpGetRspReady(redirectUrl, rpData); + } + break; + case 301: + case 302: { + if(!strUrl.isEmpty()) { + QString turl = mRedirectMap[url]; + if(turl.isEmpty()) mRedirectMap[strUrl] = url; + else mRedirectMap[strUrl] = turl; + httpGet(strUrl); + } + } + break; + default: // error + { + qDebug() << url << "[get error:" << statusCode << "]"; + QString redirectUrl = mRedirectMap[url]; + if(redirectUrl.isEmpty()) emit httpGetRspReady(url, QByteArray()); + else emit httpGetRspReady(redirectUrl, QByteArray()); + } + break; + } + clearRp(reply); +} + +void HpptClient::onHttpPostRspProgress(qint64, qint64 bytesTotal){ + if(sender() == NULL) return; + QNetworkReply* rp = qobject_cast(sender()); + if(rp == NULL) return; + if(bytesTotal <= 0) return; + mDownloadDataCache[rp->property("postMD5").toString()].append(rp->readAll()); +} + +void HpptClient::onHttpPostRspFinished(QNetworkReply *reply) { + QString url = reply->url().toString(); + QString postMD5 = reply->property("postMD5").toString(); + + int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + switch(statusCode) { + case 200: { + auto rpData = mDownloadDataCache[postMD5]; + QString redirectMD5 = mRedirectMap[postMD5]; + QString redirectUrl = mRedirectMap[url]; + if(redirectMD5.isEmpty() || redirectUrl.isEmpty()) emit httpPostRspReady(url, postMD5, rpData); + else emit httpPostRspReady(redirectUrl, redirectMD5, rpData); + } + break; + case 301: + case 302: { + auto redireUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); + if(!redireUrl.isEmpty()) { + QString turl = mRedirectMap[url];//direct by + if(turl.isEmpty()) mRedirectMap[redireUrl] = url; + else mRedirectMap[redireUrl] = turl; + + QByteArray postData = reply->property("data").toByteArray(); + QByteArray d = redireUrl.toUtf8() + postData; + QString md5 = QCryptographicHash::hash(d, QCryptographicHash::Md5); + QString tPostMD5 = mRedirectMap[md5];//direct by + if(tPostMD5.isEmpty()) mRedirectMap[md5] = postMD5; + else mRedirectMap[md5] = tPostMD5; + httpPost(redireUrl, postData); + } + } + break; + default: + QString redirectMD5 = mRedirectMap[postMD5]; + QString redirectUrl = mRedirectMap[url]; + if(redirectMD5.isEmpty() || redirectUrl.isEmpty()) + { + emit httpPostRspReady(url, postMD5, QByteArray()); + } + else + { + emit httpPostRspReady(redirectUrl, redirectMD5, QByteArray()); + } + break; + } + clearRp(reply); +} + + +void HpptClient::httpGet(const QString &url) { + if(mProcessingRq.value(url, false)) return;//ignore when rq processing + auto values = mRedirectMap.values(); + for(int i = 0; i < values.count(); i++) if(values[i] == url) return;//ignore when redirect processing + mProcessingRq.insert(url, true); + + QNetworkRequest request{url}; + QSslConfiguration config = request.sslConfiguration(); + config.setPeerVerifyMode(QSslSocket::VerifyNone); + config.setProtocol(QSsl::TlsV1SslV3); + request.setSslConfiguration(config); + + QNetworkReply* rp = mNetAccessManager.get(request); + connect(rp, &QNetworkReply::downloadProgress, this, &HpptClient::onHttpGetRspProgress); +} + +QByteArray HpptClient::httpPost(const QString &url, const QByteArray &data) { + QByteArray md5 = QCryptographicHash::hash(url.toUtf8() + data, QCryptographicHash::Md5); + if(mProcessingRq.value(md5, false)) return md5;//ignore when rq processing + auto values = mRedirectMap.values(); + for(int i=0; i < values.count(); i++) if(values[i] == md5) return md5; //ignore when redirect processing + mProcessingRq.insert(md5, true); + + QNetworkRequest request{url}; + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");//add by alahover 20200304 + QNetworkReply* reply = mNetAccessManager.post(request, data); + reply->setProperty("postMD5", md5); + reply->setProperty("url", url); + reply->setProperty("data", data); + connect(reply, &QNetworkReply::downloadProgress, this, &HpptClient::onHttpPostRspProgress); + return md5; +} diff --git a/LedOK/communication/hpptclient.h b/LedOK/communication/hpptclient.h index 351c2c0..6fdd2d7 100644 --- a/LedOK/communication/hpptclient.h +++ b/LedOK/communication/hpptclient.h @@ -1,46 +1,46 @@ -#ifndef HPPTCLIENT_H -#define HPPTCLIENT_H - -#include -#include -#include -#include -class HpptClient : public QObject { - Q_OBJECT -public: - HpptClient(QObject *p = nullptr); - - void httpGet(const QString& url); - /// \return 返回url+data的md5 - QByteArray httpPost(const QString& url, const QByteArray &data); - -signals: - /// \brief httpGetRspReady http get 请求得到回复 - /// \param url 请求的地址 - /// \param data 回复的数据(如果isEmpty则表示请求出错了) - void httpGetRspReady(QString url, QByteArray data); - - /// \brief httpPostRspReady http post 请求得到回复 - /// \param url 请求的地址 - /// \param postMD5 是post的时候url+数据的md5 - /// \param data data是回复的数据(如果isEmpty则表示请求出错了) - void httpPostRspReady(QString url, QString postMD5, QByteArray data); - -private slots: - void clearRp(QNetworkReply* rp); - - void onHttpGetRspProgress(qint64 bytesReceived, qint64 bytesTotal); //* http get 回复进度 - void onHttpGetRspFinished(QNetworkReply *reply); //* http get 处理完毕 - - void onHttpPostRspProgress(qint64 bytesReceived, qint64 bytesTotal); //* http post 回复进度 - void onHttpPostRspFinished(QNetworkReply *reply); //* http get 处理完毕 - -private: - QNetworkAccessManager mNetAccessManager; - QString mCacheRoot; //* 缓存目录 - QMap mProcessingRq; //* 当前正在处理的请求url 和是否正在处理 - QMap mDownloadDataCache; //* 数据缓存url -> data | postMD5 -> data - QMap mRedirectMap; //* 重定向关系 -}; - -#endif // HPPTCLIENT_H +#ifndef HPPTCLIENT_H +#define HPPTCLIENT_H + +#include +#include +#include +#include +class HpptClient : public QObject { + Q_OBJECT +public: + HpptClient(QObject *p = nullptr); + + void httpGet(const QString& url); + /// \return 返回url+data的md5 + QByteArray httpPost(const QString& url, const QByteArray &data); + +signals: + /// \brief httpGetRspReady http get 请求得到回复 + /// \param url 请求的地址 + /// \param data 回复的数据(如果isEmpty则表示请求出错了) + void httpGetRspReady(QString url, QByteArray data); + + /// \brief httpPostRspReady http post 请求得到回复 + /// \param url 请求的地址 + /// \param postMD5 是post的时候url+数据的md5 + /// \param data data是回复的数据(如果isEmpty则表示请求出错了) + void httpPostRspReady(QString url, QString postMD5, QByteArray data); + +private slots: + void clearRp(QNetworkReply* rp); + + void onHttpGetRspProgress(qint64 bytesReceived, qint64 bytesTotal); //* http get 回复进度 + void onHttpGetRspFinished(QNetworkReply *reply); //* http get 处理完毕 + + void onHttpPostRspProgress(qint64 bytesReceived, qint64 bytesTotal); //* http post 回复进度 + void onHttpPostRspFinished(QNetworkReply *reply); //* http get 处理完毕 + +private: + QNetworkAccessManager mNetAccessManager; + QString mCacheRoot; //* 缓存目录 + QMap mProcessingRq; //* 当前正在处理的请求url 和是否正在处理 + QMap mDownloadDataCache; //* 数据缓存url -> data | postMD5 -> data + QMap mRedirectMap; //* 重定向关系 +}; + +#endif // HPPTCLIENT_H diff --git a/LedOK/communication/taserialthread.cpp b/LedOK/communication/taserialthread.cpp index 6030b5a..c846678 100644 --- a/LedOK/communication/taserialthread.cpp +++ b/LedOK/communication/taserialthread.cpp @@ -1,130 +1,130 @@ -#include "taserialthread.h" -#include -TA_SerialThread::TA_SerialThread() -{ - portCnt = 0; - portNewCnt=0; - m_arrSerial = new QSerialPort[10]; - m_arrNewSerial=new QSerialPortInfo[10]; -} - -TA_SerialThread::~TA_SerialThread() -{ - -} - -void TA_SerialThread::run() -{ - -} - -void TA_SerialThread::SearchPort(void) { - portNewCnt=0; - //查找可用的串口 - foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { - if(portNewCnt > 9) break; - m_arrNewSerial[portNewCnt]=info; - portNewCnt++; - } - - for (int i=0;i +TA_SerialThread::TA_SerialThread() +{ + portCnt = 0; + portNewCnt=0; + m_arrSerial = new QSerialPort[10]; + m_arrNewSerial=new QSerialPortInfo[10]; +} + +TA_SerialThread::~TA_SerialThread() +{ + +} + +void TA_SerialThread::run() +{ + +} + +void TA_SerialThread::SearchPort(void) { + portNewCnt=0; + //查找可用的串口 + foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { + if(portNewCnt > 9) break; + m_arrNewSerial[portNewCnt]=info; + portNewCnt++; + } + + for (int i=0;i -#include -#include -#include - -class TA_SerialThread:public QThread -{ -public: - TA_SerialThread(); - ~TA_SerialThread(); - -public: - uint8_t portCnt; - uint8_t portNewCnt; - QSerialPort *m_arrSerial;//ptr point to an array,maxium port num is 5 - QSerialPortInfo *m_arrNewSerial;//ptr point to an array,maxium port num is 5 - -public: - void SearchPort(void); - void InitPortName(uint8_t portIndex,const QString &portName); - void InitPortBaudRate(uint8_t portIndex,qint32 baudRate); - void InitPortDataBits(uint8_t portIndex,QSerialPort::DataBits dataBits); - void InitPortParity(uint8_t portIndex,QSerialPort::Parity parity); - void InitPortStopBits(uint8_t portIndex,QSerialPort::StopBits stopBits); - bool OpenPort(uint8_t portIndex); - void ClosePort(uint8_t portIndex); - void SendDataBuf(uint8_t portIndex,const QByteArray &str); - QByteArray GetDataBuf(uint8_t portIndex); - -private slots: - void run(); -}; -#endif // TASERIALTHREAD_H +#ifndef TASERIALTHREAD_H +#define TASERIALTHREAD_H + +#include +#include +#include +#include + +class TA_SerialThread:public QThread +{ +public: + TA_SerialThread(); + ~TA_SerialThread(); + +public: + uint8_t portCnt; + uint8_t portNewCnt; + QSerialPort *m_arrSerial;//ptr point to an array,maxium port num is 5 + QSerialPortInfo *m_arrNewSerial;//ptr point to an array,maxium port num is 5 + +public: + void SearchPort(void); + void InitPortName(uint8_t portIndex,const QString &portName); + void InitPortBaudRate(uint8_t portIndex,qint32 baudRate); + void InitPortDataBits(uint8_t portIndex,QSerialPort::DataBits dataBits); + void InitPortParity(uint8_t portIndex,QSerialPort::Parity parity); + void InitPortStopBits(uint8_t portIndex,QSerialPort::StopBits stopBits); + bool OpenPort(uint8_t portIndex); + void ClosePort(uint8_t portIndex); + void SendDataBuf(uint8_t portIndex,const QByteArray &str); + QByteArray GetDataBuf(uint8_t portIndex); + +private slots: + void run(); +}; +#endif // TASERIALTHREAD_H diff --git a/LedOK/css.css b/LedOK/css.css new file mode 100644 index 0000000..78a4844 --- /dev/null +++ b/LedOK/css.css @@ -0,0 +1,176 @@ +QLineEdit,QComboBox,QAbstractSpinBox { + border: 1px solid #aaa; + border-radius: 3px; + padding: 2px; +} + +QGroupBox { + border: 1px solid #aaa; + border-radius: 3px; + margin-top: 0.5em; + padding-top: 0.4em; +} +QGroupBox::title { + subcontrol-origin: margin; + left: 0.5em; +} + +QComboBox::drop-down, +QAbstractSpinBox::up-button, +QAbstractSpinBox::down-button { + border: 0; +} +QComboBox::down-arrow, +QAbstractSpinBox::down-arrow { + image: url(:/res/ArrowDropDown.png); +} +QComboBox::down-arrow:on, +QAbstractSpinBox::up-arrow { + image: url(:/res/ArrowDropUp.png); +} + +QAbstractSpinBox::up-arrow:pressed { + top: -1px; +} +QAbstractSpinBox::down-arrow:pressed { + top: 1px; +} + +QCheckBox::indicator, QTreeWidget::indicator { + border-image: url(:/res/CheckBoxUnchecked.png); width: 1em; height: 1em; margin-left: 0.25em; +} +QCheckBox::indicator:checked, QTreeWidget::indicator:checked { + border-image: url(:/res/CheckBoxChecked.png); +} +QCheckBox::indicator:disabled { + background-color: #666; +} + +ExtendedGroupBox::indicator { + border-image: url(:/res/groupbox-unchecked.png); +} +ExtendedGroupBox::indicator:checked { + border-image: url(:/res/groupbox-checked.png); +} + +QScrollArea { + border : 0; +} +QScrollBar:vertical { + width: 12px; +} +QScrollBar:horizontal { + height: 12px; +} + +QMenu { + background-color: #eee; + border: 2px solid #ccc; +} +QMenu::item { + background-color: transparent; +} +QMenu::item:selected { + background-color: #8CD; +} + +QListWidget { + selection-background-color: #8ce; +} + +LoColorSelector { + border: 1px solid #aaa; + border-radius: 4px; + background-color: transparent; + padding: 3px 6px; + max-height: 30px; +} + +QTreeWidget[ssType="topList"]::item { + border-right: 1px solid #ddd; + border-bottom: 1px solid #ddd; + height: 40px; +} +QTreeWidget[ssType="topList"] QHeaderView::section { + border-top: 1px solid #aaa; + border-bottom: 1px solid #aaa; + border-left: 0; + border-right: 0; + height: 36px; +} +QTreeWidget[ssType="topList"]::item:hover { + background-color: #ddd; +} + + + +QPushButton[ssType="progManageTool"] { + border-radius: 4px; + background-color: #19c; + color: #000; + padding: 3px 6px; +} +QPushButton[ssType="progManageTool"]:hover { + background-color: #08b; + color: #fff; +} +QPushButton[ssType="progManageTool"]:pressed { + background-color: #07a; +} +QPushButton[ssType="progManageTool"]:disabled { + background-color: #bbb; + color: #777; +} + + +LoQTitleBar QPushButton { + border-radius: 4px; + icon-size: 20px; + width: 32px; + height: 28px; +} +LoQTitleBar QPushButton:press, +LoQTitleBar QPushButton:hover { + background-color: #C1C1C1; +} +LoQTitleBar QPushButton::menu-indicator { + image: none; +} + + +QToolButton[ss="MainTab"], +QToolButton[ss="CtrlTab"] { + border: none; +} +QToolButton[ss="MainTab"]:checked, +QToolButton[ss="MainTab"]:hover { + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ddd, stop: 1.0 #8cd); + font-size: 15px; + color: #04d; +} +QToolButton[ss="CtrlTab"]:checked, +QToolButton[ss="CtrlTab"]:hover { + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eee, stop: 1.0 #ade); + font-size: 15px; + color: #04d; +} + + +QPushButton#bnSelectFile { + border-radius: 4px; + background-color: #19c; + border: 1px solid #888; + padding: 3px 6px; +} +QPushButton#bnSelectFile:pressed { + background: transparent; +} + +QPushButton[style="multiTool"] { + border-radius: 4px; + padding: 3px 6px; +} +QPushButton[style="multiTool"]:hover { + background-color: rgba(226,226,226,1); +} + diff --git a/LedOK/wDevicesManager/controlpowerschedule.cpp b/LedOK/device/controlpowerschedule.cpp similarity index 97% rename from LedOK/wDevicesManager/controlpowerschedule.cpp rename to LedOK/device/controlpowerschedule.cpp index 17947f2..1405429 100644 --- a/LedOK/wDevicesManager/controlpowerschedule.cpp +++ b/LedOK/device/controlpowerschedule.cpp @@ -1,557 +1,555 @@ -#include "controlpowerschedule.h" -#include "ui_controlpowerschedule.h" - -#include -#include -#include -#include -#include -#include -#include -#include "cfg.h" -#include "QSettings" -#include "base/x_spinboxdelegate.h" -#include "base/x_timeeditdelegate.h" -#include "base/x_checkboxdelegate.h" -#include "tools.h" - -ControlPowerSchedule::ControlPowerSchedule(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlPowerSchedule) -{ - m_pLedlist=list; - ui->setupUi(this); - ui->labelPowerScheduleTip->setVisible(false); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - ui->pushButtonAdd->setProperty("ssType", "progManageTool"); - ui->pushButtonAdd->setFlat(true); - ui->pushButtonDelete->setProperty("ssType", "progManageTool"); - ui->pushButtonDelete->setFlat(true); - ui->pushButtonClear->setProperty("ssType", "progManageTool"); - ui->pushButtonClear->setFlat(true); - ui->pushButtonApply->setProperty("ssType", "progManageTool"); - ui->pushButtonApply->setFlat(true); - ui->pushButtonImport->setProperty("ssType", "progManageTool"); - ui->pushButtonExport->setProperty("ssType", "progManageTool"); - ui->pushButtonReadback->setProperty("ssType", "progManageTool"); - ui->pushButtonClearSchedule->setProperty("ssType", "progManageTool"); - - m_pModel = new QStandardItemModel(this); - m_pModel->setColumnCount(10); - m_pModel->setHeaderData(0,Qt::Horizontal, tr("Power On State")); - m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time")); - m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time")); - m_pModel->setHeaderData(3,Qt::Horizontal, tr("SUN")); - m_pModel->setHeaderData(4,Qt::Horizontal, tr("MON")); - m_pModel->setHeaderData(5,Qt::Horizontal, tr("TUE")); - m_pModel->setHeaderData(6,Qt::Horizontal, tr("WED")); - m_pModel->setHeaderData(7,Qt::Horizontal, tr("THU")); - m_pModel->setHeaderData(8,Qt::Horizontal, tr("FRI")); - m_pModel->setHeaderData(9,Qt::Horizontal, tr("SAT")); - ui->tableView->setModel(m_pModel); - - X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this); - ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate); - ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate); - X_CheckBoxDelegate *WeekDelegate=new X_CheckBoxDelegate(this); - ui->tableView->setItemDelegateForColumn(3,WeekDelegate); - ui->tableView->setItemDelegateForColumn(4,WeekDelegate); - ui->tableView->setItemDelegateForColumn(5,WeekDelegate); - ui->tableView->setItemDelegateForColumn(6,WeekDelegate); - ui->tableView->setItemDelegateForColumn(7,WeekDelegate); - ui->tableView->setItemDelegateForColumn(8,WeekDelegate); - ui->tableView->setItemDelegateForColumn(9,WeekDelegate); - - - ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(); - ui->tableView->setItemDelegateForColumn(0, readOnlyDelegate); //设置某列只读 - - ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - // ui->tableView->verticalHeader()->hide(); - ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); - ui->tableView->setFocusPolicy(Qt::NoFocus); - - - MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) - - connect(ui->pushButtonAdd,SIGNAL(clicked()),this,SLOT(OnClickAdd())); - connect(ui->pushButtonImport,SIGNAL(clicked()),this,SLOT(OnClickImport())); - connect(ui->pushButtonExport,SIGNAL(clicked()),this,SLOT(OnClickExport())); - connect(ui->pushButtonDelete,SIGNAL(clicked()),this,SLOT(OnClickDelete())); - connect(ui->pushButtonClear,SIGNAL(clicked()),this,SLOT(OnClickClear())); - connect(ui->pushButtonApply,SIGNAL(clicked()),this,SLOT(OnClickApply())); - connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnClickReadback())); - connect(ui->pushButtonClearSchedule,SIGNAL(clicked()),this,SLOT(OnClickClearSchedule())); - - -} - -ControlPowerSchedule::~ControlPowerSchedule() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void ControlPowerSchedule::refreshLable() -{ - ui->pushButtonAdd->setText(tr("Add")); - ui->pushButtonApply->setText(tr("Apply")); - ui->pushButtonClear->setText(tr("Clear")); - ui->pushButtonDelete->setText(tr("Delete")); - ui->pushButtonImport->setText(tr("Import")); - ui->pushButtonExport->setText(tr("Export")); -} - -void ControlPowerSchedule::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()==1) - { - ui->pushButtonReadback->setEnabled(true); - } - else { - ui->pushButtonReadback->setEnabled(false); - } - MACRO_DEFINE_CONTROL_FUNC3 - -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlPowerSchedule::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetTimingScreenTask") - { - JieXiJsonTaskPower(jsonObject["screenTask"].toObject()); - } - else if(strType == "SetTimingScreenTask") - { - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlPowerSchedule::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetTimingScreenTask") - { - emit sigHaveSchedule(JieXiJsonTaskPower(jsonObject["screenTask"].toObject())); - } - } - } -} - -void ControlPowerSchedule::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_PowerControl) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlPowerSchedule::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetTimingScreenTask"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - -} -void ControlPowerSchedule::OnClickAdd() -{ - QList Item; - Item.append(new QStandardItem(tr("On"))); - Item.append(new QStandardItem("00:00")); - Item.append(new QStandardItem("01:00")); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); - - Item.at(0)->setTextAlignment(Qt::AlignCenter); - Item.at(1)->setTextAlignment(Qt::AlignCenter); - Item.at(2)->setTextAlignment(Qt::AlignCenter); - m_pModel->appendRow(Item); - //m_lineEidt[i]->installEventFilter(this); - //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); - int i=m_pModel->rowCount()-1; - m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); - - if(m_pModel->rowCount()>0) - { - ui->labelPowerScheduleTip->setVisible(true); - - } - else { - ui->labelPowerScheduleTip->setVisible(false); - - } -} -void ControlPowerSchedule::OnClickImport(){ - QSettings settings; - QString strDir="/"; - if(settings.value("lasOpendFileDlgtDir").isValid()) - { - strDir=settings.value("lasOpendFileDlgtDir").toString(); - } - QFileDialog dlg; - QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog", - strDir, - tr("PowerSchedule (*.pjs)")); - if(strBrightScheduleFile.isEmpty()) - return; - QFile fJson(strBrightScheduleFile); - if(fJson.open(QIODevice::ReadOnly)){ - QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll()); - QJsonObject oTaskPower=jBrightSchedule.object(); - JieXiJsonTaskPower(oTaskPower); - fJson.close(); - } -} -bool ControlPowerSchedule::JieXiJsonTaskPower(QJsonObject oTaskPower) -{ - OnClickClear(); - QJsonArray oSchedules; - oSchedules=oTaskPower["schedules"].toArray(); - if(oSchedules.count()>0) - { - ui->labelPowerScheduleTip->setVisible(true); - } - else - { - ui->labelPowerScheduleTip->setVisible(false); - } - //bool bHaveSchedule=false; - for(int i=0;i Item; - Item.append(new QStandardItem(tr("On"))); - Item.append(new QStandardItem(oSchedule["startTime"].toString())); - Item.append(new QStandardItem(oSchedule["endTime"].toString())); - Item.at(0)->setTextAlignment(Qt::AlignCenter); - Item.at(1)->setTextAlignment(Qt::AlignCenter); - Item.at(2)->setTextAlignment(Qt::AlignCenter); - m_pModel->appendRow(Item); - if(oSchedule["filterType"].toString()=="None") - { - m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); - } - else if(oSchedule["filterType"].toString()=="Week") - { - QJsonArray oWeeks; - oWeeks=oSchedule["weekFilter"].toArray(); - for(int m=0;m<7;m++) - { - bool bHave=false; - for (int j=0;jsetData(m_pModel->index(i, m+3),bHave,Qt::UserRole); - } - - - } - - - - - } - if(oSchedules.count()>0) - return true; - else { - return false; - } -} -void ControlPowerSchedule::OnClickExport(){ - QSettings settings; - QString strDir="/"; - if(settings.value("lasOpendFileDlgtDir").isValid()) { - strDir=settings.value("lasOpendFileDlgtDir").toString(); - } - QFileDialog dlg; - QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("PowerSchedule (*.pjs)")); - - if( saveFileName.isEmpty() ) - return; - settings.setValue("lasOpendFileDlgtDir",saveFileName); - QJsonObject oTaskPower=GetJsonObjectPowerSchedule(); - QJsonDocument tPowerScheduleJsonDoc; - tPowerScheduleJsonDoc.setObject(oTaskPower); - - QFile f(saveFileName); - if(f.open(QIODevice::WriteOnly)) { - f.write(tPowerScheduleJsonDoc.toJson()); - f.close(); - } -} -void ControlPowerSchedule::OnClickDelete() -{ - if(m_pModel->rowCount()>0) - { - QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); - if(selected.count()>0) - m_pModel->removeRows(selected.begin()->row(),selected.count()); - } - if(m_pModel->rowCount()>0) - { - ui->labelPowerScheduleTip->setVisible(true); - } - else { - ui->labelPowerScheduleTip->setVisible(false); - } -} -void ControlPowerSchedule:: OnClickClear() -{ - //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); - - if(m_pModel->rowCount()>0) - { - m_pModel->removeRows(0,m_pModel->rowCount()); - - } - if(m_pModel->rowCount()>0) - { - ui->labelPowerScheduleTip->setVisible(true); - - } - else { - ui->labelPowerScheduleTip->setVisible(false); - - } -} -extern QWidget *gMainWin; -void ControlPowerSchedule::OnClickApply() { - if(m_pLedlist==nullptr) return; - if(m_pLedlist->count()<=1){ - if(m_pLedCard==nullptr||m_pLedlist->count()==0){ - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - } - if(m_pModel->rowCount()<=0) { - auto btn = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Clear schedule task?")); - if(btn == QMessageBox::Yes) { - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "CleanTimingScreenTask"); - MACRO_DEFINE_TIPDLG_FUCN(tr("CleanTimingScreenTask"),tr("Success"),tr("failed")) - } - } else { - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetTimingScreenTask"); - QJsonObject oTaskPower=GetJsonObjectPowerSchedule(); - json.insert("screenTask", oTaskPower); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetTimingScreenTask"),tr("Success"),tr("failed")) - } - -} -void ControlPowerSchedule::OnClickReadback() { - if(m_pLedlist==nullptr) return; - if(m_pLedlist->count()<=1) { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) { - QMessageBox::information(gMainWin, tr("Tip"),tr("NoSelectedController")); - return; - } - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetTimingScreenTask"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetTimingScreenTask"),tr("Success"),tr("failed")) - -} -void ControlPowerSchedule::OnClickClearSchedule() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - QMessageBox::information(gMainWin, tr("Tip"),tr("NoSelectedController")); - return; - } - } - auto btn = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Clear schedule task?")); - if(btn == QMessageBox::Yes) { - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "CleanTimingScreenTask"); - MACRO_DEFINE_TIPDLG_FUCN(tr("CleanTimingScreenTask"),tr("Success"),tr("failed")) - } -} -QJsonObject ControlPowerSchedule::GetJsonObjectPowerSchedule() -{ - QJsonObject oTaskPower; - QJsonArray oItems; - - oTaskPower["createDate"] = QJsonValue::Null; - oTaskPower["createBy"] = "alahover"; - oTaskPower["name"] = "TimingScreen"; - - QJsonArray oSchedules; - for(int i=0; irowCount(); i++) - { - - QJsonObject oSchedule; - oSchedule["timeType"] = "Range"; - oSchedule["startTime"] = m_pModel->data(m_pModel->index(i, 1)).toString();; - oSchedule["endTime"] = m_pModel->data(m_pModel->index(i, 2)).toString();; - oSchedule["dateType"] = "All"; - oSchedule["startDate"] = QJsonValue::Null; - oSchedule["endDate"] = QJsonValue::Null; - oSchedule["monthFilter"] = QJsonArray(); - - bool bSun=m_pModel->data(m_pModel->index(i, 3),Qt::UserRole).toBool(); - bool bMon=m_pModel->data(m_pModel->index(i, 4),Qt::UserRole).toBool(); - bool bTur=m_pModel->data(m_pModel->index(i, 5),Qt::UserRole).toBool(); - bool bWed=m_pModel->data(m_pModel->index(i, 6),Qt::UserRole).toBool(); - bool bThu=m_pModel->data(m_pModel->index(i, 7),Qt::UserRole).toBool(); - bool bFri=m_pModel->data(m_pModel->index(i, 8),Qt::UserRole).toBool(); - bool bSat=m_pModel->data(m_pModel->index(i, 9),Qt::UserRole).toBool(); - - - if(bMon && bTur && bWed && bThu && bFri && bSat && bSun) - { - oSchedule["filterType"] = "None"; - oSchedule["weekFilter"] = QJsonArray(); - - } - else { - oSchedule["filterType"] = "Week"; - QJsonArray tempArray; - if( bSun) - { - tempArray.append(0); - } - if(bMon) - { - tempArray.append(1); - } - if(bTur) - { - tempArray.append(2); - } - if( bWed) - { - tempArray.append(3); - } - if( bThu) - { - tempArray.append(4); - } - if( bFri) - { - tempArray.append(5); - } - if( bSat) - { - tempArray.append(6); - } - - - oSchedule["weekFilter"] = tempArray; - - } - - - oSchedules.append(oSchedule); - } - - oTaskPower["schedules"] = oSchedules; - return oTaskPower; - -} - -void ControlPowerSchedule::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} +#include "controlpowerschedule.h" +#include "ui_controlpowerschedule.h" + +#include +#include +#include +#include +#include +#include +#include +#include "cfg.h" +#include "QSettings" +#include "base/x_spinboxdelegate.h" +#include "base/x_timeeditdelegate.h" +#include "base/x_checkboxdelegate.h" +#include "tools.h" + +ControlPowerSchedule::ControlPowerSchedule(QWidget *parent,QList *list) : + QWidget(parent), + ui(new Ui::ControlPowerSchedule) +{ + m_pLedlist=list; + ui->setupUi(this); + ui->labelPowerScheduleTip->setVisible(false); + refreshLable(); +setStyleSheet(css); + ui->pushButtonAdd->setProperty("ssType", "progManageTool"); + ui->pushButtonAdd->setFlat(true); + ui->pushButtonDelete->setProperty("ssType", "progManageTool"); + ui->pushButtonDelete->setFlat(true); + ui->pushButtonClear->setProperty("ssType", "progManageTool"); + ui->pushButtonClear->setFlat(true); + ui->pushButtonApply->setProperty("ssType", "progManageTool"); + ui->pushButtonApply->setFlat(true); + ui->pushButtonImport->setProperty("ssType", "progManageTool"); + ui->pushButtonExport->setProperty("ssType", "progManageTool"); + ui->pushButtonReadback->setProperty("ssType", "progManageTool"); + ui->pushButtonClearSchedule->setProperty("ssType", "progManageTool"); + + m_pModel = new QStandardItemModel(this); + m_pModel->setColumnCount(10); + m_pModel->setHeaderData(0,Qt::Horizontal, tr("Power On State")); + m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time")); + m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time")); + m_pModel->setHeaderData(3,Qt::Horizontal, tr("SUN")); + m_pModel->setHeaderData(4,Qt::Horizontal, tr("MON")); + m_pModel->setHeaderData(5,Qt::Horizontal, tr("TUE")); + m_pModel->setHeaderData(6,Qt::Horizontal, tr("WED")); + m_pModel->setHeaderData(7,Qt::Horizontal, tr("THU")); + m_pModel->setHeaderData(8,Qt::Horizontal, tr("FRI")); + m_pModel->setHeaderData(9,Qt::Horizontal, tr("SAT")); + ui->tableView->setModel(m_pModel); + + X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this); + ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate); + ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate); + X_CheckBoxDelegate *WeekDelegate=new X_CheckBoxDelegate(this); + ui->tableView->setItemDelegateForColumn(3,WeekDelegate); + ui->tableView->setItemDelegateForColumn(4,WeekDelegate); + ui->tableView->setItemDelegateForColumn(5,WeekDelegate); + ui->tableView->setItemDelegateForColumn(6,WeekDelegate); + ui->tableView->setItemDelegateForColumn(7,WeekDelegate); + ui->tableView->setItemDelegateForColumn(8,WeekDelegate); + ui->tableView->setItemDelegateForColumn(9,WeekDelegate); + + + ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(); + ui->tableView->setItemDelegateForColumn(0, readOnlyDelegate); //设置某列只读 + + ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + // ui->tableView->verticalHeader()->hide(); + ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + ui->tableView->setFocusPolicy(Qt::NoFocus); + + + MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) + + connect(ui->pushButtonAdd,SIGNAL(clicked()),this,SLOT(OnClickAdd())); + connect(ui->pushButtonImport,SIGNAL(clicked()),this,SLOT(OnClickImport())); + connect(ui->pushButtonExport,SIGNAL(clicked()),this,SLOT(OnClickExport())); + connect(ui->pushButtonDelete,SIGNAL(clicked()),this,SLOT(OnClickDelete())); + connect(ui->pushButtonClear,SIGNAL(clicked()),this,SLOT(OnClickClear())); + connect(ui->pushButtonApply,SIGNAL(clicked()),this,SLOT(OnClickApply())); + connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnClickReadback())); + connect(ui->pushButtonClearSchedule,SIGNAL(clicked()),this,SLOT(OnClickClearSchedule())); + + +} + +ControlPowerSchedule::~ControlPowerSchedule() +{ + delete ui; + if(pHpptClient != nullptr) + { + qDebug() <<"delete pHpptClient in ~NetComm"; + delete pHpptClient; + pHpptClient=nullptr; + } + if(pHpptClientAll != nullptr) + { + qDebug() <<"delete pHpptClientAll in ~NetComm"; + delete pHpptClientAll; + pHpptClientAll=nullptr; + } +} +void ControlPowerSchedule::refreshLable() +{ + ui->pushButtonAdd->setText(tr("Add")); + ui->pushButtonApply->setText(tr("Apply")); + ui->pushButtonClear->setText(tr("Clear")); + ui->pushButtonDelete->setText(tr("Delete")); + ui->pushButtonImport->setText(tr("Import")); + ui->pushButtonExport->setText(tr("Export")); +} + +void ControlPowerSchedule::onSelectedDeviceList(QList *list) +{ + m_pLedlist=list; + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()==1) + { + ui->pushButtonReadback->setEnabled(true); + } + else { + ui->pushButtonReadback->setEnabled(false); + } + MACRO_DEFINE_CONTROL_FUNC3 + +} +//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 +void ControlPowerSchedule::OnProHttpResponse(QString url, QString postMD5, QByteArray data) +{ + Q_UNUSED(postMD5) + //qDebug()<< url + "\r\n"+m_strUrl; + if(url == m_strUrl) + { + QJsonParseError parseJsonErr; + QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); + if(!(parseJsonErr.error == QJsonParseError::NoError)) + { + if(data.size()==0) + qDebug()<<"json is empty"; + else + qDebug()<count()!=1) + return; + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "GetTimingScreenTask"); + HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); + +} +void ControlPowerSchedule::OnClickAdd() +{ + QList Item; + Item.append(new QStandardItem(tr("On"))); + Item.append(new QStandardItem("00:00")); + Item.append(new QStandardItem("01:00")); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); + + Item.at(0)->setTextAlignment(Qt::AlignCenter); + Item.at(1)->setTextAlignment(Qt::AlignCenter); + Item.at(2)->setTextAlignment(Qt::AlignCenter); + m_pModel->appendRow(Item); + //m_lineEidt[i]->installEventFilter(this); + //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); + int i=m_pModel->rowCount()-1; + m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); + + if(m_pModel->rowCount()>0) + { + ui->labelPowerScheduleTip->setVisible(true); + + } + else { + ui->labelPowerScheduleTip->setVisible(false); + + } +} +void ControlPowerSchedule::OnClickImport(){ + QSettings settings; + QString strDir="/"; + if(settings.value("lasOpendFileDlgtDir").isValid()) + { + strDir=settings.value("lasOpendFileDlgtDir").toString(); + } + QFileDialog dlg; + QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog", + strDir, + tr("PowerSchedule (*.pjs)")); + if(strBrightScheduleFile.isEmpty()) + return; + QFile fJson(strBrightScheduleFile); + if(fJson.open(QIODevice::ReadOnly)){ + QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll()); + QJsonObject oTaskPower=jBrightSchedule.object(); + JieXiJsonTaskPower(oTaskPower); + fJson.close(); + } +} +bool ControlPowerSchedule::JieXiJsonTaskPower(QJsonObject oTaskPower) +{ + OnClickClear(); + QJsonArray oSchedules; + oSchedules=oTaskPower["schedules"].toArray(); + if(oSchedules.count()>0) + { + ui->labelPowerScheduleTip->setVisible(true); + } + else + { + ui->labelPowerScheduleTip->setVisible(false); + } + //bool bHaveSchedule=false; + for(int i=0;i Item; + Item.append(new QStandardItem(tr("On"))); + Item.append(new QStandardItem(oSchedule["startTime"].toString())); + Item.append(new QStandardItem(oSchedule["endTime"].toString())); + Item.at(0)->setTextAlignment(Qt::AlignCenter); + Item.at(1)->setTextAlignment(Qt::AlignCenter); + Item.at(2)->setTextAlignment(Qt::AlignCenter); + m_pModel->appendRow(Item); + if(oSchedule["filterType"].toString()=="None") + { + m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); + } + else if(oSchedule["filterType"].toString()=="Week") + { + QJsonArray oWeeks; + oWeeks=oSchedule["weekFilter"].toArray(); + for(int m=0;m<7;m++) + { + bool bHave=false; + for (int j=0;jsetData(m_pModel->index(i, m+3),bHave,Qt::UserRole); + } + + + } + + + + + } + if(oSchedules.count()>0) + return true; + else { + return false; + } +} +void ControlPowerSchedule::OnClickExport(){ + QSettings settings; + QString strDir="/"; + if(settings.value("lasOpendFileDlgtDir").isValid()) { + strDir=settings.value("lasOpendFileDlgtDir").toString(); + } + QFileDialog dlg; + QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("PowerSchedule (*.pjs)")); + + if( saveFileName.isEmpty() ) + return; + settings.setValue("lasOpendFileDlgtDir",saveFileName); + QJsonObject oTaskPower=GetJsonObjectPowerSchedule(); + QJsonDocument tPowerScheduleJsonDoc; + tPowerScheduleJsonDoc.setObject(oTaskPower); + + QFile f(saveFileName); + if(f.open(QIODevice::WriteOnly)) { + f.write(tPowerScheduleJsonDoc.toJson()); + f.close(); + } +} +void ControlPowerSchedule::OnClickDelete() +{ + if(m_pModel->rowCount()>0) + { + QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); + if(selected.count()>0) + m_pModel->removeRows(selected.begin()->row(),selected.count()); + } + if(m_pModel->rowCount()>0) + { + ui->labelPowerScheduleTip->setVisible(true); + } + else { + ui->labelPowerScheduleTip->setVisible(false); + } +} +void ControlPowerSchedule:: OnClickClear() +{ + //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); + + if(m_pModel->rowCount()>0) + { + m_pModel->removeRows(0,m_pModel->rowCount()); + + } + if(m_pModel->rowCount()>0) + { + ui->labelPowerScheduleTip->setVisible(true); + + } + else { + ui->labelPowerScheduleTip->setVisible(false); + + } +} +extern QWidget *gMainWin; +void ControlPowerSchedule::OnClickApply() { + if(m_pLedlist==nullptr) return; + if(m_pLedlist->count()<=1){ + if(m_pLedCard==nullptr||m_pLedlist->count()==0){ + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + } + if(m_pModel->rowCount()<=0) { + auto btn = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Clear schedule task?")); + if(btn == QMessageBox::Yes) { + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "CleanTimingScreenTask"); + MACRO_DEFINE_TIPDLG_FUCN(tr("CleanTimingScreenTask"),tr("Success"),tr("failed")) + } + } else { + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "SetTimingScreenTask"); + QJsonObject oTaskPower=GetJsonObjectPowerSchedule(); + json.insert("screenTask", oTaskPower); + MACRO_DEFINE_TIPDLG_FUCN(tr("SetTimingScreenTask"),tr("Success"),tr("failed")) + } + +} +void ControlPowerSchedule::OnClickReadback() { + if(m_pLedlist==nullptr) return; + if(m_pLedlist->count()<=1) { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) { + QMessageBox::information(gMainWin, tr("Tip"),tr("NoSelectedController")); + return; + } + } + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "GetTimingScreenTask"); + MACRO_DEFINE_TIPDLG_FUCN(tr("GetTimingScreenTask"),tr("Success"),tr("failed")) + +} +void ControlPowerSchedule::OnClickClearSchedule() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()<=1) + { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + QMessageBox::information(gMainWin, tr("Tip"),tr("NoSelectedController")); + return; + } + } + auto btn = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Clear schedule task?")); + if(btn == QMessageBox::Yes) { + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "CleanTimingScreenTask"); + MACRO_DEFINE_TIPDLG_FUCN(tr("CleanTimingScreenTask"),tr("Success"),tr("failed")) + } +} +QJsonObject ControlPowerSchedule::GetJsonObjectPowerSchedule() +{ + QJsonObject oTaskPower; + QJsonArray oItems; + + oTaskPower["createDate"] = QJsonValue::Null; + oTaskPower["createBy"] = "alahover"; + oTaskPower["name"] = "TimingScreen"; + + QJsonArray oSchedules; + for(int i=0; irowCount(); i++) + { + + QJsonObject oSchedule; + oSchedule["timeType"] = "Range"; + oSchedule["startTime"] = m_pModel->data(m_pModel->index(i, 1)).toString();; + oSchedule["endTime"] = m_pModel->data(m_pModel->index(i, 2)).toString();; + oSchedule["dateType"] = "All"; + oSchedule["startDate"] = QJsonValue::Null; + oSchedule["endDate"] = QJsonValue::Null; + oSchedule["monthFilter"] = QJsonArray(); + + bool bSun=m_pModel->data(m_pModel->index(i, 3),Qt::UserRole).toBool(); + bool bMon=m_pModel->data(m_pModel->index(i, 4),Qt::UserRole).toBool(); + bool bTur=m_pModel->data(m_pModel->index(i, 5),Qt::UserRole).toBool(); + bool bWed=m_pModel->data(m_pModel->index(i, 6),Qt::UserRole).toBool(); + bool bThu=m_pModel->data(m_pModel->index(i, 7),Qt::UserRole).toBool(); + bool bFri=m_pModel->data(m_pModel->index(i, 8),Qt::UserRole).toBool(); + bool bSat=m_pModel->data(m_pModel->index(i, 9),Qt::UserRole).toBool(); + + + if(bMon && bTur && bWed && bThu && bFri && bSat && bSun) + { + oSchedule["filterType"] = "None"; + oSchedule["weekFilter"] = QJsonArray(); + + } + else { + oSchedule["filterType"] = "Week"; + QJsonArray tempArray; + if( bSun) + { + tempArray.append(0); + } + if(bMon) + { + tempArray.append(1); + } + if(bTur) + { + tempArray.append(2); + } + if( bWed) + { + tempArray.append(3); + } + if( bThu) + { + tempArray.append(4); + } + if( bFri) + { + tempArray.append(5); + } + if( bSat) + { + tempArray.append(6); + } + + + oSchedule["weekFilter"] = tempArray; + + } + + + oSchedules.append(oSchedule); + } + + oTaskPower["schedules"] = oSchedules; + return oTaskPower; + +} + +void ControlPowerSchedule::DeletePostingDlg() +{ + if(m_PostingDlg!=nullptr) + { + delete m_PostingDlg; + m_PostingDlg=nullptr; + } +} diff --git a/LedOK/wDevicesManager/controlpowerschedule.h b/LedOK/device/controlpowerschedule.h similarity index 95% rename from LedOK/wDevicesManager/controlpowerschedule.h rename to LedOK/device/controlpowerschedule.h index f7d1c75..1222321 100644 --- a/LedOK/wDevicesManager/controlpowerschedule.h +++ b/LedOK/device/controlpowerschedule.h @@ -1,77 +1,77 @@ -#ifndef CONTROLPOWERSCHEDULE_H -#define CONTROLPOWERSCHEDULE_H - -#include -#include -#include -#include -#include -#include -namespace Ui { -class ControlPowerSchedule; -} - -class ControlPowerSchedule : public QWidget -{ - Q_OBJECT - -public: - explicit ControlPowerSchedule(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlPowerSchedule(); -private: - Ui::ControlPowerSchedule *ui; -protected slots: - void refreshLable(); - void OnClickAdd(); - void OnClickImport(); - void OnClickExport(); - void OnClickDelete(); - void OnClickClear(); - void OnClickApply(); - void OnClickReadback(); - void OnClickClearSchedule(); - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigSend(QJsonObject &,QString); - void sigHaveSchedule(bool); - - protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; - QStandardItemModel * m_pModel; - bool JieXiJsonTaskPower(QJsonObject oTaskPower); - QJsonObject GetJsonObjectPowerSchedule(); - - -}; -class ReadOnlyDelegate: public QStyledItemDelegate -{ - Q_OBJECT -public: - ReadOnlyDelegate(QWidget *parent = nullptr):QStyledItemDelegate(parent) - {} - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, -const QModelIndex &index) const override //final - { - Q_UNUSED(parent) - Q_UNUSED(option) - Q_UNUSED(index) - return nullptr; - } -}; -#endif // CONTROLPOWERSCHEDULE_H +#ifndef CONTROLPOWERSCHEDULE_H +#define CONTROLPOWERSCHEDULE_H + +#include +#include +#include +#include +#include +#include +namespace Ui { +class ControlPowerSchedule; +} + +class ControlPowerSchedule : public QWidget +{ + Q_OBJECT + +public: + explicit ControlPowerSchedule(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); + ~ControlPowerSchedule(); + void refreshLable(); +private: + Ui::ControlPowerSchedule *ui; +protected slots: + void OnClickAdd(); + void OnClickImport(); + void OnClickExport(); + void OnClickDelete(); + void OnClickClear(); + void OnClickApply(); + void OnClickReadback(); + void OnClickClearSchedule(); + //类似的控制操作信号和槽函数和变量定义 + signals: + void sigSend(QJsonObject &,QString); + void sigHaveSchedule(bool); + + protected slots: + void DeletePostingDlg(); + void OnProHttpResponse(QString url, QString postMD5, QByteArray data); + void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); + void onSelectedDeviceList(QList *); + void onReadbackAllThisPage(); + void OnControlTypeSwitchIndexChanged(int index); + private: + QList *m_pLedlist=nullptr; + LedCard *m_pLedCard = nullptr; + LedCard *m_oldLedlist = nullptr; + HpptClient *pHpptClient = nullptr; + HpptClient *pHpptClientAll = nullptr; + QString m_strUrl=""; + LoEmptyDialog * m_PostingDlg=nullptr; + QTimer *m_pGetAskTimer=nullptr; + bool m_bSelected=false; + QStandardItemModel * m_pModel; + bool JieXiJsonTaskPower(QJsonObject oTaskPower); + QJsonObject GetJsonObjectPowerSchedule(); + + +}; +class ReadOnlyDelegate: public QStyledItemDelegate +{ + Q_OBJECT +public: + ReadOnlyDelegate(QWidget *parent = nullptr):QStyledItemDelegate(parent) + {} + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, +const QModelIndex &index) const override //final + { + Q_UNUSED(parent) + Q_UNUSED(option) + Q_UNUSED(index) + return nullptr; + } +}; +#endif // CONTROLPOWERSCHEDULE_H diff --git a/LedOK/wDevicesManager/controlpowerschedule.ui b/LedOK/device/controlpowerschedule.ui similarity index 96% rename from LedOK/wDevicesManager/controlpowerschedule.ui rename to LedOK/device/controlpowerschedule.ui index c608179..22d0305 100644 --- a/LedOK/wDevicesManager/controlpowerschedule.ui +++ b/LedOK/device/controlpowerschedule.ui @@ -1,255 +1,255 @@ - - - ControlPowerSchedule - - - - 0 - 0 - 422 - 300 - - - - Form - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - Edit area - - - - - - - - 10 - - - 0 - - - - - - 60 - 30 - - - - Add - - - - - - - - 60 - 30 - - - - Delete - - - - - - - - 60 - 30 - - - - Clear - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Import - - - - - - - - 0 - 30 - - - - Export - - - - - - - - - It is power off state outside the schedule time period - - - - - - - background-color: #FFFFFF; - - - - - - - - - - - - Send command - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 60 - 30 - - - - Apply - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Clear Schedule - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Readback - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - - + + + ControlPowerSchedule + + + + 0 + 0 + 422 + 300 + + + + Form + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + Edit area + + + + + + + + 10 + + + 0 + + + + + + 60 + 30 + + + + Add + + + + + + + + 60 + 30 + + + + Delete + + + + + + + + 60 + 30 + + + + Clear + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 30 + + + + Import + + + + + + + + 0 + 30 + + + + Export + + + + + + + + + It is power off state outside the schedule time period + + + + + + + background-color: #FFFFFF; + + + + + + + + + + + + Send command + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 60 + 30 + + + + Apply + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 30 + + + + Clear Schedule + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 30 + + + + Readback + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + diff --git a/LedOK/device/controlpowerwidget.cpp b/LedOK/device/controlpowerwidget.cpp new file mode 100644 index 0000000..f2cf965 --- /dev/null +++ b/LedOK/device/controlpowerwidget.cpp @@ -0,0 +1,155 @@ +#include "controlpowerwidget.h" +#include "gutil/qgui.h" +#include "globaldefine.h" +#include "base/waitingdlg.h" +#include "tools.h" +#include + +ControlPowerWidget::ControlPowerWidget(QWidget *parent, QList *list) : QWidget(parent) { + auto vBox = new VBox(this); + + lbScreenCfg = new QLabel; + lbScreenCfg->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbScreenCfg); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + fdManual = new QRadioButton; + hBox->addWidget(fdManual); + hBox->addSpacing(40); + + fdSchedule = new QRadioButton; + hBox->addWidget(fdSchedule); + hBox->addStretch(); + + auto stack = new QStackedLayout(vBox); + { + auto vBox = new VBox(stack); + vBox->addSpacing(20); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + lbScreen = new QLabel; + hBox->addWidget(lbScreen); + + fdScreen = new SwitchControl; + fdScreen->setMinimumSize(QSize(80, 33)); + fdScreen->setSliderColor(QColor(0, 0, 0), QColor(0, 160, 230)); + fdScreen->setBgColor(QColor(200,200,200), QColor(0x00cc00)); + fdScreen->setTextColor(QColor(100,100,100), QColor(0, 160, 230)); + connect(fdScreen, &SwitchControl::checkedChanged, this, [this](bool checked) { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetScreenOn"); + json.insert("_type", "SetScreenOn"); + json.insert("on", checked); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, (checked ? tr("SetScreenOn") : tr("SetScreenOff"))+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + if(checked) foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetScreenOn")) + } + else foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetScreenOff")) + } + } + }); + hBox->addWidget(fdScreen); + hBox->addStretch(); + + btnScreenGet = new QPushButton; + btnScreenGet->setMinimumSize(QSize(60, 30)); + btnScreenGet->setProperty("ssType", "progManageTool"); + connect(btnScreenGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "IsScreenOn"); + json.insert("_type", "IsScreenOn"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("IsScreenOn")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdScreen->setCheckedStatus(json["on"].toBool()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["on"].toBool() ? tr("On") : tr("Off"); + gFdResInfo->append(cardId+" "+tr("IsScreenOn")+" "+err); + }); + } + } + }); + vBox->addWidget(btnScreenGet, 0, Qt::AlignCenter); + vBox->addStretch(); + } + m_pSchedule = new ControlPowerSchedule(this, list); + connect(m_pSchedule, &ControlPowerSchedule::sigHaveSchedule, this, [=](bool b) { + if(b) fdSchedule->setChecked(true); + else fdManual->setChecked(true); + }); + stack->addWidget(m_pSchedule); + + connect(fdSchedule, &QRadioButton::toggled, stack, &QStackedLayout::setCurrentIndex); + fdManual->setChecked(true); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void ControlPowerWidget::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void ControlPowerWidget::init() { + bool isSingle = gSelCards->count()==1; + if(! isSingle) return; + auto card = gSelCards->at(0); + + QJsonObject json; + json.insert("_id", "IsScreenOn"); + json.insert("_type", "IsScreenOn"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdScreen->setCheckedStatus(json["on"].toBool()); + }); +} + +void ControlPowerWidget::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void ControlPowerWidget::transUi() { + lbScreenCfg->setText(tr("Power Configuration")); + fdManual->setText(tr("Manual")); + fdSchedule->setText(tr("Schedule")); + + lbScreen->setText(tr("Power")); + fdScreen->setText(tr("Off"), tr("On")); + btnScreenGet->setText(tr("Readback")); + + m_pSchedule->refreshLable(); +} diff --git a/LedOK/device/controlpowerwidget.h b/LedOK/device/controlpowerwidget.h new file mode 100644 index 0000000..04e507b --- /dev/null +++ b/LedOK/device/controlpowerwidget.h @@ -0,0 +1,29 @@ +#ifndef CONTROLPOWERWIDGET_H +#define CONTROLPOWERWIDGET_H + +#include +#include +#include + +class ControlPowerWidget : public QWidget { + Q_OBJECT +public: + explicit ControlPowerWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); +protected: + void showEvent(QShowEvent *event) override; + void init(); + void changeEvent(QEvent *) override; + void transUi(); +private: + ControlPowerSchedule *m_pSchedule=nullptr; + + QLabel *lbScreenCfg; + QRadioButton *fdManual; + QRadioButton *fdSchedule; + + QLabel *lbScreen; + SwitchControl *fdScreen; + QPushButton *btnScreenGet; +}; + +#endif // CONTROLPOWERWIDGET_H diff --git a/LedOK/wDevicesManager/controltestwidget.cpp b/LedOK/device/controltestwidget.cpp similarity index 97% rename from LedOK/wDevicesManager/controltestwidget.cpp rename to LedOK/device/controltestwidget.cpp index 4ead2ea..dfb96b1 100644 --- a/LedOK/wDevicesManager/controltestwidget.cpp +++ b/LedOK/device/controltestwidget.cpp @@ -1,558 +1,545 @@ -#include "controltestwidget.h" -#include "ui_controltestwidget.h" -#include "base/x_uimsgboxok.h" -#include "QFileDialog" -#include "QDir" -#include -#include -#include -#include -#include -#include -#include "tools.h" -ControlTestWidget::ControlTestWidget(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlTestWidget) -{ - m_pLedlist=list; - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - ui->pushButtonStartLine->setProperty("ssType", "progManageTool"); - ui->pushButtonStartGray->setProperty("ssType", "progManageTool"); - ui->pushButtonStartColor->setProperty("ssType", "progManageTool"); - ui->pushButtonStopTest->setProperty("ssType", "progManageTool"); - ui->pushButton->setProperty("ssType", "progManageTool"); - ui->pushButton_2->setProperty("ssType", "progManageTool"); - ui->pushButton_3->setProperty("ssType", "progManageTool"); - ui->pushButton_4->setProperty("ssType", "progManageTool"); - ui->pushButton_5->setProperty("ssType", "progManageTool"); - ui->pushButton_6->setProperty("ssType", "progManageTool"); - ui->pushButton_7->setProperty("ssType", "progManageTool"); - ui->pushButton_8->setProperty("ssType", "progManageTool"); - ui->pushButton_9->setProperty("ssType", "progManageTool"); - ui->pushButton_10->setProperty("ssType", "progManageTool"); - ui->pushButton_11->setProperty("ssType", "progManageTool"); - ui->pushButton_12->setProperty("ssType", "progManageTool"); - ui->pushButton_13->setProperty("ssType", "progManageTool"); - - ui->spinBoxLineSpeed->setValue(10); - ui->spinBoxLineDistance->setValue(15); - ui->spinBoxGraySpeed->setValue(10); - ui->spinBoxGrayValue->setValue(0); - ui->radioButtonWhite->setChecked(true); - ui->radioButton_White->setChecked(true); - ui->checkBoxHorizontal->setChecked(true); - ui->checkBoxVertical->setChecked(true); - ui->checkBoxSlash->setChecked(true); - ui->checkBox_red->setChecked(true); - ui->checkBox_green->setChecked(true); - ui->checkBox_blue->setChecked(true); - ui->checkBox_white->setChecked(true); - - - connect(ui->pushButtonStartLine,SIGNAL(clicked()),this,SLOT(OnStartTestLine())); - connect(ui->pushButtonStartGray,SIGNAL(clicked()),this,SLOT(OnStartTestGray())); - connect(ui->pushButtonStartColor,SIGNAL(clicked()),this,SLOT(OnStartTestColor())); - connect(ui->pushButtonStopTest,SIGNAL(clicked()),this,SLOT(OnStopTest())); - - connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(OnpushButton1())); - connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(OnpushButton2())); - connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(OnpushButton3())); - connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(OnpushButton4())); - connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(OnpushButton5())); - connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(OnpushButton6())); - connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(OnpushButton7())); - connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(OnpushButton8())); - connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(OnpushButton9())); - connect(ui->pushButton_10,SIGNAL(clicked()),this,SLOT(OnpushButton0())); - connect(ui->pushButton_11,SIGNAL(clicked()),this,SLOT(OnpushButtonClear())); - connect(ui->pushButton_12,SIGNAL(clicked()),this,SLOT(OnpushButtonReset())); - connect(ui->pushButton_13,SIGNAL(clicked()),this,SLOT(OnpushButtonAnycast())); - - ui->pushButton_13->setEnabled(false); - - MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent) - - connect(this,SIGNAL(sigTcpSend(int)),parent->parent(),SLOT(OnControlTcpSend(int))); - ui->lineEdit->setValidator(new QIntValidator(0, 100, this)); - - -} - -ControlTestWidget::~ControlTestWidget() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void ControlTestWidget::refreshLable() -{ - ui->labelTestScreen->setText(tr("Test Screen")); - ui->groupBox->setTitle(tr("Line test")); - ui->radioButtonRed->setText(tr("Red")); - ui->radioButtonGreen->setText(tr("Green")); - ui->radioButtonBlue->setText(tr("Blue")); - ui->radioButtonWhite->setText(tr("White")); - ui->radioButton_red->setText(tr("Red")); - ui->radioButton_Green->setText(tr("Green")); - ui->radioButton_Blue->setText(tr("Blue")); - ui->radioButton_White->setText(tr("White")); - ui->checkBoxVertical->setText(tr("Vertical")); - ui->checkBoxHorizontal->setText(tr("Horizontal")); - ui->checkBoxSlash->setText(tr("Slash")); - ui->label->setText(tr("Speed")); - ui->label_5->setText(tr("ms(>10)")); - ui->checkBoxHorizontal->setText(tr("Horizontal")); - ui->label_2->setText(tr("Line Distance")); - ui->pushButtonStartLine->setText(tr("Test")); - ui->groupBox_2->setTitle(tr("Gradation test")); - ui->checkBoxShowInfo->setText(tr("Only the gray value is displayed")); - ui->checkBox_red->setText(tr("Red")); - ui->checkBox_green->setText(tr("Green")); - ui->checkBox_blue->setText(tr("Blue")); - ui->checkBox_white->setText(tr("White")); - ui->label_3->setText(tr("Speed")); - ui->label_4->setText(tr("GrayValue")); - ui->pushButtonStartGray->setText(tr("Test")); - ui->groupBox_3->setTitle(tr("Color test")); - ui->checkBoxGradient->setText(tr("Gradient")); - ui->radioButton_red->setText(tr("Red")); - ui->radioButton_Green->setText(tr("Green")); - ui->radioButton_Blue->setText(tr("Blue")); - ui->radioButton_White->setText(tr("White")); - ui->pushButtonStopTest->setText(tr("Stop")); - ui->pushButton_11->setText(tr("Clear")); - ui->pushButton_12->setText(tr("Reset")); - ui->pushButton_13->setText(tr("Anycast")); - -} -void ControlTestWidget::OnStartTestLine() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "TestScreen"); - json.insert("mode", 1);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 - json.insert("speed", ui->spinBoxLineSpeed->value()); - if(ui->radioButtonRed->isChecked()) - json.insert("color", "#FFFF0000"); - else if(ui->radioButtonGreen->isChecked()) - json.insert("color", "#FF00FF00"); - else if(ui->radioButtonBlue->isChecked()) - json.insert("color", "#FF0000FF"); - else - json.insert("color", "#FFFFFFFF"); - - json.insert("interval", ui->spinBoxLineDistance->value()); - json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked()); - json.insert("verticalLine", ui->checkBoxVertical->isChecked()); - json.insert("slantLine", ui->checkBoxSlash->isChecked()); - json.insert("runLimit", ui->spinBoxGrayValue->value()); - json.insert("showInfo", !ui->checkBoxShowInfo->isChecked()); - json.insert("red", ui->checkBox_red->isChecked()); - json.insert("green", ui->checkBox_green->isChecked()); - json.insert("blue", ui->checkBox_blue->isChecked()); - json.insert("white", ui->checkBox_white->isChecked()); - - MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed")) - -} -void ControlTestWidget::OnStartTestGray() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "TestScreen"); - json.insert("mode", 2);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 - json.insert("speed", ui->spinBoxGraySpeed->value()); - // qDebug()<<"speed="<spinBoxGraySpeed->value(); - if(ui->radioButtonRed->isChecked()) - json.insert("color", "#FFFF0000"); - else if(ui->radioButtonGreen->isChecked()) - json.insert("color", "#FF00FF00"); - else if(ui->radioButtonBlue->isChecked()) - json.insert("color", "#FF0000FF"); - else - json.insert("color", "#FFFFFFFF"); - json.insert("interval", ui->spinBoxLineDistance->value()); - json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked()); - json.insert("verticalLine", ui->checkBoxVertical->isChecked()); - json.insert("slantLine", ui->checkBoxSlash->isChecked()); - json.insert("runLimit", ui->spinBoxGrayValue->value()); - json.insert("showInfo", !ui->checkBoxShowInfo->isChecked()); - json.insert("red", ui->checkBox_red->isChecked()); - json.insert("green", ui->checkBox_green->isChecked()); - json.insert("blue", ui->checkBox_blue->isChecked()); - json.insert("white", ui->checkBox_white->isChecked()); - - MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed")) - -} -void ControlTestWidget::OnStartTestColor() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "TestScreen"); - if(ui->checkBoxGradient->isChecked()) - json.insert("mode", 4);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 - else - json.insert("mode", 3);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 - json.insert("speed", ui->spinBoxLineSpeed->value()); - if(ui->radioButton_red->isChecked()) - json.insert("color", "#FFFF0000"); - else if(ui->radioButton_Green->isChecked()) - json.insert("color", "#FF00FF00"); - else if(ui->radioButton_Blue->isChecked()) - json.insert("color", "#FF0000FF"); - else - json.insert("color", "#FFFFFFFF"); - - json.insert("interval", ui->spinBoxLineDistance->value()); - json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked()); - json.insert("verticalLine", ui->checkBoxVertical->isChecked()); - json.insert("slantLine", ui->checkBoxSlash->isChecked()); - json.insert("runLimit", ui->spinBoxGrayValue->value()); - json.insert("showInfo", !ui->checkBoxShowInfo->isChecked()); - json.insert("red", ui->checkBox_red->isChecked()); - json.insert("green", ui->checkBox_green->isChecked()); - json.insert("blue", ui->checkBox_blue->isChecked()); - json.insert("white", ui->checkBox_white->isChecked()); - - MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed")) - -} -void ControlTestWidget::OnStopTest() -{ - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "TestScreen"); - json.insert("mode", 0); - MACRO_DEFINE_TIPDLG_FUCN(tr("StopTest"),tr("Success"),tr("failed")) -} - -void ControlTestWidget::OnpushButton1() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"1"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton2() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"2"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton3() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"3"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton4() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"4"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton5() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"5"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton6() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"6"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton7() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"7"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton8() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"8"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton9() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"9"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButton0() -{ - if(ui->lineEdit->text().contains("-")) - ui->lineEdit->clear(); - ui->lineEdit->setText(ui->lineEdit->text()+"0"); - ui->pushButton_13->setEnabled(true); -} -void ControlTestWidget::OnpushButtonClear() -{ - ui->lineEdit->clear(); - ui->pushButton_13->setEnabled(false); -} - -void ControlTestWidget::OnpushButtonReset() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - int iIndex= ui->lineEdit->text().toInt(); - if(m_pLedlist->count()==1) - { - - SendAnycastCmd(m_pLedCard->m_strCardIp,0); - } - else { - emit sigTcpSend(iIndex); - - } - ui->lineEdit->setText("-"+tr("loopback mode")+"-"); - ui->pushButton_13->setEnabled(false); -} -void ControlTestWidget::OnpushButtonAnycast() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - int iIndex= ui->lineEdit->text().toInt(); - if(m_pLedlist->count()==1) - { - - SendAnycastCmd(m_pLedCard->m_strCardIp,iIndex); - } - else { - emit sigTcpSend(iIndex); - - } - - - - - - ui->lineEdit->setText(tr("Anycast")+" - "+ui->lineEdit->text()); - ui->pushButton_13->setEnabled(false); -} -void ControlTestWidget::SendAnycastCmd(QString strIp,int iProgramIndex) -{ - - QTcpSocket *send = new QTcpSocket(); - connect(send, SIGNAL(connected()), this, SLOT(connect_sucessful())); - connect(send, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(show_error(QAbstractSocket::SocketError))); - send->connectToHost(QHostAddress(strIp),31299); - - ST_ANSY_PROGRAM_PACKET tempStreadPakcet; - tempStreadPakcet.SyncHead[0]=0x7e; - tempStreadPakcet.SyncHead[1]=0x7e; - tempStreadPakcet.SyncHead[2]=0x55; - tempStreadPakcet.ucCommType=0x97; - tempStreadPakcet.iBaoLiu=0; - tempStreadPakcet.iLength=4; - unsigned char uctemp[4]={0}; - uctemp[0]=iProgramIndex; - - memcpy(tempStreadPakcet.pDataBuffer,uctemp,4); - tempStreadPakcet.pDataBuffer[tempStreadPakcet.iLength]=GetCheckCodeIn8(&tempStreadPakcet.ucCommType,tempStreadPakcet.iLength+sizeof(tempStreadPakcet.iBaoLiu)+sizeof(tempStreadPakcet.ucCommType)+sizeof(tempStreadPakcet.iLength)); - int iLenPacket=3*sizeof(unsigned char)+sizeof(char)+sizeof(int)+sizeof(int)+tempStreadPakcet.iLength+sizeof(char);/////除正文外的协议结构大小; - QByteArray databuf = QByteArray(reinterpret_cast(&tempStreadPakcet), iLenPacket); - if(!send->waitForConnected(10000)) //等待连接返回 - { - qDebug()<exec(); - send->close(); - delete send; - return ; - } - send->write(databuf); - if(send->waitForBytesWritten(3000)) - { - QByteArray readBuf=send->read(send->bytesAvailable()); - qDebug()<<"recv anycast success ack"; - if(iProgramIndex==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Reset loop mode")+":"+tr("success"),this,1); - pDlg->exec(); - - } - else { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Anycast")+":"+tr("success"),this,1); - pDlg->exec(); - - } - //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("Anycast")+":"+tr("success")); - } - send->close(); - delete send; - -} -void ControlTestWidget::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - MACRO_DEFINE_CONTROL_FUNC3 -} -void ControlTestWidget::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_Encrypt) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlTestWidget::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlTestWidget::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "TestScreen") - { - - } - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} - -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlTestWidget::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "TestScreen") - { - - - } - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -void ControlTestWidget::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} - - +#include "controltestwidget.h" +#include "ui_controltestwidget.h" +#include "base/x_uimsgboxok.h" +#include "QFileDialog" +#include "QDir" +#include +#include +#include +#include +#include +#include +#include "tools.h" +ControlTestWidget::ControlTestWidget(QWidget *parent,QList *list) : + QWidget(parent), + ui(new Ui::ControlTestWidget) +{ + m_pLedlist=list; + ui->setupUi(this); + refreshLable(); +setStyleSheet(css); + ui->pushButtonStartLine->setProperty("ssType", "progManageTool"); + ui->pushButtonStartGray->setProperty("ssType", "progManageTool"); + ui->pushButtonStartColor->setProperty("ssType", "progManageTool"); + ui->pushButtonStopTest->setProperty("ssType", "progManageTool"); + ui->pushButton->setProperty("ssType", "progManageTool"); + ui->pushButton_2->setProperty("ssType", "progManageTool"); + ui->pushButton_3->setProperty("ssType", "progManageTool"); + ui->pushButton_4->setProperty("ssType", "progManageTool"); + ui->pushButton_5->setProperty("ssType", "progManageTool"); + ui->pushButton_6->setProperty("ssType", "progManageTool"); + ui->pushButton_7->setProperty("ssType", "progManageTool"); + ui->pushButton_8->setProperty("ssType", "progManageTool"); + ui->pushButton_9->setProperty("ssType", "progManageTool"); + ui->pushButton_10->setProperty("ssType", "progManageTool"); + ui->pushButton_11->setProperty("ssType", "progManageTool"); + ui->pushButton_12->setProperty("ssType", "progManageTool"); + ui->pushButton_13->setProperty("ssType", "progManageTool"); + + ui->spinBoxLineSpeed->setValue(10); + ui->spinBoxLineDistance->setValue(15); + ui->spinBoxGraySpeed->setValue(10); + ui->spinBoxGrayValue->setValue(0); + ui->radioButtonWhite->setChecked(true); + ui->radioButton_White->setChecked(true); + ui->checkBoxHorizontal->setChecked(true); + ui->checkBoxVertical->setChecked(true); + ui->checkBoxSlash->setChecked(true); + ui->checkBox_red->setChecked(true); + ui->checkBox_green->setChecked(true); + ui->checkBox_blue->setChecked(true); + ui->checkBox_white->setChecked(true); + + + connect(ui->pushButtonStartLine,SIGNAL(clicked()),this,SLOT(OnStartTestLine())); + connect(ui->pushButtonStartGray,SIGNAL(clicked()),this,SLOT(OnStartTestGray())); + connect(ui->pushButtonStartColor,SIGNAL(clicked()),this,SLOT(OnStartTestColor())); + connect(ui->pushButtonStopTest,SIGNAL(clicked()),this,SLOT(OnStopTest())); + + connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(OnpushButton1())); + connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(OnpushButton2())); + connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(OnpushButton3())); + connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(OnpushButton4())); + connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(OnpushButton5())); + connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(OnpushButton6())); + connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(OnpushButton7())); + connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(OnpushButton8())); + connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(OnpushButton9())); + connect(ui->pushButton_10,SIGNAL(clicked()),this,SLOT(OnpushButton0())); + connect(ui->pushButton_11,SIGNAL(clicked()),this,SLOT(OnpushButtonClear())); + connect(ui->pushButton_12,SIGNAL(clicked()),this,SLOT(OnpushButtonReset())); + connect(ui->pushButton_13,SIGNAL(clicked()),this,SLOT(OnpushButtonAnycast())); + + ui->pushButton_13->setEnabled(false); + + MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent) + + connect(this,SIGNAL(sigTcpSend(int)),parent->parent(),SLOT(OnControlTcpSend(int))); + ui->lineEdit->setValidator(new QIntValidator(0, 100, this)); + + +} + +ControlTestWidget::~ControlTestWidget() +{ + delete ui; + if(pHpptClient != nullptr) + { + qDebug() <<"delete pHpptClient in ~NetComm"; + delete pHpptClient; + pHpptClient=nullptr; + } + if(pHpptClientAll != nullptr) + { + qDebug() <<"delete pHpptClientAll in ~NetComm"; + delete pHpptClientAll; + pHpptClientAll=nullptr; + } +} +void ControlTestWidget::refreshLable() +{ + ui->labelTestScreen->setText(tr("Test Screen")); + ui->groupBox->setTitle(tr("Line test")); + ui->radioButtonRed->setText(tr("Red")); + ui->radioButtonGreen->setText(tr("Green")); + ui->radioButtonBlue->setText(tr("Blue")); + ui->radioButtonWhite->setText(tr("White")); + ui->radioButton_red->setText(tr("Red")); + ui->radioButton_Green->setText(tr("Green")); + ui->radioButton_Blue->setText(tr("Blue")); + ui->radioButton_White->setText(tr("White")); + ui->checkBoxVertical->setText(tr("Vertical")); + ui->checkBoxHorizontal->setText(tr("Horizontal")); + ui->checkBoxSlash->setText(tr("Slash")); + ui->label->setText(tr("Speed")); + ui->label_5->setText(tr("ms(>10)")); + ui->checkBoxHorizontal->setText(tr("Horizontal")); + ui->label_2->setText(tr("Line Distance")); + ui->pushButtonStartLine->setText(tr("Test")); + ui->groupBox_2->setTitle(tr("Gradation test")); + ui->checkBoxShowInfo->setText(tr("Only the gray value is displayed")); + ui->checkBox_red->setText(tr("Red")); + ui->checkBox_green->setText(tr("Green")); + ui->checkBox_blue->setText(tr("Blue")); + ui->checkBox_white->setText(tr("White")); + ui->label_3->setText(tr("Speed")); + ui->label_4->setText(tr("GrayValue")); + ui->pushButtonStartGray->setText(tr("Test")); + ui->groupBox_3->setTitle(tr("Color test")); + ui->checkBoxGradient->setText(tr("Gradient")); + ui->radioButton_red->setText(tr("Red")); + ui->radioButton_Green->setText(tr("Green")); + ui->radioButton_Blue->setText(tr("Blue")); + ui->radioButton_White->setText(tr("White")); + ui->pushButtonStopTest->setText(tr("Stop")); + ui->pushButton_11->setText(tr("Clear")); + ui->pushButton_12->setText(tr("Reset")); + ui->pushButton_13->setText(tr("Anycast")); + +} +void ControlTestWidget::OnStartTestLine() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()<=1) + { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + } + + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "TestScreen"); + json.insert("mode", 1);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 + json.insert("speed", ui->spinBoxLineSpeed->value()); + if(ui->radioButtonRed->isChecked()) + json.insert("color", "#FFFF0000"); + else if(ui->radioButtonGreen->isChecked()) + json.insert("color", "#FF00FF00"); + else if(ui->radioButtonBlue->isChecked()) + json.insert("color", "#FF0000FF"); + else + json.insert("color", "#FFFFFFFF"); + + json.insert("interval", ui->spinBoxLineDistance->value()); + json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked()); + json.insert("verticalLine", ui->checkBoxVertical->isChecked()); + json.insert("slantLine", ui->checkBoxSlash->isChecked()); + json.insert("runLimit", ui->spinBoxGrayValue->value()); + json.insert("showInfo", !ui->checkBoxShowInfo->isChecked()); + json.insert("red", ui->checkBox_red->isChecked()); + json.insert("green", ui->checkBox_green->isChecked()); + json.insert("blue", ui->checkBox_blue->isChecked()); + json.insert("white", ui->checkBox_white->isChecked()); + + MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed")) + +} +void ControlTestWidget::OnStartTestGray() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()<=1) + { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + } + + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "TestScreen"); + json.insert("mode", 2);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 + json.insert("speed", ui->spinBoxGraySpeed->value()); + // qDebug()<<"speed="<spinBoxGraySpeed->value(); + if(ui->radioButtonRed->isChecked()) + json.insert("color", "#FFFF0000"); + else if(ui->radioButtonGreen->isChecked()) + json.insert("color", "#FF00FF00"); + else if(ui->radioButtonBlue->isChecked()) + json.insert("color", "#FF0000FF"); + else + json.insert("color", "#FFFFFFFF"); + json.insert("interval", ui->spinBoxLineDistance->value()); + json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked()); + json.insert("verticalLine", ui->checkBoxVertical->isChecked()); + json.insert("slantLine", ui->checkBoxSlash->isChecked()); + json.insert("runLimit", ui->spinBoxGrayValue->value()); + json.insert("showInfo", !ui->checkBoxShowInfo->isChecked()); + json.insert("red", ui->checkBox_red->isChecked()); + json.insert("green", ui->checkBox_green->isChecked()); + json.insert("blue", ui->checkBox_blue->isChecked()); + json.insert("white", ui->checkBox_white->isChecked()); + + MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed")) + +} +void ControlTestWidget::OnStartTestColor() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()<=1) + { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + } + + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "TestScreen"); + if(ui->checkBoxGradient->isChecked()) + json.insert("mode", 4);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 + else + json.insert("mode", 3);// 0:停止; 1:斜线; 2:灰度; 3:颜色;4:渐变 + json.insert("speed", ui->spinBoxLineSpeed->value()); + if(ui->radioButton_red->isChecked()) + json.insert("color", "#FFFF0000"); + else if(ui->radioButton_Green->isChecked()) + json.insert("color", "#FF00FF00"); + else if(ui->radioButton_Blue->isChecked()) + json.insert("color", "#FF0000FF"); + else + json.insert("color", "#FFFFFFFF"); + + json.insert("interval", ui->spinBoxLineDistance->value()); + json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked()); + json.insert("verticalLine", ui->checkBoxVertical->isChecked()); + json.insert("slantLine", ui->checkBoxSlash->isChecked()); + json.insert("runLimit", ui->spinBoxGrayValue->value()); + json.insert("showInfo", !ui->checkBoxShowInfo->isChecked()); + json.insert("red", ui->checkBox_red->isChecked()); + json.insert("green", ui->checkBox_green->isChecked()); + json.insert("blue", ui->checkBox_blue->isChecked()); + json.insert("white", ui->checkBox_white->isChecked()); + + MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed")) + +} +void ControlTestWidget::OnStopTest() +{ + + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "TestScreen"); + json.insert("mode", 0); + MACRO_DEFINE_TIPDLG_FUCN(tr("StopTest"),tr("Success"),tr("failed")) +} + +void ControlTestWidget::OnpushButton1() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"1"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton2() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"2"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton3() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"3"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton4() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"4"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton5() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"5"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton6() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"6"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton7() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"7"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton8() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"8"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton9() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"9"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButton0() +{ + if(ui->lineEdit->text().contains("-")) + ui->lineEdit->clear(); + ui->lineEdit->setText(ui->lineEdit->text()+"0"); + ui->pushButton_13->setEnabled(true); +} +void ControlTestWidget::OnpushButtonClear() +{ + ui->lineEdit->clear(); + ui->pushButton_13->setEnabled(false); +} + +void ControlTestWidget::OnpushButtonReset() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + int iIndex= ui->lineEdit->text().toInt(); + if(m_pLedlist->count()==1) + { + + SendAnycastCmd(m_pLedCard->m_strCardIp,0); + } + else { + emit sigTcpSend(iIndex); + + } + ui->lineEdit->setText("-"+tr("loopback mode")+"-"); + ui->pushButton_13->setEnabled(false); +} +void ControlTestWidget::OnpushButtonAnycast() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + int iIndex= ui->lineEdit->text().toInt(); + if(m_pLedlist->count()==1) + { + + SendAnycastCmd(m_pLedCard->m_strCardIp,iIndex); + } + else { + emit sigTcpSend(iIndex); + + } + + + + + + ui->lineEdit->setText(tr("Anycast")+" - "+ui->lineEdit->text()); + ui->pushButton_13->setEnabled(false); +} +void ControlTestWidget::SendAnycastCmd(QString strIp,int iProgramIndex) +{ + + QTcpSocket *send = new QTcpSocket(); + connect(send, SIGNAL(connected()), this, SLOT(connect_sucessful())); + connect(send, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(show_error(QAbstractSocket::SocketError))); + send->connectToHost(QHostAddress(strIp),31299); + + ST_ANSY_PROGRAM_PACKET tempStreadPakcet; + tempStreadPakcet.SyncHead[0]=0x7e; + tempStreadPakcet.SyncHead[1]=0x7e; + tempStreadPakcet.SyncHead[2]=0x55; + tempStreadPakcet.ucCommType=0x97; + tempStreadPakcet.iBaoLiu=0; + tempStreadPakcet.iLength=4; + unsigned char uctemp[4]={0}; + uctemp[0]=iProgramIndex; + + memcpy(tempStreadPakcet.pDataBuffer,uctemp,4); + tempStreadPakcet.pDataBuffer[tempStreadPakcet.iLength]=GetCheckCodeIn8(&tempStreadPakcet.ucCommType,tempStreadPakcet.iLength+sizeof(tempStreadPakcet.iBaoLiu)+sizeof(tempStreadPakcet.ucCommType)+sizeof(tempStreadPakcet.iLength)); + int iLenPacket=3*sizeof(unsigned char)+sizeof(char)+sizeof(int)+sizeof(int)+tempStreadPakcet.iLength+sizeof(char);/////除正文外的协议结构大小; + QByteArray databuf = QByteArray(reinterpret_cast(&tempStreadPakcet), iLenPacket); + if(!send->waitForConnected(10000)) //等待连接返回 + { + qDebug()<exec(); + send->close(); + delete send; + return ; + } + send->write(databuf); + if(send->waitForBytesWritten(3000)) + { + QByteArray readBuf=send->read(send->bytesAvailable()); + qDebug()<<"recv anycast success ack"; + if(iProgramIndex==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Reset loop mode")+":"+tr("success"),this,1); + pDlg->exec(); + + } + else { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Anycast")+":"+tr("success"),this,1); + pDlg->exec(); + + } + //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("Anycast")+":"+tr("success")); + } + send->close(); + delete send; + +} +void ControlTestWidget::onSelectedDeviceList(QList *list) +{ + m_pLedlist=list; + MACRO_DEFINE_CONTROL_FUNC3 +} +void ControlTestWidget::OnControlTypeSwitchIndexChanged(int index) +{ + if(index==Setting_Encrypt) + { + m_bSelected=true; + if(m_pLedCard!=nullptr) + onReadbackAllThisPage(); + } + else { + m_bSelected=false; + } +} +void ControlTestWidget::onReadbackAllThisPage() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()!=1) + return; +} +//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 +void ControlTestWidget::OnProHttpResponse(QString url, QString postMD5, QByteArray data) +{ + Q_UNUSED(postMD5) + //qDebug()<< url + "\r\n"+m_strUrl; + if(url == m_strUrl) + { + QJsonParseError parseJsonErr; + QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); + if(!(parseJsonErr.error == QJsonParseError::NoError)) + { + if(data.size()==0) + qDebug()<<"json is empty"; + else + qDebug()< -#include -#include -#include -namespace Ui { -class ControlTestWidget; -} - -class ControlTestWidget : public QWidget -{ - Q_OBJECT - -public: - explicit ControlTestWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlTestWidget(); - -private: - Ui::ControlTestWidget *ui; -protected slots: - void OnStartTestLine(); - void OnStartTestGray(); - void OnStartTestColor(); - void OnStopTest(); - - void OnpushButton1(); - void OnpushButton2(); - void OnpushButton3(); - void OnpushButton4(); - void OnpushButton5(); - void OnpushButton6(); - void OnpushButton7(); - void OnpushButton8(); - void OnpushButton9(); - void OnpushButton0(); - void OnpushButtonClear(); - void OnpushButtonReset(); - void OnpushButtonAnycast(); - void refreshLable(); - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigTcpSend(int); - void sigSend(QJsonObject &,QString); - protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; - void SendAnycastCmd(QString strIp,int iProgramIndex); - -}; - -#endif // CONTROLTESTWIDGET_H +#ifndef CONTROLTESTWIDGET_H +#define CONTROLTESTWIDGET_H + +#include +#include +#include +#include +namespace Ui { +class ControlTestWidget; +} + +class ControlTestWidget : public QWidget +{ + Q_OBJECT + +public: + explicit ControlTestWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); + ~ControlTestWidget(); + +private: + Ui::ControlTestWidget *ui; +protected slots: + void OnStartTestLine(); + void OnStartTestGray(); + void OnStartTestColor(); + void OnStopTest(); + + void OnpushButton1(); + void OnpushButton2(); + void OnpushButton3(); + void OnpushButton4(); + void OnpushButton5(); + void OnpushButton6(); + void OnpushButton7(); + void OnpushButton8(); + void OnpushButton9(); + void OnpushButton0(); + void OnpushButtonClear(); + void OnpushButtonReset(); + void OnpushButtonAnycast(); + void refreshLable(); + //类似的控制操作信号和槽函数和变量定义 + signals: + void sigTcpSend(int); + void sigSend(QJsonObject &,QString); + protected slots: + void DeletePostingDlg(); + void OnProHttpResponse(QString url, QString postMD5, QByteArray data); + void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); + void onSelectedDeviceList(QList *); + void onReadbackAllThisPage(); + void OnControlTypeSwitchIndexChanged(int index); + private: + QList *m_pLedlist=nullptr; + LedCard *m_pLedCard = nullptr; + LedCard *m_oldLedlist = nullptr; + HpptClient *pHpptClient = nullptr; + HpptClient *pHpptClientAll = nullptr; + QString m_strUrl=""; + LoEmptyDialog * m_PostingDlg=nullptr; + QTimer *m_pGetAskTimer=nullptr; + bool m_bSelected=false; + void SendAnycastCmd(QString strIp,int iProgramIndex); + +}; + +#endif // CONTROLTESTWIDGET_H diff --git a/LedOK/wDevicesManager/controltestwidget.ui b/LedOK/device/controltestwidget.ui similarity index 97% rename from LedOK/wDevicesManager/controltestwidget.ui rename to LedOK/device/controltestwidget.ui index 42a8f1a..c23ae96 100644 --- a/LedOK/wDevicesManager/controltestwidget.ui +++ b/LedOK/device/controltestwidget.ui @@ -1,1016 +1,1016 @@ - - - ControlTestWidget - - - - 0 - 0 - 872 - 609 - - - - - 0 - 0 - - - - Form - - - - - - - Arial - 12 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - Test Screen - - - Qt::AlignCenter - - - - - - - Qt::Horizontal - - - - - - - true - - - - - 0 - 0 - 832 - 536 - - - - - - - 0 - - - 10 - - - - - 0 - - - 0 - - - - - Line test - - - - 0 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Red - - - - - - - Green - - - - - - - Blue - - - - - - - White - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Vertical - - - - - - - Slash - - - - - - - Horizontal - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Speed - - - - - - - 99999 - - - - - - - ms(>10) - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - Line Distance - - - - - - - 128 - - - - - - - px - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 60 - 30 - - - - - 80 - 16777215 - - - - Test - - - - - - - - - - Gradation test - - - - 0 - - - - - Only the gray value is displayed - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Red - - - - - - - Green - - - - - - - Blue - - - - - - - White - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Speed - - - - - - - - 60 - 0 - - - - 10 - - - 99999 - - - - - - - (>10) - - - - - - - GrayValue - - - - - - - 255 - - - - - - - (0-255) - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 60 - 30 - - - - - 80 - 16777215 - - - - Test - - - - - - - - - - Color test - - - - 0 - - - - - Gradient - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Red - - - - - - - Green - - - - - - - Blue - - - - - - - White - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 60 - 30 - - - - - 80 - 16777215 - - - - Test - - - - - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 60 - 30 - - - - Stop - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - Qt::Vertical - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 0 - - - 0 - - - - - - 0 - 36 - - - - - 194 - 16777215 - - - - false - - - color: rgb(0, 255, 0); -background-color: rgb(0, 0, 0); - - - Qt::AlignCenter - - - - - - - QLayout::SetMaximumSize - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 8 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 2 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 3 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 6 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 4 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 5 - - - - - - - - 30 - 30 - - - - - 60 - 0 - - - - - 60 - 30 - - - - 1 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 9 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 7 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - 0 - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - Clear - - - - - - - - 60 - 0 - - - - - 60 - 30 - - - - Reset - - - - - - - - - - 0 - 30 - - - - - 194 - 30 - - - - Anycast - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - + + + ControlTestWidget + + + + 0 + 0 + 872 + 609 + + + + + 0 + 0 + + + + Form + + + + + + + Arial + 12 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + Test Screen + + + Qt::AlignCenter + + + + + + + Qt::Horizontal + + + + + + + true + + + + + 0 + 0 + 832 + 536 + + + + + + + 0 + + + 10 + + + + + 0 + + + 0 + + + + + Line test + + + + 0 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Red + + + + + + + Green + + + + + + + Blue + + + + + + + White + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Vertical + + + + + + + Slash + + + + + + + Horizontal + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Speed + + + + + + + 99999 + + + + + + + ms(>10) + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Line Distance + + + + + + + 128 + + + + + + + px + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 60 + 30 + + + + + 80 + 16777215 + + + + Test + + + + + + + + + + Gradation test + + + + 0 + + + + + Only the gray value is displayed + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Red + + + + + + + Green + + + + + + + Blue + + + + + + + White + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Speed + + + + + + + + 60 + 0 + + + + 10 + + + 99999 + + + + + + + (>10) + + + + + + + GrayValue + + + + + + + 255 + + + + + + + (0-255) + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 60 + 30 + + + + + 80 + 16777215 + + + + Test + + + + + + + + + + Color test + + + + 0 + + + + + Gradient + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Red + + + + + + + Green + + + + + + + Blue + + + + + + + White + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + 60 + 30 + + + + + 80 + 16777215 + + + + Test + + + + + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 60 + 30 + + + + Stop + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Qt::Vertical + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 0 + + + 0 + + + + + + 0 + 36 + + + + + 194 + 16777215 + + + + false + + + color: rgb(0, 255, 0); +background-color: rgb(0, 0, 0); + + + Qt::AlignCenter + + + + + + + QLayout::SetMaximumSize + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 8 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 2 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 3 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 6 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 4 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 5 + + + + + + + + 30 + 30 + + + + + 60 + 0 + + + + + 60 + 30 + + + + 1 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 9 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 7 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + 0 + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + Clear + + + + + + + + 60 + 0 + + + + + 60 + 30 + + + + Reset + + + + + + + + + + 0 + 30 + + + + + 194 + 30 + + + + Anycast + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + diff --git a/LedOK/wDevicesManager/controlvolumeschedule.cpp b/LedOK/device/controlvolumeschedule.cpp similarity index 97% rename from LedOK/wDevicesManager/controlvolumeschedule.cpp rename to LedOK/device/controlvolumeschedule.cpp index 9ff2ccd..4efcdd4 100644 --- a/LedOK/wDevicesManager/controlvolumeschedule.cpp +++ b/LedOK/device/controlvolumeschedule.cpp @@ -1,530 +1,528 @@ -#include "controlvolumeschedule.h" -#include "ui_controlvolumeschedule.h" -#include "base/x_uimsgboxok.h" -#include "QFileDialog" -#include "QDir" -#include -#include -#include -#include -#include -#include -#include "QSettings" -#include "base/x_spinboxdelegate.h" -#include "base/x_timeeditdelegate.h" -#include "base/x_checkboxdelegate.h" -#include "tools.h" -ControlVolumeSchedule::ControlVolumeSchedule(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlVolumeSchedule) -{ - m_pLedlist=list; - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - ui->pushButtonAdd->setProperty("ssType", "progManageTool"); - ui->pushButtonAdd->setFlat(true); - ui->pushButtonDelete->setProperty("ssType", "progManageTool"); - ui->pushButtonDelete->setFlat(true); - ui->pushButtonClear->setProperty("ssType", "progManageTool"); - ui->pushButtonClear->setFlat(true); - ui->pushButtonApply->setProperty("ssType", "progManageTool"); - ui->pushButtonApply->setFlat(true); - ui->pushButtonImport->setProperty("ssType", "progManageTool"); - ui->pushButtonExport->setProperty("ssType", "progManageTool"); - ui->pushButtonReadback->setProperty("ssType", "progManageTool"); - ui->lineEdit->setText("10"); - m_pModel = new QStandardItemModel(this); - m_pModel->setColumnCount(10); - m_pModel->setHeaderData(0,Qt::Horizontal, tr("Volume value")); - m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time")); - m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time")); - m_pModel->setHeaderData(3,Qt::Horizontal, tr("SUN")); - m_pModel->setHeaderData(4,Qt::Horizontal, tr("MON")); - m_pModel->setHeaderData(5,Qt::Horizontal, tr("TUE")); - m_pModel->setHeaderData(6,Qt::Horizontal, tr("WED")); - m_pModel->setHeaderData(7,Qt::Horizontal, tr("THU")); - m_pModel->setHeaderData(8,Qt::Horizontal, tr("FRI")); - m_pModel->setHeaderData(9,Qt::Horizontal, tr("SAT")); - ui->tableView->setModel(m_pModel); - SpinBoxDelegate *pVolumeDelegate=new SpinBoxDelegate(this,1); - ui->tableView->setItemDelegateForColumn(0,pVolumeDelegate); - - X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this); - ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate); - ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate); - X_CheckBoxDelegate *WeekDelegate=new X_CheckBoxDelegate(this); - ui->tableView->setItemDelegateForColumn(3,WeekDelegate); - ui->tableView->setItemDelegateForColumn(4,WeekDelegate); - ui->tableView->setItemDelegateForColumn(5,WeekDelegate); - ui->tableView->setItemDelegateForColumn(6,WeekDelegate); - ui->tableView->setItemDelegateForColumn(7,WeekDelegate); - ui->tableView->setItemDelegateForColumn(8,WeekDelegate); - ui->tableView->setItemDelegateForColumn(9,WeekDelegate); - - - ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - // ui->tableView->verticalHeader()->hide(); - ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); - ui->tableView->setFocusPolicy(Qt::NoFocus); - - - MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) - - connect(ui->pushButtonAdd,SIGNAL(clicked()),this,SLOT(OnClickAdd())); - connect(ui->pushButtonImport,SIGNAL(clicked()),this,SLOT(OnClickImport())); - connect(ui->pushButtonExport,SIGNAL(clicked()),this,SLOT(OnClickExport())); - connect(ui->pushButtonDelete,SIGNAL(clicked()),this,SLOT(OnClickDelete())); - connect(ui->pushButtonClear,SIGNAL(clicked()),this,SLOT(OnClickClear())); - connect(ui->pushButtonApply,SIGNAL(clicked()),this,SLOT(OnClickApply())); - connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnClickReadback())); -} - -ControlVolumeSchedule::~ControlVolumeSchedule() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void ControlVolumeSchedule::refreshLable() -{ - ui->pushButtonAdd->setText(tr("Add")); - ui->pushButtonApply->setText(tr("Apply")); - ui->pushButtonClear->setText(tr("Clear")); - ui->pushButtonDelete->setText(tr("Delete")); - ui->pushButtonImport->setText(tr("Import")); - ui->pushButtonExport->setText(tr("Export")); - - ui->labelVolumeScheduleTip->setText(tr("Default volume tip")); - ui->labelDefalutVolume->setText(tr("Default volume")); - -} - -void ControlVolumeSchedule::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()==1) - { - ui->pushButtonReadback->setEnabled(true); - } - else { - ui->pushButtonReadback->setEnabled(false); - } - MACRO_DEFINE_CONTROL_FUNC3 - -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlVolumeSchedule::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetAutoVolumeTask") - { - JieXiJsonTaskVolume(jsonObject["taskVolume"].toObject()); - } - else if(strType == "SetAutoVolumeTask") - { - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlVolumeSchedule::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetAutoVolumeTask") - { - emit sigHaveSchedule(JieXiJsonTaskVolume(jsonObject["taskVolume"].toObject())); - - } - } - } -} - -void ControlVolumeSchedule::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_Volume) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlVolumeSchedule::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetAutoVolumeTask"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - -} -void ControlVolumeSchedule::OnClickAdd() -{ - QList Item; - Item.append(new QStandardItem(tr("10"))); - Item.append(new QStandardItem("00:00")); - Item.append(new QStandardItem("01:00")); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); - - Item.at(0)->setTextAlignment(Qt::AlignCenter); - Item.at(1)->setTextAlignment(Qt::AlignCenter); - Item.at(2)->setTextAlignment(Qt::AlignCenter); - m_pModel->appendRow(Item); - //m_lineEidt[i]->installEventFilter(this); - //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); - int i=m_pModel->rowCount()-1; - m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); - - if(m_pModel->rowCount()>0) - { - ui->labelVolumeScheduleTip->setVisible(true); - } - else { - ui->labelVolumeScheduleTip->setVisible(false); - } -} -void ControlVolumeSchedule::OnClickImport() { - QSettings settings; - QString strDir="/"; - if(settings.value("lasOpendFileDlgtDir").isValid()) - { - strDir=settings.value("lasOpendFileDlgtDir").toString(); - } - QFileDialog dlg; - QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog", - strDir, - tr("Volume Schedule (*.vols)")); - if(strBrightScheduleFile.isEmpty()) - return; - QFile fJson(strBrightScheduleFile); - if(fJson.open(QIODevice::ReadOnly)){ - QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll()); - QJsonObject oTaskVolume=jBrightSchedule.object(); - JieXiJsonTaskVolume(oTaskVolume); - fJson.close(); - } -} -bool ControlVolumeSchedule::JieXiJsonTaskVolume(QJsonObject oTaskVolume) -{ - OnClickClear(); - QJsonArray items; - QString strDefaultVolume=QString::number(oTaskVolume["defaultVolume"].toInt()); - if(!strDefaultVolume.isEmpty()) - ui->lineEdit->setText(strDefaultVolume); - items=oTaskVolume["items"].toArray(); - for(int i=0;i Item; - Item.append(new QStandardItem(QString::number(item["volume"].toInt()))); - Item.append(new QStandardItem(oSchedule["startTime"].toString())); - Item.append(new QStandardItem(oSchedule["endTime"].toString())); - - Item.at(0)->setTextAlignment(Qt::AlignCenter); - Item.at(1)->setTextAlignment(Qt::AlignCenter); - Item.at(2)->setTextAlignment(Qt::AlignCenter); - //m_lineEidt[i]->installEventFilter(this); - //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); - m_pModel->appendRow(Item); - if(oSchedule["filterType"].toString()=="None") - { - m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); - } - else if(oSchedule["filterType"].toString()=="Week") - { - QJsonArray oWeeks; - oWeeks=oSchedule["weekFilter"].toArray(); - for(int m=0;m<7;m++) - { - bool bHave=false; - for (int j=0;jsetData(m_pModel->index(i, m+3),bHave,Qt::UserRole); - } - } - } - if(items.count()>0) - return true; - else { - return false; - } -} -void ControlVolumeSchedule::OnClickExport() { - QSettings settings; - QString strDir="/"; - if(settings.value("lasOpendFileDlgtDir").isValid()) { - strDir=settings.value("lasOpendFileDlgtDir").toString(); - } - QFileDialog dlg; - QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("Volume Schedule (*.vols)")); - - if( saveFileName.isEmpty() ) - return; - settings.setValue("lasOpendFileDlgtDir",saveFileName); - QJsonObject oTaskSync=GetJsonObjectVolumeSchedule(); - QJsonDocument tSyncScheduleJsonDoc; - tSyncScheduleJsonDoc.setObject(oTaskSync); - - QFile f(saveFileName); - if(f.open(QIODevice::WriteOnly)) { - f.write(tSyncScheduleJsonDoc.toJson()); - f.close(); - } -} -void ControlVolumeSchedule::OnClickDelete() -{ - if(m_pModel->rowCount()>0) - { - QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); - if(selected.count()>0) - m_pModel->removeRows(selected.begin()->row(),selected.count()); - - } - if(m_pModel->rowCount()>0) - { - ui->labelVolumeScheduleTip->setVisible(true); - } - else { - ui->labelVolumeScheduleTip->setVisible(false); - } -} -void ControlVolumeSchedule:: OnClickClear() -{ - //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); - - if(m_pModel->rowCount()>0) - m_pModel->removeRows(0,m_pModel->rowCount()); - if(m_pModel->rowCount()>0) - { - ui->labelVolumeScheduleTip->setVisible(true); - } - else { - ui->labelVolumeScheduleTip->setVisible(false); - } - } -void ControlVolumeSchedule::OnClickApply() -{ - if(m_pLedlist==nullptr) - return; - - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetAutoVolumeTask"); - QJsonObject oTaskVolume=GetJsonObjectVolumeSchedule(); - json.insert("taskVolume", oTaskVolume); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetAutoVolumeTask"),tr("Success"),tr("failed")) - -} -void ControlVolumeSchedule::OnClickReadback() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetAutoVolumeTask"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetAutoVolumeTask"),tr("Success"),tr("failed")) - -} -QJsonObject ControlVolumeSchedule::GetJsonObjectVolumeSchedule() -{ - QJsonObject oTaskVolume; - QJsonArray oItems; - - oTaskVolume["createDate"] = QJsonValue::Null; - oTaskVolume["createBy"] = "alahover"; - oTaskVolume["defaultVolume"] = ui->lineEdit->text().toInt(); - oTaskVolume["volume"] = ui->lineEdit->text().toInt(); - oTaskVolume["name"] = "TimingVolume"; - - - for(int i=0; irowCount(); i++) - { - QJsonObject oItem; - oItem["volume"] = m_pModel->data(m_pModel->index(i, 0)).toInt(); - - QJsonArray oSchedules; - QJsonObject oSchedule; - oSchedule["timeType"] = "Range"; - oSchedule["startTime"] = m_pModel->data(m_pModel->index(i, 1)).toString();; - oSchedule["endTime"] = m_pModel->data(m_pModel->index(i, 2)).toString();; - oSchedule["dateType"] = "All"; - oSchedule["startDate"] = QJsonValue::Null; - oSchedule["endDate"] = QJsonValue::Null; - oSchedule["monthFilter"] = QJsonArray(); - - bool bSun=m_pModel->data(m_pModel->index(i, 3),Qt::UserRole).toBool(); - bool bMon=m_pModel->data(m_pModel->index(i, 4),Qt::UserRole).toBool(); - bool bTur=m_pModel->data(m_pModel->index(i, 5),Qt::UserRole).toBool(); - bool bWed=m_pModel->data(m_pModel->index(i, 6),Qt::UserRole).toBool(); - bool bThu=m_pModel->data(m_pModel->index(i, 7),Qt::UserRole).toBool(); - bool bFri=m_pModel->data(m_pModel->index(i, 8),Qt::UserRole).toBool(); - bool bSat=m_pModel->data(m_pModel->index(i, 9),Qt::UserRole).toBool(); - - - if(bMon && bTur && bWed && bThu && bFri && bSat && bSun) - { - oSchedule["filterType"] = "None"; - oSchedule["weekFilter"] = QJsonArray(); - - } - else { - oSchedule["filterType"] = "Week"; - QJsonArray tempArray; - if( bSun) - { - tempArray.append(0); - } - if(bMon) - { - tempArray.append(1); - } - if(bTur) - { - tempArray.append(2); - } - if( bWed) - { - tempArray.append(3); - } - if( bThu) - { - tempArray.append(4); - } - if( bFri) - { - tempArray.append(5); - } - if( bSat) - { - tempArray.append(6); - } - - - oSchedule["weekFilter"] = tempArray; - - } - - - oSchedules.append(oSchedule); - oItem["schedules"] = oSchedules; - oItems.append(oItem); - } - - oTaskVolume["items"] = oItems; - return oTaskVolume; - -} -void ControlVolumeSchedule::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} +#include "controlvolumeschedule.h" +#include "ui_controlvolumeschedule.h" +#include "base/x_uimsgboxok.h" +#include "QFileDialog" +#include "QDir" +#include +#include +#include +#include +#include +#include +#include "QSettings" +#include "base/x_spinboxdelegate.h" +#include "base/x_timeeditdelegate.h" +#include "base/x_checkboxdelegate.h" +#include "tools.h" +ControlVolumeSchedule::ControlVolumeSchedule(QWidget *parent,QList *list) : + QWidget(parent), + ui(new Ui::ControlVolumeSchedule) +{ + m_pLedlist=list; + ui->setupUi(this); + refreshLable(); +setStyleSheet(css); + ui->pushButtonAdd->setProperty("ssType", "progManageTool"); + ui->pushButtonAdd->setFlat(true); + ui->pushButtonDelete->setProperty("ssType", "progManageTool"); + ui->pushButtonDelete->setFlat(true); + ui->pushButtonClear->setProperty("ssType", "progManageTool"); + ui->pushButtonClear->setFlat(true); + ui->pushButtonApply->setProperty("ssType", "progManageTool"); + ui->pushButtonApply->setFlat(true); + ui->pushButtonImport->setProperty("ssType", "progManageTool"); + ui->pushButtonExport->setProperty("ssType", "progManageTool"); + ui->pushButtonReadback->setProperty("ssType", "progManageTool"); + ui->lineEdit->setText("10"); + m_pModel = new QStandardItemModel(this); + m_pModel->setColumnCount(10); + m_pModel->setHeaderData(0,Qt::Horizontal, tr("Volume value")); + m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time")); + m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time")); + m_pModel->setHeaderData(3,Qt::Horizontal, tr("SUN")); + m_pModel->setHeaderData(4,Qt::Horizontal, tr("MON")); + m_pModel->setHeaderData(5,Qt::Horizontal, tr("TUE")); + m_pModel->setHeaderData(6,Qt::Horizontal, tr("WED")); + m_pModel->setHeaderData(7,Qt::Horizontal, tr("THU")); + m_pModel->setHeaderData(8,Qt::Horizontal, tr("FRI")); + m_pModel->setHeaderData(9,Qt::Horizontal, tr("SAT")); + ui->tableView->setModel(m_pModel); + SpinBoxDelegate *pVolumeDelegate=new SpinBoxDelegate(this,1); + ui->tableView->setItemDelegateForColumn(0,pVolumeDelegate); + + X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this); + ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate); + ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate); + X_CheckBoxDelegate *WeekDelegate=new X_CheckBoxDelegate(this); + ui->tableView->setItemDelegateForColumn(3,WeekDelegate); + ui->tableView->setItemDelegateForColumn(4,WeekDelegate); + ui->tableView->setItemDelegateForColumn(5,WeekDelegate); + ui->tableView->setItemDelegateForColumn(6,WeekDelegate); + ui->tableView->setItemDelegateForColumn(7,WeekDelegate); + ui->tableView->setItemDelegateForColumn(8,WeekDelegate); + ui->tableView->setItemDelegateForColumn(9,WeekDelegate); + + + ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + // ui->tableView->verticalHeader()->hide(); + ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + ui->tableView->setFocusPolicy(Qt::NoFocus); + + + MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) + + connect(ui->pushButtonAdd,SIGNAL(clicked()),this,SLOT(OnClickAdd())); + connect(ui->pushButtonImport,SIGNAL(clicked()),this,SLOT(OnClickImport())); + connect(ui->pushButtonExport,SIGNAL(clicked()),this,SLOT(OnClickExport())); + connect(ui->pushButtonDelete,SIGNAL(clicked()),this,SLOT(OnClickDelete())); + connect(ui->pushButtonClear,SIGNAL(clicked()),this,SLOT(OnClickClear())); + connect(ui->pushButtonApply,SIGNAL(clicked()),this,SLOT(OnClickApply())); + connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnClickReadback())); +} + +ControlVolumeSchedule::~ControlVolumeSchedule() +{ + delete ui; + if(pHpptClient != nullptr) + { + qDebug() <<"delete pHpptClient in ~NetComm"; + delete pHpptClient; + pHpptClient=nullptr; + } + if(pHpptClientAll != nullptr) + { + qDebug() <<"delete pHpptClientAll in ~NetComm"; + delete pHpptClientAll; + pHpptClientAll=nullptr; + } +} +void ControlVolumeSchedule::refreshLable() +{ + ui->pushButtonAdd->setText(tr("Add")); + ui->pushButtonApply->setText(tr("Apply")); + ui->pushButtonClear->setText(tr("Clear")); + ui->pushButtonDelete->setText(tr("Delete")); + ui->pushButtonImport->setText(tr("Import")); + ui->pushButtonExport->setText(tr("Export")); + + ui->labelVolumeScheduleTip->setText(tr("Default volume tip")); + ui->labelDefalutVolume->setText(tr("Default volume")); + +} + +void ControlVolumeSchedule::onSelectedDeviceList(QList *list) +{ + m_pLedlist=list; + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()==1) + { + ui->pushButtonReadback->setEnabled(true); + } + else { + ui->pushButtonReadback->setEnabled(false); + } + MACRO_DEFINE_CONTROL_FUNC3 + +} +//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 +void ControlVolumeSchedule::OnProHttpResponse(QString url, QString postMD5, QByteArray data) +{ + Q_UNUSED(postMD5) + //qDebug()<< url + "\r\n"+m_strUrl; + if(url == m_strUrl) + { + QJsonParseError parseJsonErr; + QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); + if(!(parseJsonErr.error == QJsonParseError::NoError)) + { + if(data.size()==0) + qDebug()<<"json is empty"; + else + qDebug()<count()!=1) + return; + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "GetAutoVolumeTask"); + HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); + +} +void ControlVolumeSchedule::OnClickAdd() +{ + QList Item; + Item.append(new QStandardItem(tr("10"))); + Item.append(new QStandardItem("00:00")); + Item.append(new QStandardItem("01:00")); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); +// Item.append(new QStandardItem(true)); + + Item.at(0)->setTextAlignment(Qt::AlignCenter); + Item.at(1)->setTextAlignment(Qt::AlignCenter); + Item.at(2)->setTextAlignment(Qt::AlignCenter); + m_pModel->appendRow(Item); + //m_lineEidt[i]->installEventFilter(this); + //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); + int i=m_pModel->rowCount()-1; + m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); + + if(m_pModel->rowCount()>0) + { + ui->labelVolumeScheduleTip->setVisible(true); + } + else { + ui->labelVolumeScheduleTip->setVisible(false); + } +} +void ControlVolumeSchedule::OnClickImport() { + QSettings settings; + QString strDir="/"; + if(settings.value("lasOpendFileDlgtDir").isValid()) + { + strDir=settings.value("lasOpendFileDlgtDir").toString(); + } + QFileDialog dlg; + QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog", + strDir, + tr("Volume Schedule (*.vols)")); + if(strBrightScheduleFile.isEmpty()) + return; + QFile fJson(strBrightScheduleFile); + if(fJson.open(QIODevice::ReadOnly)){ + QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll()); + QJsonObject oTaskVolume=jBrightSchedule.object(); + JieXiJsonTaskVolume(oTaskVolume); + fJson.close(); + } +} +bool ControlVolumeSchedule::JieXiJsonTaskVolume(QJsonObject oTaskVolume) +{ + OnClickClear(); + QJsonArray items; + QString strDefaultVolume=QString::number(oTaskVolume["defaultVolume"].toInt()); + if(!strDefaultVolume.isEmpty()) + ui->lineEdit->setText(strDefaultVolume); + items=oTaskVolume["items"].toArray(); + for(int i=0;i Item; + Item.append(new QStandardItem(QString::number(item["volume"].toInt()))); + Item.append(new QStandardItem(oSchedule["startTime"].toString())); + Item.append(new QStandardItem(oSchedule["endTime"].toString())); + + Item.at(0)->setTextAlignment(Qt::AlignCenter); + Item.at(1)->setTextAlignment(Qt::AlignCenter); + Item.at(2)->setTextAlignment(Qt::AlignCenter); + //m_lineEidt[i]->installEventFilter(this); + //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); + m_pModel->appendRow(Item); + if(oSchedule["filterType"].toString()=="None") + { + m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); + m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); + } + else if(oSchedule["filterType"].toString()=="Week") + { + QJsonArray oWeeks; + oWeeks=oSchedule["weekFilter"].toArray(); + for(int m=0;m<7;m++) + { + bool bHave=false; + for (int j=0;jsetData(m_pModel->index(i, m+3),bHave,Qt::UserRole); + } + } + } + if(items.count()>0) + return true; + else { + return false; + } +} +void ControlVolumeSchedule::OnClickExport() { + QSettings settings; + QString strDir="/"; + if(settings.value("lasOpendFileDlgtDir").isValid()) { + strDir=settings.value("lasOpendFileDlgtDir").toString(); + } + QFileDialog dlg; + QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("Volume Schedule (*.vols)")); + + if( saveFileName.isEmpty() ) + return; + settings.setValue("lasOpendFileDlgtDir",saveFileName); + QJsonObject oTaskSync=GetJsonObjectVolumeSchedule(); + QJsonDocument tSyncScheduleJsonDoc; + tSyncScheduleJsonDoc.setObject(oTaskSync); + + QFile f(saveFileName); + if(f.open(QIODevice::WriteOnly)) { + f.write(tSyncScheduleJsonDoc.toJson()); + f.close(); + } +} +void ControlVolumeSchedule::OnClickDelete() +{ + if(m_pModel->rowCount()>0) + { + QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); + if(selected.count()>0) + m_pModel->removeRows(selected.begin()->row(),selected.count()); + + } + if(m_pModel->rowCount()>0) + { + ui->labelVolumeScheduleTip->setVisible(true); + } + else { + ui->labelVolumeScheduleTip->setVisible(false); + } +} +void ControlVolumeSchedule:: OnClickClear() +{ + //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); + + if(m_pModel->rowCount()>0) + m_pModel->removeRows(0,m_pModel->rowCount()); + if(m_pModel->rowCount()>0) + { + ui->labelVolumeScheduleTip->setVisible(true); + } + else { + ui->labelVolumeScheduleTip->setVisible(false); + } + } +void ControlVolumeSchedule::OnClickApply() +{ + if(m_pLedlist==nullptr) + return; + + if(m_pLedlist->count()<=1) + { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + } + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "SetAutoVolumeTask"); + QJsonObject oTaskVolume=GetJsonObjectVolumeSchedule(); + json.insert("taskVolume", oTaskVolume); + MACRO_DEFINE_TIPDLG_FUCN(tr("SetAutoVolumeTask"),tr("Success"),tr("failed")) + +} +void ControlVolumeSchedule::OnClickReadback() +{ + if(m_pLedlist==nullptr) + return; + if(m_pLedlist->count()<=1) + { + if(m_pLedCard==nullptr||m_pLedlist->count()==0) + { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); + pDlg->exec(); + return; + } + } + QJsonObject json; + json.insert("_id", getRandomString(10)); + json.insert("_type", "GetAutoVolumeTask"); + MACRO_DEFINE_TIPDLG_FUCN(tr("GetAutoVolumeTask"),tr("Success"),tr("failed")) + +} +QJsonObject ControlVolumeSchedule::GetJsonObjectVolumeSchedule() +{ + QJsonObject oTaskVolume; + QJsonArray oItems; + + oTaskVolume["createDate"] = QJsonValue::Null; + oTaskVolume["createBy"] = "alahover"; + oTaskVolume["defaultVolume"] = ui->lineEdit->text().toInt(); + oTaskVolume["volume"] = ui->lineEdit->text().toInt(); + oTaskVolume["name"] = "TimingVolume"; + + + for(int i=0; irowCount(); i++) + { + QJsonObject oItem; + oItem["volume"] = m_pModel->data(m_pModel->index(i, 0)).toInt(); + + QJsonArray oSchedules; + QJsonObject oSchedule; + oSchedule["timeType"] = "Range"; + oSchedule["startTime"] = m_pModel->data(m_pModel->index(i, 1)).toString();; + oSchedule["endTime"] = m_pModel->data(m_pModel->index(i, 2)).toString();; + oSchedule["dateType"] = "All"; + oSchedule["startDate"] = QJsonValue::Null; + oSchedule["endDate"] = QJsonValue::Null; + oSchedule["monthFilter"] = QJsonArray(); + + bool bSun=m_pModel->data(m_pModel->index(i, 3),Qt::UserRole).toBool(); + bool bMon=m_pModel->data(m_pModel->index(i, 4),Qt::UserRole).toBool(); + bool bTur=m_pModel->data(m_pModel->index(i, 5),Qt::UserRole).toBool(); + bool bWed=m_pModel->data(m_pModel->index(i, 6),Qt::UserRole).toBool(); + bool bThu=m_pModel->data(m_pModel->index(i, 7),Qt::UserRole).toBool(); + bool bFri=m_pModel->data(m_pModel->index(i, 8),Qt::UserRole).toBool(); + bool bSat=m_pModel->data(m_pModel->index(i, 9),Qt::UserRole).toBool(); + + + if(bMon && bTur && bWed && bThu && bFri && bSat && bSun) + { + oSchedule["filterType"] = "None"; + oSchedule["weekFilter"] = QJsonArray(); + + } + else { + oSchedule["filterType"] = "Week"; + QJsonArray tempArray; + if( bSun) + { + tempArray.append(0); + } + if(bMon) + { + tempArray.append(1); + } + if(bTur) + { + tempArray.append(2); + } + if( bWed) + { + tempArray.append(3); + } + if( bThu) + { + tempArray.append(4); + } + if( bFri) + { + tempArray.append(5); + } + if( bSat) + { + tempArray.append(6); + } + + + oSchedule["weekFilter"] = tempArray; + + } + + + oSchedules.append(oSchedule); + oItem["schedules"] = oSchedules; + oItems.append(oItem); + } + + oTaskVolume["items"] = oItems; + return oTaskVolume; + +} +void ControlVolumeSchedule::DeletePostingDlg() +{ + if(m_PostingDlg!=nullptr) + { + delete m_PostingDlg; + m_PostingDlg=nullptr; + } +} diff --git a/LedOK/wDevicesManager/controlvolumeschedule.h b/LedOK/device/controlvolumeschedule.h similarity index 95% rename from LedOK/wDevicesManager/controlvolumeschedule.h rename to LedOK/device/controlvolumeschedule.h index 72770bb..85cf53f 100644 --- a/LedOK/wDevicesManager/controlvolumeschedule.h +++ b/LedOK/device/controlvolumeschedule.h @@ -1,60 +1,60 @@ -#ifndef CONTROLVOLUMESCHEDULE_H -#define CONTROLVOLUMESCHEDULE_H - -#include -#include -#include -#include -#include -#include - -namespace Ui { -class ControlVolumeSchedule; -} - -class ControlVolumeSchedule : public QWidget -{ - Q_OBJECT - -public: - explicit ControlVolumeSchedule(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlVolumeSchedule(); -protected slots: - void refreshLable(); - void OnClickAdd(); - void OnClickImport(); - void OnClickExport(); - void OnClickDelete(); - void OnClickClear(); - void OnClickApply(); - void OnClickReadback(); -private: - Ui::ControlVolumeSchedule *ui; - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigSend(QJsonObject &,QString); - void sigHaveSchedule(bool); - protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; - QStandardItemModel * m_pModel; - bool JieXiJsonTaskVolume(QJsonObject oTaskVolume); - QJsonObject GetJsonObjectVolumeSchedule(); - -}; - -#endif // CONTROLVOLUMESCHEDULE_H +#ifndef CONTROLVOLUMESCHEDULE_H +#define CONTROLVOLUMESCHEDULE_H + +#include +#include +#include +#include +#include +#include + +namespace Ui { +class ControlVolumeSchedule; +} + +class ControlVolumeSchedule : public QWidget +{ + Q_OBJECT + +public: + explicit ControlVolumeSchedule(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); + ~ControlVolumeSchedule(); + void refreshLable(); +protected slots: + void OnClickAdd(); + void OnClickImport(); + void OnClickExport(); + void OnClickDelete(); + void OnClickClear(); + void OnClickApply(); + void OnClickReadback(); +private: + Ui::ControlVolumeSchedule *ui; + //类似的控制操作信号和槽函数和变量定义 + signals: + void sigSend(QJsonObject &,QString); + void sigHaveSchedule(bool); + protected slots: + void DeletePostingDlg(); + void OnProHttpResponse(QString url, QString postMD5, QByteArray data); + void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); + void onSelectedDeviceList(QList *); + void onReadbackAllThisPage(); + void OnControlTypeSwitchIndexChanged(int index); + private: + QList *m_pLedlist=nullptr; + LedCard *m_pLedCard = nullptr; + LedCard *m_oldLedlist = nullptr; + HpptClient *pHpptClient = nullptr; + HpptClient *pHpptClientAll = nullptr; + QString m_strUrl=""; + LoEmptyDialog * m_PostingDlg=nullptr; + QTimer *m_pGetAskTimer=nullptr; + bool m_bSelected=false; + QStandardItemModel * m_pModel; + bool JieXiJsonTaskVolume(QJsonObject oTaskVolume); + QJsonObject GetJsonObjectVolumeSchedule(); + +}; + +#endif // CONTROLVOLUMESCHEDULE_H diff --git a/LedOK/wDevicesManager/controlvolumeschedule.ui b/LedOK/device/controlvolumeschedule.ui similarity index 96% rename from LedOK/wDevicesManager/controlvolumeschedule.ui rename to LedOK/device/controlvolumeschedule.ui index bfda2a2..7bfb54f 100644 --- a/LedOK/wDevicesManager/controlvolumeschedule.ui +++ b/LedOK/device/controlvolumeschedule.ui @@ -1,251 +1,251 @@ - - - ControlVolumeSchedule - - - - 0 - 0 - 708 - 447 - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - Defalut volume tip - - - true - - - - - - - - - 10 - - - 0 - - - - - - 60 - 30 - - - - Add - - - - - - - - 60 - 30 - - - - Delete - - - - - - - - 60 - 30 - - - - Clear - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Default Volume - - - - - - - - 30 - 16777215 - - - - background-color: #FFFFFF; - - - - - - - (0-15) - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Import - - - - - - - - 0 - 30 - - - - Export - - - - - - - - - background-color: #FFFFFF; - - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 60 - 30 - - - - Apply - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Readback - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - + + + ControlVolumeSchedule + + + + 0 + 0 + 708 + 447 + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + Defalut volume tip + + + true + + + + + + + + + 10 + + + 0 + + + + + + 60 + 30 + + + + Add + + + + + + + + 60 + 30 + + + + Delete + + + + + + + + 60 + 30 + + + + Clear + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Default Volume + + + + + + + + 30 + 16777215 + + + + background-color: #FFFFFF; + + + + + + + (0-15) + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 30 + + + + Import + + + + + + + + 0 + 30 + + + + Export + + + + + + + + + background-color: #FFFFFF; + + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 60 + 30 + + + + Apply + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 30 + + + + Readback + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + diff --git a/LedOK/device/controlvolumewidget.cpp b/LedOK/device/controlvolumewidget.cpp new file mode 100644 index 0000000..66a8baf --- /dev/null +++ b/LedOK/device/controlvolumewidget.cpp @@ -0,0 +1,154 @@ +#include "controlvolumewidget.h" +#include "gutil/qgui.h" +#include "globaldefine.h" +#include "base/waitingdlg.h" +#include "tools.h" +#include + +ControlVolumeWidget::ControlVolumeWidget(QWidget *parent,QList *list) : QWidget(parent) { + auto vBox = new VBox(this); + + lbVolumeControl = new QLabel; + lbVolumeControl->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbVolumeControl); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + fdManual = new QRadioButton; + hBox->addWidget(fdManual); + hBox->addSpacing(40); + + fdSchedule = new QRadioButton; + hBox->addWidget(fdSchedule); + hBox->addStretch(); + + auto stack = new QStackedLayout(vBox); + { + auto vBox = new VBox(stack); + vBox->addSpacing(20); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + lbVolume = new QLabel; + hBox->addWidget(lbVolume); + + fdVolume = new QSlider(Qt::Horizontal); + fdVolume->setTickPosition(QSlider::TicksAbove); + fdVolume->setRange(0, 15); + connect(fdVolume, &QSlider::sliderReleased, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetVolume"); + json.insert("_type", "SetVolume"); + json.insert("volume", fdVolume->value()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetVolume")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetVolume")) + } + } + }); + hBox->addWidget(fdVolume); + + auto lbCurVol = new QLabel; + lbCurVol->setMinimumWidth(30); + connect(fdVolume, &QSlider::valueChanged, lbCurVol, (void(QLabel::*)(int))&QLabel::setNum); + hBox->addWidget(lbCurVol); + hBox->addStretch(); + + fdVolumeGet = new QPushButton; + fdVolumeGet->setMinimumSize(QSize(60, 30)); + fdVolumeGet->setProperty("ssType", "progManageTool"); + connect(fdVolumeGet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetVolume"); + json.insert("_type", "GetVolume"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetVolume")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdVolume->setValue(json["volume"].toInt()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = QString::number(json["volume"].toInt()); + gFdResInfo->append(cardId+" "+tr("GetVolume")+" "+err); + }); + } + } + }); + vBox->addWidget(fdVolumeGet, 0, Qt::AlignCenter); + vBox->addStretch(); + } + m_pSchedule = new ControlVolumeSchedule(this, list); + connect(m_pSchedule, &ControlVolumeSchedule::sigHaveSchedule, this, [=](bool b) { + if(b) fdSchedule->setChecked(true); + else fdManual->setChecked(true); + }); + stack->addWidget(m_pSchedule); + + connect(fdSchedule, &QRadioButton::toggled, stack, &QStackedLayout::setCurrentIndex); + fdManual->setChecked(true); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void ControlVolumeWidget::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void ControlVolumeWidget::init() { + bool isSingle = gSelCards->count()==1; + if(! isSingle) return; + auto card = gSelCards->at(0); + + QJsonObject json; + json.insert("_id", "GetVolume"); + json.insert("_type", "GetVolume"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdVolume->setValue(json["volume"].toInt()); + }); +} + +void ControlVolumeWidget::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void ControlVolumeWidget::transUi() { + lbVolumeControl->setText(tr("Volume Control")); + fdManual->setText(tr("Manual")); + fdSchedule->setText(tr("Schedule")); + + lbVolume->setText(tr("Volume")); + fdVolumeGet->setText(tr("Readback")); + + m_pSchedule->refreshLable(); +} diff --git a/LedOK/device/controlvolumewidget.h b/LedOK/device/controlvolumewidget.h new file mode 100644 index 0000000..d9a14db --- /dev/null +++ b/LedOK/device/controlvolumewidget.h @@ -0,0 +1,31 @@ +#ifndef CONTROLVOLUMEWIDGET_H +#define CONTROLVOLUMEWIDGET_H + +#include +#include +#include "QStackedWidget" +#include + +class ControlVolumeWidget : public QWidget { + Q_OBJECT +public: + explicit ControlVolumeWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); +protected: + void showEvent(QShowEvent *event) override; + void init(); + void changeEvent(QEvent *) override; + void transUi(); + +private: + ControlVolumeSchedule *m_pSchedule; + + QLabel *lbVolumeControl; + QRadioButton *fdManual; + QRadioButton *fdSchedule; + + QLabel *lbVolume; + QSlider *fdVolume; + QPushButton *fdVolumeGet; +}; + +#endif // CONTROLVOLUMEWIDGET_H diff --git a/LedOK/device/ctrladvancedpanel.cpp b/LedOK/device/ctrladvancedpanel.cpp new file mode 100644 index 0000000..3d68ac5 --- /dev/null +++ b/LedOK/device/ctrladvancedpanel.cpp @@ -0,0 +1,2436 @@ +#include "ctrladvancedpanel.h" +#include "deviceitem.h" +#include "globaldefine.h" +#include "base/waitingdlg.h" +#include "base/changepasswordform.h" +#include "base/updateledset3dialog.h" +#include "passwordindlg.h" +#include "tools.h" +#include "gutil/qgui.h" +#include "gutil/qnetwork.h" +#include "program/ephoto.h" +#include "upgradeapkdialog.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +CtrlAdvancedPanel::CtrlAdvancedPanel(QWidget *parent) : QWidget(parent) { + setFocusPolicy(Qt::StrongFocus); + + auto vBox = new QVBoxLayout(this); + + lbTitle = new QLabel; + lbTitle->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbTitle); + + auto hBox = new HBox(vBox); + + lbScreenWidth = new QLabel; + hBox->addWidget(lbScreenWidth); + + fdScreenWidth = new QLineEdit; + fdScreenWidth->setMaximumWidth(60); + hBox->addWidget(fdScreenWidth); + + lbScreenHeight = new QLabel; + hBox->addWidget(lbScreenHeight); + + fdScreenHeight = new QLineEdit; + fdScreenHeight->setMaximumWidth(60); + hBox->addWidget(fdScreenHeight); + + btnScreenSet = new QPushButton; + btnScreenSet->setProperty("ssType", "progManageTool"); + connect(btnScreenSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto width = fdScreenWidth->text(); + if(width.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"),tr("InputWidthTip")); + fdScreenWidth->setFocus(); + return; + } + auto height = fdScreenHeight->text(); + if(height.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"),tr("InputHeightTip")); + fdScreenHeight->setFocus(); + return; + } + QJsonObject json; + json.insert("_id", "SetScreenSize"); + json.insert("_type", "SetScreenSize"); + json.insert("width", width.toInt()); + json.insert("height", height.toInt()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetScreenSize")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetScreenSize")) + } + } + }); + hBox->addWidget(btnScreenSet); + + hBox->addSpacing(20); + + lbAlias = new QLabel; + hBox->addWidget(lbAlias); + + fdAlias = new QLineEdit; + fdAlias->setMaximumWidth(200); + hBox->addWidget(fdAlias); + + btnAliasSet = new QPushButton; + btnAliasSet->setProperty("ssType", "progManageTool"); + connect(btnAliasSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto alias = fdAlias->text(); + if(alias.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"),tr("InputAliasTip")); + fdAlias->setFocus(); + return; + } + QJsonObject json; + json.insert("_id", "SetCardAlias"); + json.insert("_type", "SetCardAlias"); + json.insert("alias", QString::fromLatin1(alias.toUtf8().toBase64())); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetCardAlias")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetCardAlias")) + } + } + }); + hBox->addWidget(btnAliasSet); + + hBox->addStretch(); + + hBox = new HBox(vBox); + + labelWebServer = new QLabel; + hBox->addWidget(labelWebServer); + + fdWebServerAddr = new QComboBox; + fdWebServerAddr->addItem(tr("www.m2mled.net")); + fdWebServerAddr->addItem(tr("www.ledaips.com")); + fdWebServerAddr->addItem(tr("https://www.taxihub.cn:2340")); + fdWebServerAddr->addItem(tr("https://www.ledaips.com:2340")); + fdWebServerAddr->addItem(tr("https://www.36taxi.com:2340")); + fdWebServerAddr->addItem(tr("www.tlzxled.com")); + fdWebServerAddr->setMinimumWidth(260); + fdWebServerAddr->setEditable(true); + hBox->addWidget(fdWebServerAddr); + + lbCompanyId = new QLabel; + hBox->addWidget(lbCompanyId); + + fdCompanyId = new QLineEdit; + fdCompanyId->setFixedWidth(100); + hBox->addWidget(fdCompanyId); + + btnWebServerSet = new QPushButton; + btnWebServerSet->setProperty("ssType", "progManageTool"); + connect(btnWebServerSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + + QString serverAddr = fdWebServerAddr->currentText(); + if(serverAddr.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"),tr("InputWebServerAddressTip")); + fdWebServerAddr->setFocus(); + return; + } + auto companyId = fdCompanyId->text(); + if(companyId.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"),tr("InputCompanyIdTip")); + fdCompanyId->setFocus(); + return; + } + auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Do you want to modify webserveraddress and companyId?")); + if(res != QMessageBox::Yes) return; + QJsonObject json; + json.insert("_id", "SetOnlineAddr"); + json.insert("_type", "SetOnlineAddr"); + json.insert("server", serverAddr); + json.insert("companyID", companyId); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetOnlineAddr")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetOnlineAddr")) + } + } + }); + hBox->addWidget(btnWebServerSet); + + hBox->addStretch(); + + hBox = new HBox(vBox); + + label = new QLabel; + hBox->addWidget(label); + + fdRealtimeServer = new QComboBox; + fdRealtimeServer->addItem(tr("www.ledokcloud.com/realtime")); + fdRealtimeServer->setMinimumWidth(260); + fdRealtimeServer->setEditable(true); + hBox->addWidget(fdRealtimeServer); + + btnRealtimeServerSet = new QPushButton; + btnRealtimeServerSet->setProperty("ssType", "progManageTool"); + connect(btnRealtimeServerSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetRealtimeServer"); + json.insert("_type", "SetRealtimeServer"); + json.insert("server", fdRealtimeServer->currentText()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetRealtimeServer")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetRealtimeServer")) + } + } + }); + hBox->addWidget(btnRealtimeServerSet); + + btnRealtimeClear = new QPushButton; + btnRealtimeClear->setProperty("ssType", "progManageTool"); + connect(btnRealtimeClear, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + fdRealtimeServer->clearEditText(); + QJsonObject json; + json.insert("_id", "SetRealtimeServer"); + json.insert("_type", "SetRealtimeServer"); + json.insert("server", ""); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("ClearRealtimeServer")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("ClearRealtimeServer")) + } + } + }); + hBox->addWidget(btnRealtimeClear); + + hBox->addStretch(); + + + hBox = new HBox(vBox); + + btnWareUpdate = new QPushButton; + btnWareUpdate->setMinimumSize(100, 30); + btnWareUpdate->setProperty("ssType", "progManageTool"); + connect(btnWareUpdate, &QPushButton::clicked, this, [] { + UpgradeApkDialog dlg(gMainWin); + dlg.exec(); + }); + hBox->addWidget(btnWareUpdate); + + lbWareTip = new QLabel; + hBox->addWidget(lbWareTip); + hBox->addStretch(); + + hBox = new HBox(vBox); + + btnApkCheck = new QPushButton; + btnApkCheck->setProperty("ssType", "progManageTool"); + connect(btnApkCheck, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "CheckSoftVersions"); + json.insert("_type", "CheckSoftVersions"); + if(gSelCards->count() != 1) return; + auto waitingDlg = new WaitingDlg(this, tr("Check Apk Version")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->close(); + fdPkg->clear(); + auto apps = json["apps"].toArray(); + auto infoDlg = new QDialog(this); + infoDlg->setWindowFlag(Qt::WindowContextHelpButtonHint, false); + infoDlg->resize(500, 500); + infoDlg->setWindowTitle(tr("Software Version Info")); + auto vBox = new QVBoxLayout(infoDlg); + vBox->setContentsMargins(0, 0, 0, 0); + auto table = new Table{ + {"apk", "Apk"}, + {"ver", tr("Version")}, + {"pkg", tr("Package")} + }; + table->setDefs(); + table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + table->setRowCount(apps.size()); + vBox->addWidget(table); + for(int i=0; isetItem(i, "apk", new QTableWidgetItem{app["appName"].toString()}); + table->setItem(i, "ver", new QTableWidgetItem{app["versionName"].toString()}); + table->setItem(i, "pkg", new QTableWidgetItem{packageName}); + if(! (packageName.endsWith(".cardsystem") || packageName.endsWith(".systemcore") || packageName.endsWith(".update"))) fdPkg->addItem(packageName); + } + infoDlg->show(); + }); + }); + hBox->addWidget(btnApkCheck); + + fdPkg = new QComboBox; + fdPkg->setEditable(true); + fdPkg->setMinimumWidth(200); + hBox->addWidget(fdPkg); + + fdUninstall = new QPushButton; + fdUninstall->setProperty("ssType", "progManageTool"); + connect(fdUninstall, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto pkg = fdPkg->currentText(); + if(pkg.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Package name is null")); + return; + } + QJsonObject json; + json.insert("_id", "UninstallSoftware"); + json.insert("_type", "UninstallSoftware"); + json.insert("packageName", pkg); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("UninstallSoftware")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("UninstallSoftware")) + } + } + }); + hBox->addWidget(fdUninstall); + + btnIsRunning = new QPushButton; + btnIsRunning->setProperty("ssType", "progManageTool"); + connect(btnIsRunning, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto pkg = fdPkg->currentText(); + if(pkg.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Package name is null")); + return; + } + QJsonObject json; + json.insert("_id", "IsSoftwareRunning"); + json.insert("_type", "IsSoftwareRunning"); + json.insert("packageName", pkg); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Check apk running status")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->close(); + QMessageBox::information(gMainWin, tr("Tip"), json["running"].toBool() ? tr("running") : tr("no running")); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + gFdResInfo->append(cardId+" "+tr("Check apk running status")+" "+(err.isEmpty() ? (json["running"].toBool() ? tr("running") : tr("no running")) : err)); + }); + } + } + }); + hBox->addWidget(btnIsRunning); + hBox->addStretch(); + + hBox = new HBox(vBox); + + btnRestart = new QPushButton; + btnRestart->setProperty("ssType", "progManageTool"); + connect(btnRestart, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "RestartAndroid"); + json.insert("_type", "RestartAndroid"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("RestartAndroid")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("RestartAndroid")) + } + } + }); + hBox->addWidget(btnRestart); + + btnClearProg = new QPushButton; + btnClearProg->setProperty("ssType", "progManageTool"); + connect(btnClearProg, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Clearing Program")+" ..."); + waitingDlg->show(); + auto card = gSelCards->at(0); + auto tcp = new QTcpSocket(); + auto timer = new QTimer(tcp); + timer->setSingleShot(true); + connect(timer, &QTimer::timeout, tcp, [=] { + waitingDlg->close(); + tcp->abort(); + tcp->deleteLater(); + QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear Program")+" "+tr("Timeout")); + }); + connect(waitingDlg, &WaitingDlg::rejected, tcp, [=] { + timer->stop(); + tcp->abort(); + tcp->deleteLater(); + }); + connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { + timer->stop(); + tcp->write("{\"_type\":\"DelPrograms\",\"_id\":\"DelPrograms\",\"zVer\":\"xixun1\"}"); + timer->start(10000); + }); + connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, waitingDlg] { + timer->stop(); + QByteArray resp = tcp->readAll(); + tcp->close(); + tcp->deleteLater(); + QJsonParseError parseErr; + QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); + if(parseErr.error != QJsonParseError::NoError) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), parseErr.errorString()); + } else if(! json["success"].toBool()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear Program")+" "+tr("Failed")); + } else waitingDlg->success(); + }); + connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, waitingDlg](QAbstractSocket::SocketError err) { + timer->stop(); + tcp->close(); + tcp->deleteLater(); + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), QString(socketErrKey(err))+" ("+QString::number(err)+") "+tcp->errorString()); + }); + tcp->connectToHost(card->m_strCardIp, 3333); + timer->start(10000); + } else { + foreach(auto card, *gSelCards) { + auto tcp = new QTcpSocket(); + auto timer = new QTimer(tcp); + timer->setSingleShot(true); + auto cardId = card->m_strCardId; + connect(timer, &QTimer::timeout, tcp, [tcp, cardId] { + tcp->abort(); + tcp->deleteLater(); + gFdResInfo->append(cardId+" "+tr("Clear Program")+" "+tr("Timeout")); + }); + connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { + timer->stop(); + tcp->write("{\"_type\":\"DelPrograms\",\"_id\":\"DelPrograms\",\"zVer\":\"xixun1\"}"); + timer->start(10000); + }); + connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, cardId] { + timer->stop(); + QByteArray resp = tcp->readAll(); + tcp->close(); + tcp->deleteLater(); + QJsonParseError parseErr; + QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); + if(parseErr.error != QJsonParseError::NoError) gFdResInfo->append(cardId+" "+tr("Clear Program")+" "+parseErr.errorString()); + else if(! json["success"].toBool()) gFdResInfo->append(cardId+" "+tr("Clear Program")+" "+tr("Failed")); + else gFdResInfo->append(cardId+" "+tr("Clear Program")+" "+tr("Success")); + }); + connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, cardId](QAbstractSocket::SocketError err) { + timer->stop(); + tcp->close(); + tcp->deleteLater(); + gFdResInfo->append(cardId+" "+tr("Clear Program")+" "+QMetaEnum::fromType().valueToKey(err)+" ("+QString::number(err)+") "+tcp->errorString()); + }); + tcp->connectToHost(card->m_strCardIp, 3333); + timer->start(10000); + } + } + }); + + hBox->addWidget(btnClearProg); + + btnGetLog = new QPushButton; + btnGetLog->setProperty("ssType", "progManageTool"); + connect(btnGetLog, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Getting Log")+" ..."); + waitingDlg->show(); + auto card = gSelCards->at(0); + auto reply = Tools::netManager().get(netReq("http://"+card->m_strCardIp+":2016/download?file=logs")); + connect(waitingDlg, &WaitingDlg::rejected, reply, [reply] { + reply->blockSignals(true); + reply->abort(); + reply->blockSignals(false); + reply->deleteLater(); + }); + connect(reply, &QNetworkReply::finished, this, [=] { + waitingDlg->close(); + QString err = checkReply(reply); + if(! err.isEmpty()) { + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + QString logFile = QApplication::applicationDirPath()+"/log_"+card->m_strCardId+".txt"; + QFile file(logFile); + if(! file.open(QIODevice::WriteOnly)) { + QMessageBox::critical(gMainWin, tr("Error"), "Open for Write Fail"); + return; + } + file.write(reply->readAll()); + file.close(); + QProcess::execute("notepad", {logFile}); + }); + } + }); + hBox->addWidget(btnGetLog); + + hBox->addStretch(); + hBox = new HBox(vBox); + hBox->addWidget(lbTimingReboot = new QLabel); + + auto fdRebootTime = new QLineEdit; + fdRebootTime->setMaximumWidth(60); + hBox->addWidget(fdRebootTime); + + btnTimingRebootSet = new QPushButton; + btnTimingRebootSet->setProperty("ssType", "progManageTool"); + connect(btnTimingRebootSet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetTimingReboot"); + json.insert("_type", "SetTimingReboot"); + json.insert("time", fdRebootTime->text()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Setting Timing Reboot")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set Timing Reboot")) + } + } + }); + hBox->addWidget(btnTimingRebootSet); + + btnTimingRebootGet = new QPushButton; + btnTimingRebootGet->setProperty("ssType", "progManageTool"); + connect(btnTimingRebootGet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetTimingReboot"); + json.insert("_type", "GetTimingReboot"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Getting Timing Reboot")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [=] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdRebootTime->setText(json["time"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["time"].toString(); + gFdResInfo->append(cardId+" "+tr("Get Timing Reboot")+" "+err); + }); + } + } + }); + hBox->addWidget(btnTimingRebootGet); + + hBox->addStretch(); + + grpM80 = new QGroupBox; + hBox = new HBox(grpM80); + + fdM80Resolu = new QComboBox; + fdM80Resolu->setMinimumWidth(160); + hBox->addWidget(fdM80Resolu); + + btnM80Set = new QPushButton(); + btnM80Set->setProperty("ssType", "progManageTool"); + connect(btnM80Set, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetSpecialResolution"); + json.insert("_type", "SetSpecialResolution"); + json.insert("displayResolution", fdM80Resolu->currentText()); //显示分辨率 + json.insert("totalResolution", fdM80Resolu->currentData().toString()); //显示分辨率 + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetSpecialResolution")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetSpecialResolution")) + } + } + }); + hBox->addWidget(btnM80Set); + + btnM80Refresh = new QPushButton(); + btnM80Refresh->setProperty("ssType", "progManageTool"); + connect(btnM80Refresh, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetSpecialResolution"); + json.insert("_type", "GetSpecialResolution"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetSpecialResolution")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdM80Resolu->setCurrentText(json["displayResolution"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = tr("totalResolution")+"["+json["totalResolution"].toString()+"], "+tr("strCurDisplayResolution")+"["+json["displayResolution"].toString()+"]"; + gFdResInfo->append(cardId+" "+tr("GetSpecialResolution")+" "+err); + }); + } + } + }); + hBox->addWidget(btnM80Refresh); + + btnM80Restore = new QPushButton(); + btnM80Restore->setProperty("ssType", "progManageTool"); + connect(btnM80Restore, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "CleanDisplayScreenSize"); + json.insert("_type", "CleanDisplayScreenSize"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("CleanDisplayScreenSize")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("CleanDisplayScreenSize")) + } + } + }); + hBox->addWidget(btnM80Restore); + + hBox->addStretch(); + + vBox->addWidget(grpM80); + + { + grpY50 = new QGroupBox; + hBox = new HBox(grpY50); + + auto fdY50Resolu = new QComboBox; + auto dirs = QDir(QApplication::applicationDirPath()+"/y50 param").entryList(QDir::Dirs | QDir::NoDotAndDotDot); + foreach(auto dir, dirs) fdY50Resolu->addItem(dir); + fdY50Resolu->setMinimumWidth(160); + hBox->addWidget(fdY50Resolu); + + btnY50Set = new QPushButton; + btnY50Set->setProperty("ssType", "progManageTool"); + connect(btnY50Set, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QFile qFile(QApplication::applicationDirPath()+"/y50 param/"+fdY50Resolu->currentText()+"/rk_lcd_parameters"); + if(! qFile.exists()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("File not exist")); + return; + } + if(! qFile.open(QIODevice::ReadOnly)) return; + auto fileData = qFile.readAll(); + qFile.close(); + + auto Boundary = "----QtLedOK_.oOo._"+QUuid::createUuid().toByteArray(QUuid::WithoutBraces); + QByteArray data; + data.append("--").append(Boundary).append("\r\nContent-Disposition: form-data; name=\"rk_lcd_parameters\"; filename=\"rk_lcd_parameters\"\r\n\r\n").append(fileData).append("\r\n"); + data.append("--").append(Boundary).append("--\r\n"); + + auto waitingDlg = new WaitingDlg(this, tr("Uploading")+" ..."); + waitingDlg->show(); + NetReq req("http://"+gSelCards->at(0)->m_strCardIp+":2016/upload?type=update_display"); + auto reply = req.timeout(120000).type("multipart/form-data; boundary="+Boundary).post(data); + connect(waitingDlg, &WaitingDlg::rejected, reply, [reply] { + reply->blockSignals(true); + reply->abort(); + reply->blockSignals(false); + reply->deleteLater(); + }); + connect(reply, &QNetworkReply::finished, this, [=] { + QString err = checkReply(reply); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + waitingDlg->success(); + }); + }); + hBox->addWidget(btnY50Set); + + hBox->addStretch(); + + vBox->addWidget(grpY50); + } + + hBox = new HBox(vBox); + + lbDisMode = new QLabel; + hBox->addWidget(lbDisMode); + + fdDisMode = new QComboBox; + fdDisMode->setSizeAdjustPolicy(QComboBox::AdjustToContents); + fdDisMode->addItem("Full screen", 1); + fdDisMode->addItem("Part", 2); + hBox->addWidget(fdDisMode); + + btnDisModeSet = new QPushButton; + btnDisModeSet->setProperty("ssType", "progManageTool"); + connect(btnDisModeSet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")+" ..."); + return; + } + QJsonObject json; + json.insert("_id", "SetDisplayModel"); + json.insert("_type", "SetDisplayModel"); + json.insert("model", fdDisMode->currentData().toInt()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Set Display Mode")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set Display Mode")) + } + } + }); + hBox->addWidget(btnDisModeSet); + + btnDisModeGet = new QPushButton; + btnDisModeGet->setProperty("ssType", "progManageTool"); + connect(btnDisModeGet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetDisplayModel"); + json.insert("_type", "GetDisplayModel"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Get Display Mode")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [=] { + Def_CtrlSingleGetReply + waitingDlg->success(); + setCurrentData(fdDisMode, json["result"].toInt()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + auto result = json["result"].toInt(); + int idx = fdDisMode->findData(result); + if(idx!=-1) err = fdDisMode->itemText(idx); + else err = QString::number(result); + } + gFdResInfo->append(cardId+" "+tr("Get Display Mode")+" "+err); + }); + } + } + }); + hBox->addWidget(btnDisModeGet); + hBox->addSpacing(40); + + lbScreenPos = new QLabel; + hBox->addWidget(lbScreenPos); + + auto fdScreenPos = new QSpinBox; + fdScreenPos->setRange(0, 99999); + hBox->addWidget(fdScreenPos); + + lbScreenOff = new QLabel; + hBox->addWidget(lbScreenOff); + + auto fdScreenOff = new QSpinBox; + fdScreenOff->setRange(-9999, 99999); + hBox->addWidget(fdScreenOff); + + btnScreenOffSet = new QPushButton; + btnScreenOffSet->setProperty("ssType", "progManageTool"); + connect(btnScreenOffSet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "ConfigScreen"); + json.insert("_type", "ConfigScreen"); + json.insert("index", fdScreenPos->value()); + json.insert("x", fdScreenOff->value()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Set Screen Offset")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set Screen Offset")) + } + } + }); + hBox->addWidget(btnScreenOffSet); + + btnScreenOffGet = new QPushButton; + btnScreenOffGet->setProperty("ssType", "progManageTool"); + connect(btnScreenOffGet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetConfigScreen"); + json.insert("_type", "GetConfigScreen"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Get Screen Offset")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [=] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdScreenPos->setValue(json["offsetNum"].toInt()); + fdScreenOff->setValue(json["offsetValue"].toInt()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + err = lbScreenPos->text()+" "+QString::number(json["offsetNum"].toInt())+". "+lbScreenOff->text()+" "+QString::number(json["offsetValue"].toInt()); + } + gFdResInfo->append(cardId+" "+tr("Get Screen Offset")+" "+err); + }); + } + } + }); + hBox->addWidget(btnScreenOffGet); + hBox->addStretch(); + + hBox = new HBox(vBox); + + btnLedSet3 = new QPushButton; + btnLedSet3->setMinimumHeight(34); + btnLedSet3->setProperty("ssType", "progManageTool"); + connect(btnLedSet3, &QPushButton::clicked, this, [this] { + QString strLedSetFile = QApplication::applicationDirPath()+"/LedSet/LedSet3.0.exe"; + QFileInfo cc22(strLedSetFile); + if(cc22.exists()) { + QProcess::startDetached(strLedSetFile,QStringList()); + return; + } + QSettings reg("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\sysolution\\LedSet3.0", QSettings::NativeFormat); + QString strLedsetPath = reg.value("Program_path").toString(); + if(!strLedsetPath.isEmpty()) { + QFileInfo cc(strLedsetPath); + if(cc.exists()) QProcess::startDetached(strLedsetPath,QStringList()); + else { + auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath); + if(res == QMessageBox::Yes) { + UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this); + pDlg->exec(); + } + } + return; + } + QSettings reg1("HKEY_LOCAL_MACHINE\\SOFTWARE\\sysolution\\LedSet3.0", QSettings::NativeFormat); + strLedsetPath = reg1.value("Program_path").toString(); + QFileInfo cc(strLedsetPath); + if(!strLedsetPath.isEmpty()) { + if(cc.exists()) QProcess::startDetached(strLedsetPath,QStringList()); + else { + QString str1="C:/Program Files/sysolution/LedSet3.0/LedSet3.0.exe"; + QFileInfo cc1(str1); + if(cc1.exists()) QProcess::startDetached(str1,QStringList()); + else { + QString str2="C:/Program Files (x86)/sysolution/LedSet3.0/LedSet3.0.exe"; + QFileInfo cc2(str1); + if(cc2.exists()) QProcess::startDetached(str2,QStringList()); + else { + auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath); + if(res == QMessageBox::Yes) { + UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this); + pDlg->exec(); + } + } + } + } + } else { + QString str1="C:/Program Files/sysolution/LedSet3.0/LedSet3.0.exe"; + QFileInfo cc1(str1); + if(cc1.exists()) QProcess::startDetached(str1,QStringList()); + else { + QString str2="C:/Program Files (x86)/sysolution/LedSet3.0/LedSet3.0.exe"; + QFileInfo cc2(str1); + if(cc2.exists())QProcess::startDetached(str2,QStringList()); + else { + auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath); + if(res == QMessageBox::Yes) { + UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this); + pDlg->exec(); + } + } + } + } + }); + hBox->addWidget(btnLedSet3); + + btnLedSet4 = new QPushButton; + btnLedSet4->setMinimumHeight(34); + btnLedSet4->setProperty("ssType", "progManageTool"); + connect(btnLedSet4, &QPushButton::clicked, btnLedSet4, [] { + QFileInfo file("LedSet4.0/LedSet4.0.exe"); + if(file.exists()) QProcess::startDetached(file.absoluteFilePath(), QStringList()); + }); + hBox->addWidget(btnLedSet4); + + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + hBox = new HBox(vBox); + btnBindTaxiIc = new QPushButton; + btnBindTaxiIc->setProperty("ssType", "progManageTool"); + connect(btnBindTaxiIc, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QString icFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("indentity voucher (*.ic)")); + if(icFile.isEmpty()) return; + QFile file(icFile); + if(! file.open(QIODevice::ReadOnly)) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Open file Failed")); + return; + } + auto data = file.readAll(); + file.close(); + QJsonParseError jsonErr; + QJsonDocument icJson = QJsonDocument::fromJson(data, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) { + QMessageBox::information(gMainWin, tr("Tip"), "JsonError "+jsonErr.errorString()+"\n"+data); + return; + } + QJsonObject jsonCommand; + jsonCommand.insert("action", "BindAccount"); + jsonCommand.insert("accountIdToken", icJson["account_id_token"]); + jsonCommand.insert("server", icJson["taxiServerURL"]); + jsonCommand.insert("tlsServer", icJson["taxiServerTLSURL"]); + QJsonObject json; + json.insert("action", "InvokeTaxiAppFunction"); + json.insert("jsonCommand", jsonCommand); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("InvokeTaxiAppFunction")); + waitingDlg->show(); + auto reply = Tools::netManager().post(reqForJson("http://"+gSelCards->at(0)->m_strCardIp+":3000"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(waitingDlg, &WaitingDlg::rejected, reply, [reply] { + reply->blockSignals(true); + reply->abort(); + reply->blockSignals(false); + reply->deleteLater(); + }); + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + QString err = checkReply(reply); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + auto data = reply->readAll(); + QJsonParseError jsonErr; + QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), "JsonError "+jsonErr.errorString()+"\n"+data); + return; + } + if(json["result"].toString() != "true") { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), data); + return; + } + waitingDlg->success(); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":3000"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QString err = checkReply(reply); + if(! err.isEmpty()) { + gFdResInfo->append(cardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" "+err); + return; + } + auto data = reply->readAll(); + QJsonParseError jsonErr; + QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) { + gFdResInfo->append(cardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" JsonError "+jsonErr.errorString()+"\n"+data); + return; + } + if(json["result"].toString() != "true") { + gFdResInfo->append(cardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" "+data); + return; + } + gFdResInfo->append(cardId+" "+tr("InvokeTaxiAppFunction")+" "+QCoreApplication::translate("Def","Success")); + }); + } + } + }); + hBox->addWidget(btnBindTaxiIc); + hBox->addStretch(); + + + grpHighForBusy = new QGroupBox; + grpHighForBusy->setVisible(false); + hBox = new HBox(grpHighForBusy); + + fdHighForBusy = new QRadioButton; + fdHighForBusy->setChecked(true); + hBox->addWidget(fdHighForBusy); + + fdTopLevelLH = new QRadioButton; + hBox->addWidget(fdTopLevelLH); + + btnHighForBusySet = new QPushButton; + btnHighForBusySet->setProperty("ssType", "progManageTool"); + connect(btnHighForBusySet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetHighForBusy"); + json.insert("_type", "SetHighForBusy"); + json.insert("busyState", fdTopLevelLH->isChecked() ? 0 : 1); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetHighForBusy")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetHighForBusy")) + } + } + }); + hBox->addWidget(btnHighForBusySet); + + btnGetTopLevel = new QPushButton; + btnGetTopLevel->setProperty("ssType", "progManageTool"); + connect(btnGetTopLevel, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetStateForBusy"); + json.insert("_type", "GetStateForBusy"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetStateForBusy")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + if(json["result"].toInt()==0) fdTopLevelLH->setChecked(true); + else fdHighForBusy->setChecked(true); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["result"].toInt() ? tr("Service:High Out of service:Low") : tr("Service:Low Out of service:High"); + gFdResInfo->append(cardId+" "+tr("GetStateForBusy")+" "+err); + }); + } + } + }); + hBox->addWidget(btnGetTopLevel); + + hBox->addStretch(); + + vBox->addWidget(grpHighForBusy); + + grpMinMaxBrightness = new QGroupBox(); + grpMinMaxBrightness->setVisible(false); + hBox = new HBox(grpMinMaxBrightness); + + lbMinBright = new QLabel(); + hBox->addWidget(lbMinBright); + + fdMinBright = new QLineEdit("1"); + fdMinBright->setPlaceholderText("1"); + fdMinBright->setMaximumWidth(50); + hBox->addWidget(fdMinBright); + hBox->addWidget(new QLabel("%")); + + btnMinBrightSet = new QPushButton; + btnMinBrightSet->setProperty("ssType", "progManageTool"); + connect(btnMinBrightSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetMinBrightness"); + json.insert("_type", "SetMinBrightness"); + json.insert("minBrightnessPercentage", fdMinBright->text().toInt()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetMinBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetMinBrightness")) + } + } + }); + hBox->addWidget(btnMinBrightSet); + + btnMinBrightGet = new QPushButton(); + btnMinBrightGet->setProperty("ssType", "progManageTool"); + connect(btnMinBrightGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetMinBrightness"); + json.insert("_type", "GetMinBrightness"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetMinBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdMinBright->setText(QString::number(json["minBrightnessPercentage"].toInt())); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = QString::number(json["minBrightnessPercentage"].toInt()); + gFdResInfo->append(cardId+" "+tr("GetMinBrightness")+" "+err); + }); + } + } + }); + hBox->addWidget(btnMinBrightGet); + + hBox->addSpacing(10); + + label_3 = new QLabel(); + hBox->addWidget(label_3); + + fdMaxBright = new QLineEdit("100"); + fdMaxBright->setPlaceholderText("100"); + fdMaxBright->setMaximumWidth(50); + hBox->addWidget(fdMaxBright); + hBox->addWidget(new QLabel("%")); + + btnMaxBrightSet = new QPushButton; + btnMaxBrightSet->setProperty("ssType", "progManageTool"); + connect(btnMaxBrightSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetMaxBrightness"); + json.insert("_type", "SetMaxBrightness"); + json.insert("maxBrightnessPercentage", fdMaxBright->text().toInt()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetMaxBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetMaxBrightness")) + } + } + }); + hBox->addWidget(btnMaxBrightSet); + + btnMaxBrightGet = new QPushButton; + btnMaxBrightGet->setProperty("ssType", "progManageTool"); + connect(btnMaxBrightGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetMaxBrightness"); + json.insert("_type", "GetMaxBrightness"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetMaxBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdMaxBright->setText(QString::number(json["maxBrightnessPercentage"].toInt())); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = QString::number(json["maxBrightnessPercentage"].toInt()); + gFdResInfo->append(cardId+" "+tr("GetMaxBrightness")+" "+err); + }); + } + } + }); + hBox->addWidget(btnMaxBrightGet); + + hBox->addStretch(); + vBox->addWidget(grpMinMaxBrightness); + + vBox->addSpacing(20); + + grpBoxHiddenSettings = new QGroupBox; + grpBoxHiddenSettings->setVisible(false); + { + auto vBox = new QVBoxLayout(grpBoxHiddenSettings); + vBox->setContentsMargins(6,6,6,6); + + hBox = new HBox(vBox); + + btnSetBack = new QPushButton; + btnSetBack->setProperty("ssType", "progManageTool"); + connect(btnSetBack, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QColorDialog colorDlg(this); + colorDlg.setOption(QColorDialog::DontUseNativeDialog); + + if(colorDlg.exec() != QColorDialog::Accepted) return; + QColor color = colorDlg.selectedColor(); + if(! color.isValid()) return; + QJsonObject json; + json.insert("_id", "SetWallpaper"); + json.insert("_type", "SetWallpaper"); + json.insert("rgb", color.name()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Setting Wallpaper")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set Wallpaper")) + } + } + }); + hBox->addWidget(btnSetBack); + + btnSysUpd = new QPushButton; + btnSysUpd->setProperty("ssType", "progManageTool"); + connect(btnSysUpd, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SystemUpdate"); + json.insert("_type", "SystemUpdate"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("System Updating")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("System Update")) + } + } + }); + hBox->addWidget(btnSysUpd); + + hBox->addSpacing(20); + + btnMcuUpd = new QPushButton; + btnMcuUpd->setProperty("ssType", "progManageTool"); + connect(btnMcuUpd, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto filePath = QFileDialog::getOpenFileName(this, "Open File", QString(), ".bin file (*.bin)"); + if(filePath.isEmpty()) return; + QFile qFile(filePath); + if(! qFile.exists()) return; + if(! qFile.open(QIODevice::ReadOnly)) return; + auto fileData = qFile.readAll(); + qFile.close(); + + auto nameBytes = QFileInfo(filePath).fileName().toUtf8(); + auto Boundary = "----QtLedOK_.oOo._"+QUuid::createUuid().toByteArray(QUuid::WithoutBraces); + QByteArray data; + data.append("--").append(Boundary).append("\r\nContent-Disposition: form-data; name=\"").append(nameBytes).append("\"; filename=\"").append(nameBytes).append("\"\r\n\r\n").append(fileData).append("\r\n"); + data.append("--").append(Boundary).append("--\r\n"); + + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("MCU Uploading")+" ..."); + waitingDlg->show(); + NetReq req("http://"+gSelCards->at(0)->m_strCardIp+":2016/upload?type=mcu_update"); + auto reply = req.timeout(120000).type("multipart/form-data; boundary="+Boundary).post(data); + connect(waitingDlg, &WaitingDlg::rejected, reply, [reply] { + reply->blockSignals(true); + reply->abort(); + reply->blockSignals(false); + reply->deleteLater(); + }); + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + QString err = checkReply(reply); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + waitingDlg->success(); + }); + } else { + foreach(auto card, *gSelCards) { + auto cardId = card->m_strCardId; + NetReq req("http://"+card->m_strCardIp+":2016/upload?type=mcu_update"); + auto reply = req.timeout(120000).type("multipart/form-data; boundary="+Boundary).post(data); + connect(reply, &QNetworkReply::finished, this, [=] { + QString err = checkReply(reply); + gFdResInfo->append(cardId+" "+tr("Update MCU")+" "+(err.isEmpty()?tr("Success"):err)); + }); + } + } + }); + hBox->addWidget(btnMcuUpd); + + btnMcuGet = new QPushButton; + btnMcuGet->setProperty("ssType", "progManageTool"); + connect(btnMcuGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SelectMCUVersion"); + json.insert("_type", "SelectMCUVersion"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Getting MCU Version")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->close(); + QMessageBox::information(gMainWin, tr("Tip"), tr("MCU Version")+": "+json["mcuVersion"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["mcuVersion"].toString(); + gFdResInfo->append(cardId+" "+tr("MCU Version")+" "+err); + }); + } + } + }); + hBox->addWidget(btnMcuGet); + + hBox->addSpacing(20); + + btnPlayerBackSet = new QPushButton; + btnPlayerBackSet->setProperty("ssType", "progManageTool"); + connect(btnPlayerBackSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QString file = QFileDialog::getOpenFileName(gMainWin, tr("Select File"), gFileHome, EPhoto::filters()); + if(file.isEmpty()) return; + QFileInfo info(file); + if(! info.isFile()) return; + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Setting player background")+" ..."); + waitingDlg->btnAbort->hide(); + waitingDlg->show(); + auto thread = new PlayerBackSendThread(file, gSelCards->at(0)->m_strCardIp); + connect(thread, &PlayerBackSendThread::emErr, this, [waitingDlg](QString err) { + if(err.isEmpty()) waitingDlg->success(); + else { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + } + }); + thread->start(); + } else { + foreach(auto card, *gSelCards) { + auto thread = new PlayerBackSendThread(file, card->m_strCardIp); + auto cardId = card->m_strCardId; + connect(thread, &PlayerBackSendThread::emErr, this, [cardId](QString err) { + gFdResInfo->append(cardId+" "+tr("Set player background")+" "+(err.isEmpty() ? tr("Success") : err)); + }); + thread->start(); + } + } + }); + hBox->addWidget(btnPlayerBackSet); + + btnPlayerBackClear = new QPushButton; + btnPlayerBackClear->setProperty("ssType", "progManageTool"); + connect(btnPlayerBackClear, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Clearing player background")+" ..."); + waitingDlg->show(); + auto card = gSelCards->at(0); + auto tcp = new QTcpSocket(); + auto timer = new QTimer(tcp); + timer->setSingleShot(true); + connect(timer, &QTimer::timeout, tcp, [tcp, waitingDlg] { + waitingDlg->close(); + tcp->abort(); + tcp->deleteLater(); + QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear player background")+" "+tr("Timeout")); + }); + connect(waitingDlg, &WaitingDlg::rejected, tcp, [=] { + timer->stop(); + tcp->abort(); + tcp->deleteLater(); + }); + connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { + timer->stop(); + tcp->write("{\"_type\":\"DelBackImg\",\"_id\":\"DelBackImg\",\"zVer\":\"xixun1\"}"); + timer->start(10000); + }); + connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, waitingDlg] { + timer->stop(); + QByteArray resp = tcp->readAll(); + tcp->close(); + tcp->deleteLater(); + QJsonParseError parseErr; + QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); + if(parseErr.error != QJsonParseError::NoError) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), parseErr.errorString()); + } else if(! json["success"].toBool()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear player background")+" "+tr("Failed")); + } else waitingDlg->success(); + }); + connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, waitingDlg](QAbstractSocket::SocketError err) { + timer->stop(); + tcp->close(); + tcp->deleteLater(); + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), QString(socketErrKey(err))+" ("+QString::number(err)+") "+tcp->errorString()); + }); + tcp->connectToHost(card->m_strCardIp, 3333); + timer->start(10000); + } else { + foreach(auto card, *gSelCards) { + auto tcp = new QTcpSocket(); + auto timer = new QTimer(tcp); + timer->setSingleShot(true); + auto cardId = card->m_strCardId; + connect(timer, &QTimer::timeout, tcp, [tcp, cardId] { + tcp->abort(); + tcp->deleteLater(); + gFdResInfo->append(cardId+" "+tr("Clear player background")+" "+tr("Timeout")); + }); + connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { + timer->stop(); + tcp->write("{\"_type\":\"DelBackImg\",\"_id\":\"DelBackImg\",\"zVer\":\"xixun1\"}"); + timer->start(10000); + }); + connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, cardId] { + timer->stop(); + QByteArray resp = tcp->readAll(); + tcp->close(); + tcp->deleteLater(); + QJsonParseError parseErr; + QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); + if(parseErr.error != QJsonParseError::NoError) gFdResInfo->append(cardId+" "+tr("Clear player background")+" "+parseErr.errorString()); + else if(! json["success"].toBool()) gFdResInfo->append(cardId+" "+tr("Clear player background")+" "+tr("Failed")); + else gFdResInfo->append(cardId+" "+tr("Clear player background")+" "+tr("Success")); + }); + connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, cardId](QAbstractSocket::SocketError err) { + timer->stop(); + tcp->close(); + tcp->deleteLater(); + gFdResInfo->append(cardId+" "+tr("Clear player background")+" "+QMetaEnum::fromType().valueToKey(err)+" ("+QString::number(err)+") "+tcp->errorString()); + }); + tcp->connectToHost(card->m_strCardIp, 3333); + timer->start(10000); + } + } + }); + hBox->addWidget(btnPlayerBackClear); + + hBox->addStretch(); + + auto line = new QFrame; + line->setFrameStyle(QFrame::HLine | QFrame::Sunken); + vBox->addWidget(line); + + hBox = new HBox(vBox); + + lbRotate = new QLabel; + hBox->addWidget(lbRotate); + hBox->addSpacing(20); + + auto fdDeg0 = new QRadioButton("0°"); + hBox->addWidget(fdDeg0); + auto fdDeg90 = new QRadioButton("90°"); + hBox->addWidget(fdDeg90); + auto fdDeg180 = new QRadioButton("180°"); + hBox->addWidget(fdDeg180); + auto fdDeg270 = new QRadioButton("270°"); + hBox->addWidget(fdDeg270); + + hBox->addStretch(); + + auto btnGrp = new QButtonGroup; + btnGrp->addButton(fdDeg0, 0); + btnGrp->addButton(fdDeg90, 1); + btnGrp->addButton(fdDeg180, 2); + btnGrp->addButton(fdDeg270, 3); + connect(btnGrp, &QButtonGroup::idToggled, this, [this](int value, bool checked) { + if(! checked) return; + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetScreenRotation"); + json.insert("_type", "SetScreenRotation"); + json.insert("rotation", value); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetScreenRotation")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetScreenRotation")) + } + } + }); + + hBox = new HBox(vBox); + + lbBaudCfg = new QLabel; + hBox->addWidget(lbBaudCfg); + + line = new QFrame; + line->setFrameStyle(QFrame::HLine | QFrame::Sunken); + hBox->addWidget(line, 1); + + hBox = new HBox(vBox); + + lbBaudModel = new QLabel; + hBox->addWidget(lbBaudModel); + + auto fdBaudDevMod = new QComboBox; + fdBaudDevMod->addItems({ + "M5x/M6x", + "M7x/Y7x", + "E2x/Y6x", + "L20" + }); + hBox->addWidget(fdBaudDevMod); + + lbUart = new QLabel; + hBox->addWidget(lbUart); + + auto fdUart = new QComboBox; + fdUart->setEditable(true); + fdUart->setMinimumWidth(140); + fdUart->setSizeAdjustPolicy(QComboBox::AdjustToContents); + fdUart->addItems({ + "/dev/ttyS3", + "/dev/ttyS4", + "/dev/ttyS5" + }); + hBox->addWidget(fdUart); + + connect(fdBaudDevMod, &QComboBox::currentTextChanged, fdUart, [fdUart](const QString &text) { + fdUart->clear(); + if(text.startsWith("M5x")) fdUart->addItems({ + "/dev/ttyS3", + "/dev/ttyS4", + "/dev/ttyS5" + }); + else if(text.startsWith("M7x")) fdUart->addItem("/dev/ttyS4"); + else if(text.startsWith("E2x")) fdUart->addItems({ + "/dev/ttysWK0", + "/dev/ttysWK1", + "/dev/ttysWK2", + "/dev/ttysWK3", + "/dev/tty232", + "/dev/tty485", + "/dev/ttyTTL" + }); + else if(text.startsWith("L20")) fdUart->addItems({ + "/dev/ttyS0", + "/dev/ttyS1", + "/dev/ttyS4" + }); + }); + + lbBaud = new QLabel; + hBox->addWidget(lbBaud); + + auto fdBaud = new QLineEdit; + fdBaud->setMaximumWidth(70); + hBox->addWidget(fdBaud); + + btnBaudSet = new QPushButton; + btnBaudSet->setProperty("ssType", "progManageTool"); + connect(btnBaudSet, &QPushButton::clicked, this, [this, fdUart, fdBaud] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetBaudRateByCardType"); + json.insert("_type", "SetBaudRateByCardType"); + json.insert("uartName", fdUart->currentText()); + json.insert("baud", fdBaud->text().toInt()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Setting Baud Rate")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set Baud Rate")) + } + } + }); + hBox->addWidget(btnBaudSet); + + btnBaudGet = new QPushButton; + btnBaudGet->setProperty("ssType", "progManageTool"); + connect(btnBaudGet, &QPushButton::clicked, this, [this, fdUart, fdBaud] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetBaudRateByCardType"); + json.insert("_type", "GetBaudRateByCardType"); + json.insert("uartName", fdUart->currentText()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Getting Baud Rate")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, fdBaud, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdBaud->setText(QString::number(json["baud"].toInt())); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + gFdResInfo->append(cardId+" "+tr("Get Baud Rate")+" "+(err.isEmpty()?QString::number(json["baud"].toInt()):err)); + }); + } + } + }); + hBox->addWidget(btnBaudGet); + + hBox->addStretch(); + + + fdIsOpenADB = new QCheckBox; + connect(fdIsOpenADB, &QCheckBox::toggled, this, [this](bool checked) { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "OpenAdb"); + json.insert("_type", "OpenAdb"); + json.insert("open", checked); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("OpenAdb")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("OpenAdb")) + } + } + }); + vBox->addWidget(fdIsOpenADB); + + hBox = new HBox(vBox); + + lbCustomJson = new QLabel; + hBox->addWidget(lbCustomJson); + + hBox->addSpacing(40); + + btnSendCustomJson = new QPushButton; + btnSendCustomJson->setProperty("ssType", "progManageTool"); + connect(btnSendCustomJson, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto text = fdCustomJson->toPlainText().toUtf8(); + if(text.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Text is empty")); + return; + } + QJsonParseError jsonErr; + QJsonDocument json = QJsonDocument::fromJson(text, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Json Parse Error")+jsonErr.errorString()); + return; + } + if(! json.isObject()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Json isn't an Object")); + return; + } + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("AliIotSetting")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("AliIotSetting")) + } + } + }); + hBox->addWidget(btnSendCustomJson); + + hBox->addStretch(); + + fdCustomJson = new QTextEdit; + fdCustomJson->setMinimumHeight(120); + vBox->addWidget(fdCustomJson); + + + vBox->addWidget(new QLabel(tr("Traffic screen settings"))); + + hBox = new HBox(vBox); + + lbTraficProtocol = new QLabel; + lbTraficProtocol->setMinimumWidth(100); + hBox->addWidget(lbTraficProtocol); + + auto fdTraficProtocol = new QComboBox; + fdTraficProtocol->addItem("三思协议", 1); + hBox->addWidget(fdTraficProtocol); + + btnTraficProtSet = new QPushButton; + btnTraficProtSet->setProperty("ssType", "progManageTool"); + connect(btnTraficProtSet, &QPushButton::clicked, this, [this, fdTraficProtocol] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetProtocolType"); + json.insert("_type", "SetProtocolType"); + json.insert("protocolType", fdTraficProtocol->currentData().toInt()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Setting protocol ...")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set protocol")) + } + } + }); + hBox->addWidget(btnTraficProtSet); + + btnTraficProtGet = new QPushButton; + btnTraficProtGet->setProperty("ssType", "progManageTool"); + connect(btnTraficProtGet, &QPushButton::clicked, this, [this, fdTraficProtocol] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetProtocolType"); + json.insert("_type", "GetProtocolType"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Getting protocol ...")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg, fdTraficProtocol] { + Def_CtrlSingleGetReply + waitingDlg->success(); + setCurrentData(fdTraficProtocol, json["protocolType"].toInt()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId, fdTraficProtocol] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + auto protocolType = json["protocolType"].toInt(); + int idx = fdTraficProtocol->findData(protocolType); + if(idx!=-1) err = fdTraficProtocol->itemText(idx); + else err = QString::number(protocolType); + } + gFdResInfo->append(cardId+" "+tr("Get protocol")+" "+err); + }); + } + } + }); + hBox->addWidget(btnTraficProtGet); + hBox->addStretch(); + + hBox = new HBox(vBox); + + lbCardMode = new QLabel; + lbCardMode->setMinimumWidth(100); + hBox->addWidget(lbCardMode); + + fdServerType = new QComboBox; + fdServerType->setSizeAdjustPolicy(QComboBox::AdjustToContents); + fdServerType->addItem("服务端", 1); + fdServerType->addItem("客户端", 2); + hBox->addWidget(fdServerType); + + hBox->addSpacing(10); + + lbTraficPort = new QLabel; + hBox->addWidget(lbTraficPort); + + auto fdPort = new QSpinBox; + fdPort->setRange(0, 99999); + fdPort->setValue(5000); + hBox->addWidget(fdPort); + + btnTraficSet = new QPushButton; + btnTraficSet->setProperty("ssType", "progManageTool"); + connect(btnTraficSet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetCardMode"); + json.insert("_type", "SetCardMode"); + json.insert("serverType", fdServerType->currentData().toInt()); + json.insert("port", fdPort->value()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Setting card work mode ...")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("Set card work mode")) + } + } + }); + hBox->addWidget(btnTraficSet); + + btnTraficGet = new QPushButton; + btnTraficGet->setProperty("ssType", "progManageTool"); + connect(btnTraficGet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetCardMode"); + json.insert("_type", "GetCardMode"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("Getting card work mode ...")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [=] { + Def_CtrlSingleGetReply + waitingDlg->success(); + setCurrentData(fdServerType, json["serverType"].toInt()); + fdPort->setValue(json["port"].toInt()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + err = tr("Card work mode")+": "; + auto serverType = json["serverType"].toInt(); + int idx = fdServerType->findData(serverType); + if(idx!=-1) err += fdServerType->itemText(idx); + else err += QString::number(serverType); + err += ". "+tr("Port")+": "+QString::number(json["port"].toInt()); + } + gFdResInfo->append(cardId+" "+tr("Get card work mode")+" "+err); + }); + } + } + }); + hBox->addWidget(btnTraficGet); + hBox->addStretch(); + } + vBox->addWidget(grpBoxHiddenSettings); + vBox->addStretch(); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void CtrlAdvancedPanel::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void CtrlAdvancedPanel::init() { + if(! isPassed) { + hide(); + PasswordInChDlg dlg(gMainWin); + connect(dlg.btnBox, &QDialogButtonBox::accepted, &dlg, [&dlg]() { + QString passRaw = QSettings().value("advUiPs").toString(); + QString password = passRaw.isEmpty() ? "888" : QTextCodec::codecForName("GBK")->toUnicode(QByteArray::fromBase64(passRaw.toLocal8Bit())); + if(dlg.fdPassword->text() == password) dlg.accept(); + else QMessageBox::critical(&dlg, tr("Tip"),tr("Password is error")); + }); + if(dlg.exec()==QDialog::Accepted) { + isPassed = true; + show(); + } else return; + } + + bool isSingle = gSelCards->count()==1; + btnApkCheck->setEnabled(isSingle); + btnRestart->setEnabled(isSingle); + btnGetLog->setEnabled(isSingle); + + if(! isSingle) { + grpM80->setVisible(true); + grpY50->setVisible(true); + return; + } + auto card = gSelCards->at(0); + + auto isM80 = card->m_strCardId.startsWith("M8", Qt::CaseInsensitive); + grpM80->setVisible(isM80); + if(isM80) { + QJsonObject json; + json.insert("_id", "GetAllScreenSizeM80"); + json.insert("_type", "GetAllScreenSizeM80"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + auto sizes = json["result"].toObject(); + fdM80Resolu->clear(); + auto send = sizes.constEnd(); + for(auto size=sizes.constBegin(); sizeaddItem(size.key(), size.value().toString()); + }); + } + + auto isY50 = card->m_strCardId.startsWith("st5", Qt::CaseInsensitive) + || card->m_strCardId.startsWith("m5s", Qt::CaseInsensitive) + || card->m_strCardId.startsWith("m6s", Qt::CaseInsensitive) + || card->m_strCardId.startsWith("m7s", Qt::CaseInsensitive) + || card->m_strCardId.startsWith("y5", Qt::CaseInsensitive); + grpY50->setVisible(isY50); + + QJsonObject json; + json.insert("_id", "GetScreenSize"); + json.insert("_type", "GetScreenSize"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdScreenWidth->setText(QString::number(json["width"].toInt())); + fdScreenHeight->setText(QString::number(json["height"].toInt())); + }); + + json = QJsonObject(); + json.insert("_id", "GetCardAlias"); + json.insert("_type", "GetCardAlias"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdAlias->setText(QString::fromUtf8(QByteArray::fromBase64(json["alias"].toString().toLatin1()))); + }); + + json = QJsonObject(); + json.insert("_id", "GetOnlineAddr"); + json.insert("_type", "GetOnlineAddr"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdWebServerAddr->setCurrentText(json["server"].toString()); + fdCompanyId->setText(json["companuID"].toString()); + }); + + json = QJsonObject(); + json.insert("_id", "GetRealtimeServer"); + json.insert("_type", "GetRealtimeServer"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdRealtimeServer->setCurrentText(json["server"].toString()); + }); +} +void CtrlAdvancedPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void CtrlAdvancedPanel::transUi() { + btnBindTaxiIc->setText(tr("Binding *.ic account indentity voucher")); + btnGetTopLevel->setText(tr("Readback")); + btnLedSet3->setText(tr("Start LedSet3.0 configure LED module")); + btnLedSet4->setText(tr("Start LedSet4")); + + grpM80->setTitle("M80 "+tr("Config")); + btnM80Refresh->setText(tr("Refresh")); + btnM80Restore->setText(tr("Restore to default")); + btnM80Set->setText(tr("Set")); + + grpY50->setTitle("ST50 / M50S / M60S / M70S / Y5A "+tr("Resolution Config")); + fdDisMode->setItemText(0, tr("Full screen")); + fdDisMode->setItemText(1, tr("Part")); + btnY50Set->setText(tr("Set")); + + lbDisMode->setText(tr("Display Mode")); + btnDisModeSet->setText(tr("Set")); + btnDisModeGet->setText(tr("Get")); + + lbScreenPos->setText(tr("Screen Position")); + lbScreenOff->setText(tr("Offset")); + btnScreenOffSet->setText(tr("Set")); + btnScreenOffGet->setText(tr("Get")); + + btnAliasSet->setText(tr("Set")); + btnScreenSet->setText(tr("Set")); + btnHighForBusySet->setText(tr("Set")); + fdScreenHeight->setPlaceholderText(tr("Height")); + fdScreenWidth->setPlaceholderText(tr("Width")); + fdHighForBusy->setText(tr("Service:High Out of service:Low")); + fdTopLevelLH->setText(tr("Service:Low Out of service:High")); + lbRotate->setText(tr("Rotate")); + + grpBoxHiddenSettings->setTitle(tr("Hidden Settings")+" ("+tr("Click right button to hide")+")"); + btnSysUpd->setText(tr("System Update")); + btnMcuUpd->setText(tr("Update MCU")); + btnMcuGet->setText(tr("Get MCU Version")); + lbBaudCfg->setText(tr("Baud Config")); + lbBaudModel->setText(tr("Model")); + lbUart->setText(tr("Uart")); + lbBaud->setText(tr("Baud")); + btnBaudSet->setText(tr("Set")); + btnBaudGet->setText(tr("Get")); + fdIsOpenADB->setText(tr("Open ADB")); + lbCustomJson->setText(tr("Post Custom JSON")); + btnSendCustomJson->setText(tr("Send")); + + grpHighForBusy->setTitle(tr("Taxi top screen configuration")); + label->setText(tr("Realtimer Server Address:")); + lbTitle->setText(tr("Advanced")); + lbCompanyId->setText(tr("Compant ID:")); + labelWebServer->setText(tr("Web Server Address:")); + lbMinBright->setText(tr("Min brightness")); + label_3->setText(tr("Max brightness ")); + lbAlias->setText(tr("Alias")); + lbScreenHeight->setText(tr("Height")); + lbScreenWidth->setText(tr("Screen Width(pixel)")); + fdCompanyId->setPlaceholderText(tr("Compant ID")); + + btnWareUpdate->setText(tr("Firmware Management")); + lbWareTip->setText("(APK / FPGA "+tr("update or uninstall")+")"); + btnApkCheck->setText(tr("Check Apk")); + btnGetLog->setText(tr("Check Log")); + btnSetBack->setText(tr("Set Wallpaper")); + btnClearProg->setText(tr("Clear Program")); + btnPlayerBackSet->setText(tr("Set player background")); + btnPlayerBackClear->setText(tr("Clear player background")); + + btnRealtimeClear->setText(tr("Clear")); + btnMinBrightSet->setText(tr("Set")); + btnMinBrightGet->setText(tr("Readback")); + btnMaxBrightSet->setText(tr("Set")); + btnMaxBrightGet->setText(tr("Readback")); + btnRestart->setText(tr("Restart")); + btnIsRunning->setText(tr("Running check")); + btnRealtimeServerSet->setText(tr("Set")); + btnWebServerSet->setText(tr("Set")); + fdUninstall->setText(tr("Uninstall")); + + lbTimingReboot->setText(tr("Timing Reboot")); + btnTimingRebootSet->setText(tr("Set")); + btnTimingRebootGet->setText(tr("Get")); + + lbTraficProtocol->setText(tr("Protocol")); + lbCardMode->setText(tr("Card work mode")); + fdServerType->setItemText(0, tr("Server")); + fdServerType->setItemText(1, tr("Client")); + lbTraficPort->setText(tr("Port")); + btnTraficProtSet->setText(tr("Set")); + btnTraficProtGet->setText(tr("Get")); + btnTraficSet->setText(tr("Set")); + btnTraficGet->setText(tr("Get")); +} + +//void CtrlAdvancedPanel::onUpload(QString file) { +// if(file.length() < 3) return; +// QFile qFile(file); +// if(! qFile.exists()) return; +// bool isApk = ! file.endsWith(".rpd", Qt::CaseInsensitive); +// auto BOUNDARY = QUuid::createUuid().toByteArray(); +// QByteArray data; +// data.append("--").append(BOUNDARY).append("\r\n"); +// data.append("Content-Disposition: form-data;name=\"username\"\r\n\r\n"); +// data.append("10005\r\n"); +// //上传文件的头部 +// data.append("--").append(BOUNDARY).append("\r\n"); +// QFileInfo fileinfo(file); +// auto name = fileinfo.fileName().toUtf8(); +// data.append("Content-Disposition: form-data;name=\"").append(name).append("\";filename=\"").append(name).append("\"\r\n\r\n"); +// //上传文件内容 +// if(! qFile.open(QIODevice::ReadOnly)) return; +// data.append(qFile.readAll()); +// qFile.close(); +// data.append("\r\n"); +// data.append("--").append(BOUNDARY).append("\r\n"); + +// auto waitingDlg = new WaitingDlg(this, tr("Uploading")+" ..."); +// waitingDlg->show(); +// auto request = netReq("http://"+gSelCards->at(0)->m_strCardIp+":2016/upload?type="+(isApk ? "software":"hardware"), "multipart/form-data;boundary="+BOUNDARY, 0); +// auto reply = Tools::netManager().post(request, data); +// connect(waitingDlg, &WaitingDlg::rejected, reply, [reply] { +// reply->blockSignals(true); +// reply->abort(); +// reply->blockSignals(false); +// reply->deleteLater(); +// }); +// connect(reply, &QNetworkReply::uploadProgress, this, [=](qint64 bytesSent, qint64 bytesTotal) { +// if(bytesTotal<=0) return; +// waitingDlg->fdText->setText(tr("Uploading")+" "+QString::number(bytesSent*100/bytesTotal)+"%"); +// }); +// connect(reply, &QNetworkReply::finished, this, [=] { +// QString err = checkReply(reply); +// if(! err.isEmpty()) { +// waitingDlg->close(); +// QMessageBox::critical(gMainWin, tr("Error"), err); +// return; +// } +// waitingDlg->fdText->setText(tr("Installing")+" ..."); +// QJsonObject json; +// if(isApk) { +// json.insert("_id", "UpgradeSoftware"); +// json.insert("_type", "UpgradeSoftware"); +// json.insert("fileName", QFileInfo(file).fileName()); +// json.insert("isCustom", true); +// } else { +// json.insert("_id", "SynchronousHardwareVersion"); +// json.insert("_type", "SynchronousHardwareVersion"); +// } +// auto reply = Tools::netManager().post(reqForJson("http://"+gSelCards->at(0)->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); +// connect(reply, &QNetworkReply::finished, this, [=] { +// Def_CtrlSetReqAfter +// }); +// }); +//} +void messageHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) { + auto cur = QDateTime::currentDateTime(); + QFile file("D:/LedOK-advanced-"+cur.toString("yy-MM-dd")+".log"); + file.open(QIODevice::WriteOnly | QIODevice::Append); + file.write(cur.toString("yy-MM-dd hh:mm:ss ").toUtf8()); + if(type==QtDebugMsg) file.write(" Debug: "); + else if(type==QtWarningMsg) file.write(" Warning: "); + else if(type==QtCriticalMsg)file.write("Critical: "); + else if(type==QtFatalMsg) file.write(" Fatal: "); + else if(type==QtInfoMsg) file.write(" Info: "); + else if(type==QtSystemMsg) file.write(" System: "); + file.write(msg.toUtf8()); + file.close(); +} +void CtrlAdvancedPanel::keyReleaseEvent(QKeyEvent *event) { + auto key = event->key(); + if(key == Qt::Key_F5) grpBoxHiddenSettings->setVisible(! grpBoxHiddenSettings->isVisible()); + else if(key == Qt::Key_F6) grpMinMaxBrightness->setVisible(! grpMinMaxBrightness->isVisible()); + else if(key == Qt::Key_F8) grpHighForBusy->setVisible(! grpHighForBusy->isVisible()); + else if(key == Qt::Key_F12) qInstallMessageHandler(messageHandler); + QWidget::keyPressEvent(event); +} +void CtrlAdvancedPanel::mouseReleaseEvent(QMouseEvent *event){ + if(event->button()==Qt::RightButton) grpBoxHiddenSettings->setVisible(! grpBoxHiddenSettings->isVisible()); +} + + +PlayerBackSendThread::PlayerBackSendThread(const QString &file, const QString &ip) : file(file), ip(ip) { + connect(this, &QThread::finished, this, &QThread::deleteLater); +} +void PlayerBackSendThread::run() { + TcpSocket tcp; + tcp.connectToHost(ip, 3333); + if(! tcp.waitForConnected()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForConnected"); + tcp.close(); + return; + } + QFileInfo info(file); + auto baseName = info.baseName(); + auto remain = info.size(); + + auto req = QJsonObject(); + req.insert("_type", "proStart"); + req.insert("proName", "program"); + req.insert("proSize", remain); + req.insert("zVer","xixun1"); + auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proStart'"); + tcp.close(); + return; + } + req = QJsonObject(); + req.insert("_type", "imgFileStart"); + req.insert("id", baseName); + req.insert("size", remain); + req.insert("zVer","xixun1"); + resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'imgFileStart'"); + tcp.close(); + return; + } + auto file = new QFile(info.filePath()); + if(! file->open(QFile::ReadOnly)) { + emit emErr(tr("Open file failed")+" "+file->errorString()); + tcp.close(); + return; + } + while(remain > 0) { + auto readed = file->read(qMin(4096LL, remain)); + if(readed.isEmpty()) { + emit emErr(tr("Read file failed")+" "+file->errorString()); + tcp.close(); + file->close(); + return; + } + resNum = tcp.write(readed); + if(resNum == -1) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write file: "+file->fileName()); + tcp.close(); + file->close(); + return; + } + if(! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForWritten file: "+file->fileName()); + tcp.close(); + file->close(); + return; + } + remain -= resNum; + } + file->close(); + req = QJsonObject(); + req.insert("_type", "imgFileEnd"); + req.insert("id", baseName); + req.insert("zVer","xixun1"); + resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileEnd'"); + tcp.close(); + return; + } + req = QJsonObject(); + req.insert("_type", "proEnd"); + req.insert("proName", "program"); + req.insert("zVer","xixun1"); + resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proEnd'"); + tcp.close(); + return; + }; + if(! tcp.waitForReadyRead()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'proEnd'"); + tcp.close(); + return; + } + auto resp = tcp.readAll(); + if(resp.isEmpty()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'proEnd'"); + tcp.close(); + return; + } + tcp.close(); + emit emErr(""); +} diff --git a/LedOK/device/ctrladvancedpanel.h b/LedOK/device/ctrladvancedpanel.h new file mode 100644 index 0000000..52b83a3 --- /dev/null +++ b/LedOK/device/ctrladvancedpanel.h @@ -0,0 +1,119 @@ +#ifndef CTRLADVANCEDPANEL_H +#define CTRLADVANCEDPANEL_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class CtrlAdvancedPanel : public QWidget { + Q_OBJECT +public: + explicit CtrlAdvancedPanel(QWidget *parent = nullptr); +protected: + void showEvent(QShowEvent *event) override; + void init(); + void changeEvent(QEvent *) override; + void transUi(); + + void keyReleaseEvent(QKeyEvent *) override; + void mouseReleaseEvent(QMouseEvent *) override; + +private: + bool isPassed{false}; + + QLabel *lbTitle; + QLabel *lbScreenWidth; + QLineEdit *fdScreenWidth; + QLabel *lbScreenHeight; + QLineEdit *fdScreenHeight; + QPushButton *btnScreenSet; + QLabel *lbAlias; + QLineEdit *fdAlias; + QPushButton *btnAliasSet; + QLabel *labelWebServer; + QComboBox *fdWebServerAddr; + QLabel *lbCompanyId; + QLineEdit *fdCompanyId; + QPushButton *btnWebServerSet; + QLabel *label; + QComboBox *fdRealtimeServer; + QPushButton *btnRealtimeServerSet; + QPushButton *btnRealtimeClear; + QPushButton *btnWareUpdate; + QLabel *lbWareTip; + QPushButton *btnApkCheck; + QComboBox *fdPkg; + QPushButton *fdUninstall; + QPushButton *btnIsRunning; + QPushButton *btnRestart; + QPushButton *btnClearProg; + QPushButton *btnGetLog; + QPushButton *btnSetBack, *btnPlayerBackSet, *btnPlayerBackClear; + + QLabel *lbTimingReboot; + QPushButton *btnTimingRebootSet, *btnTimingRebootGet; + + QGroupBox *grpM80, *grpY50; + QComboBox *fdM80Resolu, *fdDisMode; + QPushButton *btnM80Set, *btnY50Set; + QPushButton *btnM80Refresh; + QPushButton *btnM80Restore; + + QLabel *lbDisMode; + QPushButton *btnDisModeSet, *btnDisModeGet; + QLabel *lbScreenPos, *lbScreenOff; + QPushButton *btnScreenOffSet, *btnScreenOffGet; + + QGroupBox *grpHighForBusy; + QRadioButton *fdHighForBusy; + QRadioButton *fdTopLevelLH; + QPushButton *btnHighForBusySet; + QPushButton *btnGetTopLevel; + QPushButton *btnLedSet3; + QPushButton *btnLedSet4; + QPushButton *btnBindTaxiIc; + + QGroupBox *grpMinMaxBrightness; + QLabel *lbMinBright; + QLineEdit *fdMinBright; + QPushButton *btnMinBrightGet; + QPushButton *btnMinBrightSet; + QLabel *label_3; + QLineEdit *fdMaxBright; + QPushButton *btnMaxBrightGet; + QPushButton *btnMaxBrightSet; + + QGroupBox *grpBoxHiddenSettings; + QPushButton *btnSysUpd, *btnMcuUpd, *btnMcuGet; + QLabel *lbRotate, *lbBaudCfg, *lbBaudModel, *lbUart, *lbBaud; + QPushButton *btnBaudSet, *btnBaudGet; + QCheckBox *fdIsOpenADB; + QLabel *lbCustomJson; + QTextEdit *fdCustomJson; + QPushButton *btnSendCustomJson; + + QLabel *lbTraficProtocol, *lbCardMode, *lbTraficPort; + QComboBox *fdServerType; + QPushButton *btnTraficProtSet, *btnTraficProtGet, *btnTraficSet, *btnTraficGet; +}; + +class PlayerBackSendThread : public QThread { + Q_OBJECT +public: + PlayerBackSendThread(const QString &file, const QString &ip); + QString file, ip; + QString err; +protected: + void run(); +signals: + void emErr(QString); +}; + +#endif // CTRLADVANCEDPANEL_H diff --git a/LedOK/wDevicesManager/ctrlbrightpanel.cpp b/LedOK/device/ctrlbrightpanel.cpp similarity index 74% rename from LedOK/wDevicesManager/ctrlbrightpanel.cpp rename to LedOK/device/ctrlbrightpanel.cpp index d45da58..224cedf 100644 --- a/LedOK/wDevicesManager/ctrlbrightpanel.cpp +++ b/LedOK/device/ctrlbrightpanel.cpp @@ -1,902 +1,982 @@ -#include "ctrlbrightpanel.h" -#include "base/waitingdlg.h" -#include "globaldefine.h" -#include "deviceitem.h" -#include "tools.h" -#include "base/x_timeeditdelegate.h" -#include "xlsxdocument.h" -#include "xlsxworkbook.h" -#include -#include -#include -#include -#include -#include -#include -#include - -CtrlBrightPanel::CtrlBrightPanel(QWidget *parent) : QWidget(parent) { - auto vBox = new QVBoxLayout(this); - vBox->setContentsMargins(0,0,0,0); - vBox->addSpacing(8); - - lbBrightCfg = new QLabel; - lbBrightCfg->setAlignment(Qt::AlignCenter); - vBox->addWidget(lbBrightCfg); - - auto hBox = new QHBoxLayout(); - hBox->addStretch(); - - radioAuto = new QRadioButton(); - radioAuto->setChecked(true); - hBox->addWidget(radioAuto); - hBox->addSpacing(40); - - radioManual = new QRadioButton(); - hBox->addWidget(radioManual); - hBox->addSpacing(40); - - radioSchedule = new QRadioButton(); - hBox->addWidget(radioSchedule); - hBox->addStretch(); - - vBox->addLayout(hBox); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - auto autoPanel = new QWidget(); - { - auto vBox = new QVBoxLayout(autoPanel); - - fdBrightTip = new QLabel; - fdBrightTip->setAlignment(Qt::AlignCenter); - fdBrightTip->setWordWrap(true); - vBox->addWidget(fdBrightTip); - - auto hBox = new QHBoxLayout; - hBox->addStretch(); - - lbSensi = new QLabel; - lbSensi->setMinimumWidth(120); - lbSensi->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - hBox->addWidget(lbSensi); - - fdSensi = new QSlider(Qt::Horizontal); - fdSensi->setRange(1, 100); - hBox->addWidget(fdSensi); - - auto lbSensiValue = new QLabel(QString::number(fdSensi->value())+"%"); - lbSensiValue->setMinimumWidth(40); - lbSensiValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - connect(fdSensi, &QSlider::valueChanged, lbSensiValue, [lbSensiValue](int value) { - lbSensiValue->setText(QString::number(value)+"%"); - }); - hBox->addWidget(lbSensiValue); - - btnSensiSet = new QPushButton; - btnSensiSet->setMinimumSize(60, 30); - btnSensiSet->setProperty("ssType", "progManageTool"); - connect(btnSensiSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetBrightnessSensitivity"); - json.insert("_type", "SetBrightnessSensitivity"); - json.insert("sensitivity", fdSensi->value()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetBrightnessSensitivity")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetBrightnessSensitivity")) - } - } - }); - hBox->addWidget(btnSensiSet); - - btnSensiGet = new QPushButton; - btnSensiGet->setMinimumSize(60, 30); - btnSensiGet->setProperty("ssType", "progManageTool"); - connect(btnSensiGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetBrightnessSensitivity"); - json.insert("_type", "GetBrightnessSensitivity"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetBrightnessSensitivity")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - fdSensi->setValue(json["sensitivity"].toInt()); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = QString::number(json["sensitivity"].toInt()); - gFdResInfo->append(card->m_strCardId+" "+tr("GetBrightnessSensitivity")+" "+err); - }); - } - } - }); - hBox->addWidget(btnSensiGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout; - hBox->addStretch(); - - lbMinBright = new QLabel; - lbMinBright->setMinimumWidth(120); - lbMinBright->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - hBox->addWidget(lbMinBright); - - fdMinBright = new QSlider(Qt::Horizontal); - fdMinBright->setRange(1, 100); - hBox->addWidget(fdMinBright); - - auto lbMinBrightValue = new QLabel(QString::number(fdMinBright->value())+"%"); - lbMinBrightValue->setMinimumWidth(40); - lbMinBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - connect(fdMinBright, &QSlider::valueChanged, lbSensiValue, [lbMinBrightValue](int value) { - lbMinBrightValue->setText(QString::number(value)+"%"); - }); - hBox->addWidget(lbMinBrightValue); - - btnMinBrightSet = new QPushButton; - btnMinBrightSet->setMinimumSize(60, 30); - btnMinBrightSet->setProperty("ssType", "progManageTool"); - connect(btnMinBrightSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetMinBrightness"); - json.insert("_type", "SetMinBrightness"); - auto brightPercent = fdMinBright->value(); - if(gSelCards->count() == 1) { - json.insert("brightness", (brightPercent * gSelCards->at(0)->BrightnessLevel + 50) / 100); - auto waitingDlg = new WaitingDlg(this, tr("SetMinBrightness")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - json.insert("brightness", (brightPercent * card->BrightnessLevel + 50) / 100); - Def_CtrlSetMulti(tr("SetMinBrightness")); - } - } - }); - hBox->addWidget(btnMinBrightSet); - - btnMinBrightGet = new QPushButton; - btnMinBrightGet->setMinimumSize(60, 30); - btnMinBrightGet->setProperty("ssType", "progManageTool"); - connect(btnMinBrightGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetMinBrightness"); - json.insert("_type", "GetMinBrightness"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetMinBrightness")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { - Def_CtrlSingleGetReply - waitingDlg->success(); - fdMinBright->setValue(qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel)); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - gFdResInfo->append(card->m_strCardId+" "+tr("GetMinBrightness")+" "+(err.isEmpty()?QString::number(qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel))+"%":err)); - }); - } - } - }); - hBox->addWidget(btnMinBrightGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - - line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - fdSensiTypeTip = new QLabel; - fdSensiTypeTip->setAlignment(Qt::AlignCenter); - fdSensiTypeTip->setWordWrap(true); - vBox->addWidget(fdSensiTypeTip); - - hBox = new QHBoxLayout; - hBox->addStretch(); - - fdR68 = new QRadioButton("R68/RL3"); - hBox->addWidget(fdR68); - - fdRL2 = new QRadioButton("RL2"); - hBox->addWidget(fdRL2); - - hBox->addSpacing(20); - - btnUpload = new QPushButton; - btnUpload->setMinimumSize(60, 30); - btnUpload->setProperty("ssType", "progManageTool"); - connect(btnUpload, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QString sensorName; - if(fdRL2->isChecked()) sensorName = fdRL2->text(); - else if(fdR68->isChecked()) sensorName = fdR68->text(); - else { - QMessageBox::information(gMainWin, tr("Tip"), tr("NeedSelectSensorTypeTip")); - return; - } - QString xlsxFile = QFileDialog::getOpenFileName(this, tr("Open file dialog"), "/", "brightness files(*.xlsx)"); - if(xlsxFile.isEmpty() || ! QFileInfo::exists(xlsxFile)) return; - QXlsx::Document xlsx(xlsxFile); - auto workbook = xlsx.workbook(); - QXlsx::Worksheet *sheet = 0; - if(workbook->sheetCount() < 2) { - sheet = xlsx.currentWorksheet(); - if(sheet==0) { - QMessageBox::information(gMainWin, tr("Tip"), tr("Not found current worksheet")); - return; - } - } else { - auto names = sensorName.split("/"); - foreach(auto name, names) { - auto idx = xlsx.sheetNames().indexOf(name); - if(idx > -1) { - workbook->setActiveSheet(idx); - sheet = dynamic_cast(workbook->sheet(idx)); - break; - } - } - if(sheet==0) { - QMessageBox::information(gMainWin, tr("Tip"), "Not found sheet "+sensorName); - return; - } - } - QJsonArray values; - for(int j=0; j<255; j++) { - auto val = sheet->read(3, j+3).toString(); - if(val.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), "Cell is empty at 3, "+QString::number(j+3)); - return; - } - values.append(val); - } - QJsonObject json; - json.insert("_id", "SensorBrightnessTable"); - json.insert("_type", "SensorBrightnessTable"); - json.insert("values", values); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SensorBrightnessTable")); - Def_CtrlReqPre; - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter; - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SensorBrightnessTable")); - } - } - }); - hBox->addWidget(btnUpload); - - btnTableGet = new QPushButton(); - btnTableGet->setMinimumSize(60, 30); - btnTableGet->setProperty("ssType", "progManageTool"); - connect(btnTableGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QString strSensorType; - if(fdRL2->isChecked()) strSensorType = fdRL2->text(); - else if(fdR68->isChecked()) strSensorType = fdR68->text(); - else { - QMessageBox::information(gMainWin, tr("Tip"), tr("NeedSelectSensorTypeTip")); - return; - } - QJsonObject json; - json.insert("_id", "GetSensorBrightnessTable"); - json.insert("_type", "GetSensorBrightnessTable"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetSensorBrightnessTable")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card, strSensorType] { - Def_CtrlSingleGetReply - waitingDlg->close(); - QStringList values = json["values"].toVariant().value(); - if(values.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("no sensorBrightnessTable")); - return; - } - QString tempFile = QCoreApplication::applicationDirPath()+"/bright-template.xlsx"; - QFile tempQFile(tempFile); - if(! tempQFile.exists()) { - QMessageBox::information(gMainWin, tr("Tip"), tempFile+" is not exist"); - return; - } - QString selectFilter = "*.xlsx"; - QString savingFile = QFileDialog::getSaveFileName(this, tr("Save file"), card->m_strCardId + "BrightnessTable.xlsx", "brightness(*.xlsx );", &selectFilter, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - if(savingFile.isEmpty()) return; - tempQFile.copy(savingFile); - QXlsx::Document xlsx(savingFile); - xlsx.selectSheet(strSensorType); - for(int m=0; maddWidget(btnTableGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - - hBox = new QHBoxLayout; - hBox->addStretch(); - - lbCurBright = new QLabel; - hBox->addWidget(lbCurBright); - - fdCurBright = new QLabel; - hBox->addWidget(fdCurBright); - - btnCurBrightGet = new QPushButton; - btnCurBrightGet->setMinimumSize(60, 30); - btnCurBrightGet->setProperty("ssType", "progManageTool"); - connect(btnCurBrightGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetCurrentSensorBrightness"); - json.insert("_type", "GetCurrentSensorBrightness"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetCurrentSensorBrightness")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { - Def_CtrlSingleGetReply - waitingDlg->success(); - if(json["is485"].toBool()) fdR68->setChecked(true); - else fdRL2->setChecked(true); - fdCurBright->setText(QString::number(qRound(json["value"].toInt() * 100.0 / card->BrightnessLevel))+"%"); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = QString::number(qRound(json["value"].toInt() * 100.0 / card->BrightnessLevel))+"%"; - gFdResInfo->append(card->m_strCardId+" "+tr("GetBrightnessSensitivity")+" "+err); - }); - } - } - }); - hBox->addWidget(btnCurBrightGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - vBox->addStretch(); - } - auto manualPanel = new QWidget; - { - auto vBox = new QVBoxLayout(manualPanel); - - auto hBox = new QHBoxLayout; - hBox->addStretch(); - - lbFixedBright = new QLabel; - hBox->addWidget(lbFixedBright); - - fdFixedBright = new QSlider(Qt::Horizontal); - fdFixedBright->setRange(1, 100); - hBox->addWidget(fdFixedBright); - - auto lbBrightValue = new QLabel(QString::number(fdFixedBright->value())+"%"); - lbBrightValue->setMinimumWidth(40); - lbBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - connect(fdFixedBright, &QSlider::valueChanged, lbBrightValue, [lbBrightValue](int value) { - lbBrightValue->setText(QString::number(value)+"%"); - }); - hBox->addWidget(lbBrightValue); - - hBox->addStretch(); - - vBox->addLayout(hBox); - vBox->addSpacing(20); - - hBox = new QHBoxLayout; - hBox->addStretch(); - - btnFixedSet = new QPushButton; - btnFixedSet->setMinimumSize(60, 30); - btnFixedSet->setProperty("ssType", "progManageTool"); - connect(btnFixedSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetBrightness"); - json.insert("_type", "SetBrightness"); - auto percent = fdFixedBright->value(); - if(gSelCards->count() == 1) { - json.insert("brightness", (percent * gSelCards->at(0)->BrightnessLevel + 50) / 100); - auto waitingDlg = new WaitingDlg(this, tr("SetBrightness")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - json.insert("brightness", (percent * card->BrightnessLevel + 50) / 100); - Def_CtrlSetMulti(tr("SetBrightness")) - } - } - }); - hBox->addWidget(btnFixedSet); - - btnFixedGet = new QPushButton; - btnFixedGet->setMinimumSize(60, 30); - btnFixedGet->setProperty("ssType", "progManageTool"); - connect(btnFixedGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetBrightness"); - json.insert("_type", "GetBrightness"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetBrightness")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { - Def_CtrlSingleGetReply - waitingDlg->success(); - card->brightness = json["brightness"].toInt(); - fdFixedBright->setValue(qRound(card->brightness * 100.0 / card->BrightnessLevel)); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - gFdResInfo->append(card->m_strCardId+" "+tr("Brightness")+" "+(err.isEmpty()?QString::number(qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel))+"%":err)); - }); - } - } - }); - hBox->addWidget(btnFixedGet); - - hBox->addStretch(); - - vBox->addLayout(hBox); - vBox->addStretch(); - } - auto schedulePanel = new QWidget; - { - auto hBox = new QHBoxLayout(schedulePanel); - hBox->addStretch(); - auto vBox = new QVBoxLayout; - hBox->addLayout(vBox); - hBox->addStretch(); - - hBox = new QHBoxLayout(); - - fdScheTip = new QLabel; - fdScheTip->setWordWrap(true); - hBox->addWidget(fdScheTip); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - btnScheAdd = new QPushButton; - btnScheAdd->setMinimumSize(60, 30); - btnScheAdd->setProperty("ssType", "progManageTool"); - connect(btnScheAdd, &QPushButton::clicked, this, [this] { - int row = tableSche->rowCount(); - tableSche->insertRow(row); - - auto cellWgt = new QWidget; - auto hBox = new QHBoxLayout(cellWgt); - - auto slider = new QSlider(Qt::Horizontal); - slider->setRange(1, 100); - hBox->addWidget(slider); - - auto lb = new QLabel(QString::number(slider->value())+"%"); - connect(slider, &QSlider::valueChanged, lb, [lb](int value) { - lb->setText(QString::number(value)+"%"); - }); - hBox->addWidget(lb); - - tableSche->setCellWidget(row, "bright", cellWgt); - - auto timeEdit = new QTimeEdit(QTime(0, 0)); - timeEdit->setDisplayFormat("HH:mm"); - timeEdit->setAlignment(Qt::AlignCenter); - tableSche->setCellWidget(row, "start", timeEdit); - - timeEdit = new QTimeEdit(QTime(1, 0)); - timeEdit->setDisplayFormat("HH:mm"); - timeEdit->setAlignment(Qt::AlignCenter); - tableSche->setCellWidget(row, "end", timeEdit); - }); - hBox->addWidget(btnScheAdd); - - btnScheDel = new QPushButton; - btnScheDel->setMinimumSize(60, 30); - btnScheDel->setProperty("ssType", "progManageTool"); - connect(btnScheDel, &QPushButton::clicked, this, [this] { - auto selected = tableSche->selectedRanges(); - if(! selected.isEmpty()) tableSche->model()->removeRows(selected[0].topRow(), selected[0].rowCount()); - }); - hBox->addWidget(btnScheDel); - - btnScheClear = new QPushButton; - btnScheClear->setMinimumSize(60, 30); - btnScheClear->setProperty("ssType", "progManageTool"); - connect(btnScheClear, &QPushButton::clicked, this, [this] {tableSche->setRowCount(0);}); - hBox->addWidget(btnScheClear); - - hBox->addStretch(); - - lbDefBright = new QLabel; - lbDefBright->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - lbDefBright->setMinimumWidth(120); - hBox->addWidget(lbDefBright); - - fdDefBright = new QSlider(Qt::Horizontal); - fdDefBright->setRange(0, 100); - fdDefBright->setValue(100); - fdDefBright->setMinimumWidth(120); - hBox->addWidget(fdDefBright); - - auto lbDefBrightValue = new QLabel(QString::number(fdDefBright->value())+"%"); - lbDefBrightValue->setMinimumWidth(40); - lbDefBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); - connect(fdDefBright, &QSlider::valueChanged, lbDefBrightValue, [lbDefBrightValue](int value) { - lbDefBrightValue->setText(QString::number(value)+"%"); - }); - hBox->addWidget(lbDefBrightValue); - - hBox->addStretch(); - - btnScheImport = new QPushButton; - btnScheImport->setMinimumSize(QSize(60, 30)); - btnScheImport->setProperty("ssType", "progManageTool"); - connect(btnScheImport, &QPushButton::clicked, this, [this] { - auto dir = QSettings().value("CtrlScheduleDir").toString(); - if(dir.isEmpty()) dir = "/"; - QString scheFile = QFileDialog::getOpenFileName(this, tr("Import File"), dir, tr("BrightnessSchedule (*.bjs)")); - if(scheFile.isEmpty()) return; - QFile scheQFile(scheFile); - if(! scheQFile.open(QIODevice::ReadOnly)) return; - auto data = scheQFile.readAll(); - scheQFile.close(); - restoreScheduleJson(QJsonDocument::fromJson(data).object()); - }); - hBox->addWidget(btnScheImport); - - btnScheExport = new QPushButton; - btnScheExport->setMinimumSize(QSize(60, 30)); - btnScheExport->setProperty("ssType", "progManageTool"); - connect(btnScheExport, &QPushButton::clicked, this, [this] { - QSettings settings; - auto dir = settings.value("CtrlScheduleDir").toString(); - if(dir.isEmpty()) dir = "/"; - QString scheFile = QFileDialog::getSaveFileName(this, tr("Save File"), dir, tr("BrightnessSchedule (*.bjs)")); - if(scheFile.isEmpty()) return; - settings.setValue("CtrlScheduleDir", QFileInfo(scheFile).absolutePath()); - QFile scheQFile(scheFile); - if(! scheQFile.open(QIODevice::WriteOnly)) return; - scheQFile.write(QJsonDocument(getScheduleJson()).toJson()); - scheQFile.close(); - }); - hBox->addWidget(btnScheExport); - - vBox->addLayout(hBox); - - tableSche = new Table({ - {"bright", tr("BrightnessValue"), 300}, - {"start", tr("Start Time"), 100}, - {"end", tr("End Time"), 100} - }); - tableSche->setDefs(); - tableSche->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - vBox->addWidget(tableSche); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - - btnScheSet = new QPushButton; - btnScheSet->setMinimumSize(QSize(60, 30)); - btnScheSet->setProperty("ssType", "progManageTool"); - connect(btnScheSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetAutoBrightnessTask"); - json.insert("_type", "SetAutoBrightnessTask"); - if(gSelCards->count() == 1) { - json.insert("taskBrightness", getScheduleJson(gSelCards->at(0)->BrightnessLevel)); - auto waitingDlg = new WaitingDlg(this, tr("SetAutoBrightnessTask")); - Def_CtrlReqPre; - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - json.insert("taskBrightness", getScheduleJson(card->BrightnessLevel)); - Def_CtrlSetMulti(tr("SetAutoBrightnessTask")) - } - } - }); - hBox->addWidget(btnScheSet); - - hBox->addStretch(); - - btnScheGet = new QPushButton; - btnScheGet->setMinimumSize(QSize(60, 30)); - btnScheGet->setProperty("ssType", "progManageTool"); - connect(btnScheGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetAutoBrightnessTask"); - json.insert("_type", "GetAutoBrightnessTask"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetAutoBrightnessTask")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { - Def_CtrlSingleGetReply - waitingDlg->success(); - restoreScheduleJson(json["taskBrightness"].toObject(), card->BrightnessLevel); - }); - } - }); - hBox->addWidget(btnScheGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - } - auto stackBox = new QStackedLayout(vBox); - stackBox->addWidget(autoPanel); - stackBox->addWidget(manualPanel); - stackBox->addWidget(schedulePanel); - stackBox->setCurrentIndex(0); - - auto group = new QButtonGroup; - group->addButton(radioAuto, 0); - group->addButton(radioManual, 1); - group->addButton(radioSchedule, 2); - connect(group, &QButtonGroup::idToggled, stackBox, [stackBox](int idx, bool checked) { - if(checked) stackBox->setCurrentIndex(idx); - }); - - connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { - if(isVisible()) init(); - }); - transUi(); -} - -void CtrlBrightPanel::showEvent(QShowEvent *event) { - QWidget::showEvent(event); - init(); -} -void CtrlBrightPanel::init() { - bool isSingle = gSelCards->count()==1; - btnTableGet->setEnabled(isSingle); - btnScheGet->setEnabled(isSingle); - if(! isSingle) return; - auto card = gSelCards->at(0); - - mSensi = -1; - mTask = -1; - - QJsonObject json; - json.insert("_id", "GetAutoBrightnessTask"); - json.insert("_type", "GetAutoBrightnessTask"); - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - mTask = restoreScheduleJson(json["taskBrightness"].toObject(), card->BrightnessLevel); - if(mTask) radioSchedule->setChecked(true); - else if(mSensi > 0) radioAuto->setChecked(true); - else if(mSensi == 0) radioManual->setChecked(true); - }); - - json = QJsonObject(); - json.insert("_id", "GetBrightnessSensitivity"); - json.insert("_type", "GetBrightnessSensitivity"); - reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - mSensi = json["sensitivity"].toInt(); - fdSensi->setValue(mSensi); - if(mTask != 0) return; - if(mSensi > 0) radioAuto->setChecked(true); - else radioManual->setChecked(true); - }); - - json = QJsonObject(); - json.insert("_id", "GetMinBrightness"); - json.insert("_type", "GetMinBrightness"); - reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - fdMinBright->setValue(qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel)); - }); - - json = QJsonObject(); - json.insert("_id", "GetBrightness"); - json.insert("_type", "GetBrightness"); - reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - card->brightness = json["brightness"].toInt(); - fdFixedBright->setValue(qRound(card->brightness * 100.0 / card->BrightnessLevel)); - }); -} - -void CtrlBrightPanel::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void CtrlBrightPanel::transUi() { - lbBrightCfg->setText(tr("Brightness Configuration")); - radioAuto->setText(tr("Auto")); - radioManual->setText(tr("Manual")); - radioSchedule->setText(tr("Schedule")); - - fdBrightTip->setText(tr("BrightTip1")); - fdSensiTypeTip->setText(tr("BrightTip2")); - lbSensi->setText(tr("Sensitivity")); - lbMinBright->setText(tr("Minbrightness")); - btnMinBrightSet->setText(tr("Set")); - btnSensiSet->setText(tr("Set")); - btnUpload->setText(tr("Upload")); - btnMinBrightGet->setText(tr("Readback")); - btnSensiGet->setText(tr("Readback")); - btnTableGet->setText(tr("ReadbackTable")); - btnCurBrightGet->setText(tr("Refresh")); - lbCurBright->setText(tr("Cur Brigntness")+": "); - - lbFixedBright->setText(tr("Brightness value")); - btnFixedSet->setText(tr("Set")); - btnFixedGet->setText(tr("Readback")); - - lbDefBright->setText(tr("Default brightness")); - btnScheAdd->setText(tr("Add")); - btnScheClear->setText(tr("Clear")); - btnScheDel->setText(tr("Delete")); - btnScheImport->setText(tr("Import")); - btnScheExport->setText(tr("Export")); - btnScheSet->setText(tr("Apply")); - btnScheGet->setText(tr("Readback")); - fdScheTip->setText(tr("Default brightness tip")); -} - -bool CtrlBrightPanel::restoreScheduleJson(QJsonObject obj, int max) { - tableSche->setRowCount(0); - fdDefBright->setValue(qRound(obj["defaultBrightness"].toInt() * 100.0 / max)); - auto jsitems = obj["items"].toArray(); - foreach(auto jsitem, jsitems) { - auto schedule = jsitem["schedules"][0]; - int row = tableSche->rowCount(); - tableSche->insertRow(row); - - auto cellWgt = new QWidget; - auto hBox = new QHBoxLayout(cellWgt); - - auto slider = new QSlider(Qt::Horizontal); - slider->setRange(1, 100); - slider->setValue(qRound(jsitem["brightness"].toInt() * 100.0 / max)); - hBox->addWidget(slider); - - auto lb = new QLabel(QString::number(slider->value())+"%"); - connect(slider, &QSlider::valueChanged, lb, [lb](int value) { - lb->setText(QString::number(value)+"%"); - }); - hBox->addWidget(lb); - tableSche->setCellWidget(row, "bright", cellWgt); - - auto timeEdit = new QTimeEdit(QTime::fromString(schedule["startTime"].toString(), "HH:mm")); - timeEdit->setDisplayFormat("HH:mm"); - timeEdit->setAlignment(Qt::AlignCenter); - tableSche->setCellWidget(row, "start", timeEdit); - - timeEdit = new QTimeEdit(QTime::fromString(schedule["endTime"].toString(), "HH:mm")); - timeEdit->setDisplayFormat("HH:mm"); - timeEdit->setAlignment(Qt::AlignCenter); - tableSche->setCellWidget(row, "end", timeEdit); - } - return jsitems.count() > 0; -} -QJsonObject CtrlBrightPanel::getScheduleJson(int max) { - QJsonObject obj; - obj["createDate"] = QJsonValue::Null; - obj["createBy"] = "alahover"; - obj["name"] = "TimingBrightness"; - auto def = (fdDefBright->value() * max + 50) / 100; - obj["defaultBrightness"] = def; - obj["brightness"] = def; - QJsonArray jsItems; - for(int i=0; irowCount(); i++) { - QJsonObject item; - item["brightness"] = (static_cast(tableSche->cellWidget(i, "bright")->layout()->itemAt(0)->widget())->value() * max + 50) / 100; - QJsonObject schedule; - schedule["timeType"] = "Range"; - schedule["startTime"] = static_cast(tableSche->cellWidget(i, "start"))->text(); - schedule["endTime"] = static_cast(tableSche->cellWidget(i, "end"))->text(); - schedule["dateType"] = "All"; - schedule["startDate"] = QJsonValue::Null; - schedule["endDate"] = QJsonValue::Null; - schedule["monthFilter"] = QJsonArray(); - schedule["filterType"] = "None"; - schedule["weekFilter"] = QJsonArray(); - item["schedules"] = QJsonArray{schedule}; - jsItems.append(item); - } - obj["items"] = jsItems; - return obj; -} +#include "ctrlbrightpanel.h" +#include "base/waitingdlg.h" +#include "globaldefine.h" +#include "deviceitem.h" +#include "tools.h" +#include "xlsxdocument.h" +#include "xlsxworkbook.h" +#include +#include +#include +#include +#include +#include +#include + +CtrlBrightPanel::CtrlBrightPanel(QWidget *parent) : QWidget(parent) { + auto vBox = new VBox(this); + vBox->setContentsMargins(0,0,0,0); + vBox->addSpacing(8); + + lbBrightCfg = new QLabel; + auto font = lbBrightCfg->font(); + font.setPixelSize(font.pixelSize()+2); + font.setBold(true); + lbBrightCfg->setFont(font); + lbBrightCfg->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbBrightCfg); + vBox->addSpacing(9); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + radioAuto = new QRadioButton; + radioAuto->setChecked(true); + hBox->addWidget(radioAuto); + hBox->addSpacing(40); + + radioManual = new QRadioButton; + hBox->addWidget(radioManual); + hBox->addSpacing(40); + + radioSchedule = new QRadioButton; + hBox->addWidget(radioSchedule); + hBox->addStretch(); + + fdAdaptToOld = new QCheckBox; + hBox->addWidget(fdAdaptToOld); + + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + auto stack = new QStackedLayout(vBox); + { + auto vBox = new VBox(stack); + + fdBrightTip = new QLabel; + fdBrightTip->setAlignment(Qt::AlignCenter); + fdBrightTip->setWordWrap(true); + vBox->addWidget(fdBrightTip); + + auto hBox = new QHBoxLayout; + hBox->addStretch(); + + lbSensi = new QLabel; + lbSensi->setMinimumWidth(120); + lbSensi->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + hBox->addWidget(lbSensi); + + fdSensi = new QSlider(Qt::Horizontal); + fdSensi->setRange(1, 100); + hBox->addWidget(fdSensi); + + auto lbSensiValue = new QLabel(QString::number(fdSensi->value())+"%"); + lbSensiValue->setMinimumWidth(40); + lbSensiValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + connect(fdSensi, &QSlider::valueChanged, lbSensiValue, [lbSensiValue](int value) { + lbSensiValue->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lbSensiValue); + + btnSensiSet = new QPushButton; + btnSensiSet->setMinimumSize(60, 30); + btnSensiSet->setProperty("ssType", "progManageTool"); + connect(btnSensiSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetBrightnessSensitivity"); + json.insert("_type", "SetBrightnessSensitivity"); + json.insert("sensitivity", fdSensi->value()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetBrightnessSensitivity")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, card, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetBrightnessSensitivity")) + } + } + }); + hBox->addWidget(btnSensiSet); + + btnSensiGet = new QPushButton; + btnSensiGet->setMinimumSize(60, 30); + btnSensiGet->setProperty("ssType", "progManageTool"); + connect(btnSensiGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetBrightnessSensitivity"); + json.insert("_type", "GetBrightnessSensitivity"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetBrightnessSensitivity")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdSensi->setValue(json["sensitivity"].toInt()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = QString::number(json["sensitivity"].toInt()); + gFdResInfo->append(cardId+" "+tr("GetBrightnessSensitivity")+" "+err); + }); + } + } + }); + hBox->addWidget(btnSensiGet); + + hBox->addStretch(); + vBox->addLayout(hBox); + + hBox = new QHBoxLayout; + hBox->addStretch(); + + lbMinBright = new QLabel; + lbMinBright->setMinimumWidth(120); + lbMinBright->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + hBox->addWidget(lbMinBright); + + fdMinBright = new QSlider(Qt::Horizontal); + fdMinBright->setRange(1, 100); + hBox->addWidget(fdMinBright); + + auto lbMinBrightValue = new QLabel(QString::number(fdMinBright->value())+"%"); + lbMinBrightValue->setMinimumWidth(40); + lbMinBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + connect(fdMinBright, &QSlider::valueChanged, lbSensiValue, [lbMinBrightValue](int value) { + lbMinBrightValue->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lbMinBrightValue); + + btnMinBrightSet = new QPushButton; + btnMinBrightSet->setMinimumSize(60, 30); + btnMinBrightSet->setProperty("ssType", "progManageTool"); + connect(btnMinBrightSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto isAdaptToOld = fdAdaptToOld->isChecked(); + QJsonObject json; + json.insert("_id", "SetMinBrightness"); + json.insert("_type", "SetMinBrightness"); + auto brightPercent = fdMinBright->value(); + if(! isAdaptToOld) json.insert("minBrightnessPercentage", brightPercent); + if(gSelCards->count() == 1) { + if(isAdaptToOld) json.insert("brightness", (brightPercent * gSelCards->at(0)->BrightnessLevel + 50) / 100); + auto waitingDlg = new WaitingDlg(this, tr("SetMinBrightness")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + if(isAdaptToOld) json.insert("brightness", (brightPercent * card->BrightnessLevel + 50) / 100); + Def_CtrlSetMulti(tr("SetMinBrightness")); + } + } + }); + hBox->addWidget(btnMinBrightSet); + + btnMinBrightGet = new QPushButton; + btnMinBrightGet->setMinimumSize(60, 30); + btnMinBrightGet->setProperty("ssType", "progManageTool"); + connect(btnMinBrightGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetMinBrightness"); + json.insert("_type", "GetMinBrightness"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetMinBrightness")+" ..."); + Def_CtrlReqPre + auto brightLevel = card->BrightnessLevel; + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, brightLevel] { + Def_CtrlSingleGetReply + waitingDlg->success(); + auto value = json["minBrightnessPercentage"].toInt(-1); + if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / brightLevel); + fdMinBright->setValue(value); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + auto brightLevel = card->BrightnessLevel; + connect(reply, &QNetworkReply::finished, this, [reply, cardId, brightLevel] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + auto value = json["minBrightnessPercentage"].toInt(-1); + if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / brightLevel); + err = QString::number(value)+"%"; + } + gFdResInfo->append(cardId+" "+tr("GetMinBrightness")+" "+err); + }); + } + } + }); + hBox->addWidget(btnMinBrightGet); + + hBox->addStretch(); + vBox->addLayout(hBox); + + + line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + fdSensiTypeTip = new QLabel; + fdSensiTypeTip->setAlignment(Qt::AlignCenter); + fdSensiTypeTip->setWordWrap(true); + vBox->addWidget(fdSensiTypeTip); + + hBox = new QHBoxLayout; + hBox->addStretch(); + + fdR68 = new QRadioButton("R68/RL3"); + hBox->addWidget(fdR68); + + fdRL2 = new QRadioButton("RL2"); + hBox->addWidget(fdRL2); + + hBox->addSpacing(20); + + btnUpload = new QPushButton; + btnUpload->setMinimumSize(60, 30); + btnUpload->setProperty("ssType", "progManageTool"); + connect(btnUpload, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QString sensorName; + if(fdRL2->isChecked()) sensorName = fdRL2->text(); + else if(fdR68->isChecked()) sensorName = fdR68->text(); + else { + QMessageBox::information(gMainWin, tr("Tip"), tr("NeedSelectSensorTypeTip")); + return; + } + QString xlsxFile = QFileDialog::getOpenFileName(this, tr("Open file dialog"), "/", "brightness files(*.xlsx)"); + if(xlsxFile.isEmpty() || ! QFileInfo::exists(xlsxFile)) return; + QXlsx::Document xlsx(xlsxFile); + auto workbook = xlsx.workbook(); + QXlsx::Worksheet *sheet = 0; + if(workbook->sheetCount() < 2) { + sheet = xlsx.currentWorksheet(); + if(sheet==0) { + QMessageBox::information(gMainWin, tr("Tip"), tr("Not found current worksheet")); + return; + } + } else { + auto names = sensorName.split("/"); + foreach(auto name, names) { + auto idx = xlsx.sheetNames().indexOf(name); + if(idx > -1) { + workbook->setActiveSheet(idx); + sheet = dynamic_cast(workbook->sheet(idx)); + break; + } + } + if(sheet==0) { + QMessageBox::information(gMainWin, tr("Tip"), "Not found sheet "+sensorName); + return; + } + } + QJsonArray values; + for(int j=0; j<255; j++) { + auto val = sheet->read(3, j+3).toString(); + if(val.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), "Cell is empty at 3, "+QString::number(j+3)); + return; + } + values.append(val); + } + QJsonObject json; + json.insert("_id", "SensorBrightnessTable"); + json.insert("_type", "SensorBrightnessTable"); + json.insert("values", values); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SensorBrightnessTable")); + Def_CtrlReqPre; + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter; + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SensorBrightnessTable")); + } + } + }); + hBox->addWidget(btnUpload); + + btnTableGet = new QPushButton(); + btnTableGet->setMinimumSize(60, 30); + btnTableGet->setProperty("ssType", "progManageTool"); + connect(btnTableGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QString strSensorType; + if(fdRL2->isChecked()) strSensorType = fdRL2->text(); + else if(fdR68->isChecked()) strSensorType = fdR68->text(); + else { + QMessageBox::information(gMainWin, tr("Tip"), tr("NeedSelectSensorTypeTip")); + return; + } + QJsonObject json; + json.insert("_id", "GetSensorBrightnessTable"); + json.insert("_type", "GetSensorBrightnessTable"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetSensorBrightnessTable")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card, strSensorType] { + Def_CtrlSingleGetReply + waitingDlg->close(); + QStringList values = json["values"].toVariant().value(); + if(values.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("no sensorBrightnessTable")); + return; + } + QString tempFile = QCoreApplication::applicationDirPath()+"/bright-template.xlsx"; + QFile tempQFile(tempFile); + if(! tempQFile.exists()) { + QMessageBox::information(gMainWin, tr("Tip"), tempFile+" is not exist"); + return; + } + QString selectFilter = "*.xlsx"; + QString savingFile = QFileDialog::getSaveFileName(this, tr("Save file"), card->m_strCardId + "BrightnessTable.xlsx", "brightness(*.xlsx );", &selectFilter, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + if(savingFile.isEmpty()) return; + tempQFile.copy(savingFile); + QXlsx::Document xlsx(savingFile); + xlsx.selectSheet(strSensorType); + for(int m=0; maddWidget(btnTableGet); + + hBox->addStretch(); + vBox->addLayout(hBox); + + + hBox = new QHBoxLayout; + hBox->addStretch(); + + lbCurBright = new QLabel; + hBox->addWidget(lbCurBright); + + fdCurBright = new QLabel; + hBox->addWidget(fdCurBright); + + btnCurBrightGet = new QPushButton; + btnCurBrightGet->setMinimumSize(60, 30); + btnCurBrightGet->setProperty("ssType", "progManageTool"); + connect(btnCurBrightGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetCurrentSensorBrightness"); + json.insert("_type", "GetCurrentSensorBrightness"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetCurrentSensorBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { + QJsonDocument json; + QByteArray data; + QString err = checkReplyForJson(reply, &json, &data); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + waitingDlg->success(); + if(json["is485"].toBool()) fdR68->setChecked(true); + else fdRL2->setChecked(true); + fdCurBright->setText(QString::number(qRound(json["value"].toInt() * 100.0 / card->BrightnessLevel))+"%"); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [reply, card] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = QString::number(qRound(json["value"].toInt() * 100.0 / card->BrightnessLevel))+"%"; + gFdResInfo->append(card->m_strCardId+" "+tr("GetCurrentSensorBrightness")+" "+err); + }); + } + } + }); + hBox->addWidget(btnCurBrightGet); + + hBox->addStretch(); + vBox->addLayout(hBox); + vBox->addStretch(); + } + { + auto vBox = new VBox(stack); + + auto hBox = new QHBoxLayout; + hBox->addStretch(); + + lbFixedBright = new QLabel; + hBox->addWidget(lbFixedBright); + + fdFixedBright = new QSlider(Qt::Horizontal); + fdFixedBright->setRange(1, 100); + hBox->addWidget(fdFixedBright); + + auto lbBrightValue = new QLabel(QString::number(fdFixedBright->value())+"%"); + lbBrightValue->setMinimumWidth(40); + lbBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + connect(fdFixedBright, &QSlider::valueChanged, lbBrightValue, [lbBrightValue](int value) { + lbBrightValue->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lbBrightValue); + + hBox->addStretch(); + + vBox->addLayout(hBox); + vBox->addSpacing(20); + + hBox = new QHBoxLayout; + hBox->addStretch(); + + btnFixedSet = new QPushButton; + btnFixedSet->setMinimumSize(60, 30); + btnFixedSet->setProperty("ssType", "progManageTool"); + connect(btnFixedSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto isAdaptToOld = fdAdaptToOld->isChecked(); + QJsonObject json; + json.insert("_id", "SetBrightness"); + json.insert("_type", "SetBrightness"); + auto percent = fdFixedBright->value(); + if(! isAdaptToOld) json.insert("brightnessPercentage", percent); + if(gSelCards->count() == 1) { + if(isAdaptToOld) json.insert("brightness", (percent * gSelCards->at(0)->BrightnessLevel + 50) / 100); + auto waitingDlg = new WaitingDlg(this, tr("SetBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + if(isAdaptToOld) json.insert("brightness", (percent * card->BrightnessLevel + 50) / 100); + Def_CtrlSetMulti(tr("SetBrightness")) + } + } + }); + hBox->addWidget(btnFixedSet); + + btnFixedGet = new QPushButton; + btnFixedGet->setMinimumSize(60, 30); + btnFixedGet->setProperty("ssType", "progManageTool"); + connect(btnFixedGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetBrightness"); + json.insert("_type", "GetBrightness"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetBrightness")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { + QJsonDocument json; + QByteArray data; + QString err = checkReplyForJson(reply, &json, &data); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + waitingDlg->success(); + card->bright = json["brightnessPercentage"].toInt(-1); + if(card->bright==-1) card->bright = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel); + fdFixedBright->setValue(card->bright); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [reply, card] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + auto value = json["brightnessPercentage"].toInt(-1); + if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel); + err = QString::number(value)+"%"; + } + gFdResInfo->append(card->m_strCardId+" "+tr("Brightness")+" "+err); + }); + } + } + }); + hBox->addWidget(btnFixedGet); + + hBox->addStretch(); + + vBox->addLayout(hBox); + vBox->addStretch(); + } + { + auto hBox = new HBox(stack); + hBox->addStretch(); + auto vBox = new VBox(hBox); + hBox->addStretch(); + + hBox = new HBox(vBox); + + fdScheTip = new QLabel; + fdScheTip->setWordWrap(true); + hBox->addWidget(fdScheTip); + + + hBox = new HBox(vBox); + + btnScheAdd = new QPushButton; + btnScheAdd->setMinimumSize(60, 30); + btnScheAdd->setProperty("ssType", "progManageTool"); + connect(btnScheAdd, &QPushButton::clicked, this, [this] { + int row = tableSche->rowCount(); + tableSche->insertRow(row); + + auto cellWgt = new QWidget; + auto hBox = new QHBoxLayout(cellWgt); + + auto slider = new QSlider(Qt::Horizontal); + slider->setRange(1, 100); + hBox->addWidget(slider); + + auto lb = new QLabel(QString::number(slider->value())+"%"); + connect(slider, &QSlider::valueChanged, lb, [lb](int value) { + lb->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lb); + + tableSche->setCellWidget(row, "bright", cellWgt); + + auto timeEdit = new QTimeEdit(QTime(0, 0)); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "start", timeEdit); + + timeEdit = new QTimeEdit(QTime(1, 0)); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "end", timeEdit); + }); + hBox->addWidget(btnScheAdd); + + btnScheDel = new QPushButton; + btnScheDel->setMinimumSize(60, 30); + btnScheDel->setProperty("ssType", "progManageTool"); + connect(btnScheDel, &QPushButton::clicked, this, [this] { + auto selected = tableSche->selectedRanges(); + if(! selected.isEmpty()) tableSche->model()->removeRows(selected[0].topRow(), selected[0].rowCount()); + }); + hBox->addWidget(btnScheDel); + + btnScheClear = new QPushButton; + btnScheClear->setMinimumSize(60, 30); + btnScheClear->setProperty("ssType", "progManageTool"); + connect(btnScheClear, &QPushButton::clicked, this, [this] {tableSche->setRowCount(0);}); + hBox->addWidget(btnScheClear); + + hBox->addStretch(); + + lbDefBright = new QLabel; + lbDefBright->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + lbDefBright->setMinimumWidth(120); + hBox->addWidget(lbDefBright); + + fdDefBright = new QSlider(Qt::Horizontal); + fdDefBright->setRange(0, 100); + fdDefBright->setValue(100); + fdDefBright->setMinimumWidth(120); + hBox->addWidget(fdDefBright); + + auto lbDefBrightValue = new QLabel(QString::number(fdDefBright->value())+"%"); + lbDefBrightValue->setMinimumWidth(40); + lbDefBrightValue->setAlignment(Qt::AlignRight | Qt::AlignVCenter); + connect(fdDefBright, &QSlider::valueChanged, lbDefBrightValue, [lbDefBrightValue](int value) { + lbDefBrightValue->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lbDefBrightValue); + + hBox->addStretch(); + + btnScheImport = new QPushButton; + btnScheImport->setMinimumSize(QSize(60, 30)); + btnScheImport->setProperty("ssType", "progManageTool"); + connect(btnScheImport, &QPushButton::clicked, this, [this] { + auto dir = QSettings().value("CtrlScheduleDir").toString(); + if(dir.isEmpty()) dir = "/"; + QString scheFile = QFileDialog::getOpenFileName(this, tr("Import File"), dir, tr("BrightnessSchedule (*.bjs)")); + if(scheFile.isEmpty()) return; + QFile scheQFile(scheFile); + if(! scheQFile.open(QIODevice::ReadOnly)) return; + auto data = scheQFile.readAll(); + scheQFile.close(); + auto json = QJsonDocument::fromJson(data); + tableSche->setRowCount(0); + fdDefBright->setValue(json["defaultBrightness"].toInt()); + auto jsitems = json["items"].toArray(); + foreach(auto jsitem, jsitems) { + auto schedule = jsitem["schedules"][0]; + int row = tableSche->rowCount(); + tableSche->insertRow(row); + + auto cellWgt = new QWidget; + auto hBox = new QHBoxLayout(cellWgt); + + auto slider = new QSlider(Qt::Horizontal); + slider->setRange(1, 100); + slider->setValue(jsitem["brightness"].toInt()); + hBox->addWidget(slider); + + auto lb = new QLabel(QString::number(slider->value())+"%"); + connect(slider, &QSlider::valueChanged, lb, [lb](int value) { + lb->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lb); + tableSche->setCellWidget(row, "bright", cellWgt); + + auto timeEdit = new QTimeEdit(QTime::fromString(schedule["startTime"].toString(), "HH:mm")); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "start", timeEdit); + + timeEdit = new QTimeEdit(QTime::fromString(schedule["endTime"].toString(), "HH:mm")); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "end", timeEdit); + } + }); + hBox->addWidget(btnScheImport); + + btnScheExport = new QPushButton; + btnScheExport->setMinimumSize(QSize(60, 30)); + btnScheExport->setProperty("ssType", "progManageTool"); + connect(btnScheExport, &QPushButton::clicked, this, [this] { + QSettings settings; + auto dir = settings.value("CtrlScheduleDir").toString(); + if(dir.isEmpty()) dir = "/"; + QString scheFile = QFileDialog::getSaveFileName(this, tr("Save File"), dir, tr("BrightnessSchedule (*.bjs)")); + if(scheFile.isEmpty()) return; + settings.setValue("CtrlScheduleDir", QFileInfo(scheFile).absolutePath()); + QFile scheQFile(scheFile); + if(! scheQFile.open(QIODevice::WriteOnly)) return; + QJsonArray items; + for(int i=0; irowCount(); i++) items.append(QJsonObject{ + {"brightness", static_cast(tableSche->cellWidget(i, "bright")->layout()->itemAt(0)->widget())->value()}, + {"schedules", QJsonArray{QJsonObject{ + {"startTime", static_cast(tableSche->cellWidget(i, "start"))->text()}, + {"endTime", static_cast(tableSche->cellWidget(i, "end"))->text()} + }}} + }); + scheQFile.write(QJsonDocument(QJsonObject{{"defaultBrightness", fdDefBright->value()}, {"items", items}}).toJson()); + scheQFile.close(); + }); + hBox->addWidget(btnScheExport); + + + tableSche = new Table({ + {"bright", "", 300}, + {"start", "", 100}, + {"end", "", 100} + }); + tableSche->setDefs(); + tableSche->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + vBox->addWidget(tableSche); + + hBox = new HBox(vBox); + hBox->addStretch(); + + btnScheSet = new QPushButton; + btnScheSet->setMinimumSize(QSize(60, 30)); + btnScheSet->setProperty("ssType", "progManageTool"); + connect(btnScheSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + auto isAdaptToOld = fdAdaptToOld->isChecked(); + QJsonObject json; + json.insert("_id", "SetAutoBrightnessTask"); + json.insert("_type", "SetAutoBrightnessTask"); + if(! isAdaptToOld) getScheduleJson(json, 0); + if(gSelCards->count() == 1) { + if(isAdaptToOld) getScheduleJson(json, gSelCards->at(0)->BrightnessLevel); + auto waitingDlg = new WaitingDlg(this, tr("SetAutoBrightnessTask")); + Def_CtrlReqPre; + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + if(isAdaptToOld) getScheduleJson(json, card->BrightnessLevel); + Def_CtrlSetMulti(tr("SetAutoBrightnessTask")) + } + } + }); + hBox->addWidget(btnScheSet); + + hBox->addStretch(); + + btnScheGet = new QPushButton; + btnScheGet->setMinimumSize(QSize(60, 30)); + btnScheGet->setProperty("ssType", "progManageTool"); + connect(btnScheGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetAutoBrightnessTask"); + json.insert("_type", "GetAutoBrightnessTask"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetAutoBrightnessTask")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg, card] { + Def_CtrlSingleGetReply + waitingDlg->success(); + restoreScheduleJson(json, card->BrightnessLevel); + }); + } + }); + hBox->addWidget(btnScheGet); + + hBox->addStretch(); + } + stack->setCurrentIndex(0); + + auto group = new QButtonGroup; + group->addButton(radioAuto, 0); + group->addButton(radioManual, 1); + group->addButton(radioSchedule, 2); + connect(group, &QButtonGroup::idToggled, stack, [=](int idx, bool checked) { + if(checked) stack->setCurrentIndex(idx); + }); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void CtrlBrightPanel::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void CtrlBrightPanel::init() { + bool isSingle = gSelCards->count()==1; + btnTableGet->setEnabled(isSingle); + btnScheGet->setEnabled(isSingle); + if(! isSingle) return; + auto card = gSelCards->at(0); + + mSensi = -1; + mTask = -1; + + QJsonObject json; + json.insert("_id", "GetAutoBrightnessTask"); + json.insert("_type", "GetAutoBrightnessTask"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply, card] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + mTask = restoreScheduleJson(json, card->BrightnessLevel); + if(mTask) radioSchedule->setChecked(true); + else if(mSensi > 0) radioAuto->setChecked(true); + else if(mSensi == 0) radioManual->setChecked(true); + }); + + json = QJsonObject(); + json.insert("_id", "GetBrightnessSensitivity"); + json.insert("_type", "GetBrightnessSensitivity"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + mSensi = json["sensitivity"].toInt(); + fdSensi->setValue(mSensi); + if(mTask != 0) return; + if(mSensi > 0) radioAuto->setChecked(true); + else radioManual->setChecked(true); + }); + + json = QJsonObject(); + json.insert("_id", "GetMinBrightness"); + json.insert("_type", "GetMinBrightness"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply, card] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + auto value = json["minBrightnessPercentage"].toInt(-1); + if(value==-1) value = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel); + fdMinBright->setValue(value); + }); + + json = QJsonObject(); + json.insert("_id", "GetBrightness"); + json.insert("_type", "GetBrightness"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply, card] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + card->bright = json["brightnessPercentage"].toInt(-1); + if(card->bright==-1) card->bright = qRound(json["brightness"].toInt() * 100.0 / card->BrightnessLevel); + fdFixedBright->setValue(card->bright); + }); +} + +void CtrlBrightPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void CtrlBrightPanel::transUi() { + lbBrightCfg->setText(tr("Brightness Configuration")); + radioAuto->setText(tr("Auto")); + radioManual->setText(tr("Manual")); + radioSchedule->setText(tr("Schedule")); + fdAdaptToOld->setText(tr("Adapt to Old Devices")); + + fdBrightTip->setText(tr("BrightTip1")); + fdSensiTypeTip->setText(tr("BrightTip2")); + lbSensi->setText(tr("Sensitivity")); + lbMinBright->setText(tr("Minbrightness")); + btnMinBrightSet->setText(tr("Set")); + btnSensiSet->setText(tr("Set")); + btnUpload->setText(tr("Upload")); + btnMinBrightGet->setText(tr("Readback")); + btnSensiGet->setText(tr("Readback")); + btnTableGet->setText(tr("ReadbackTable")); + btnCurBrightGet->setText(tr("Refresh")); + lbCurBright->setText(tr("Cur Brigntness")+": "); + + lbFixedBright->setText(tr("Brightness value")); + btnFixedSet->setText(tr("Set")); + btnFixedGet->setText(tr("Readback")); + + lbDefBright->setText(tr("Default brightness")); + btnScheAdd->setText(tr("Add")); + btnScheClear->setText(tr("Clear")); + btnScheDel->setText(tr("Delete")); + btnScheImport->setText(tr("Import")); + btnScheExport->setText(tr("Export")); + + tableSche->setHeaderText("bright", tr("BrightnessValue")); + tableSche->setHeaderText("start", tr("Start Time")); + tableSche->setHeaderText("end", tr("End Time")); + + btnScheSet->setText(tr("Apply")); + btnScheGet->setText(tr("Readback")); + fdScheTip->setText(tr("Default brightness tip")); +} + +bool CtrlBrightPanel::restoreScheduleJson(QJsonDocument &json, int max) { + tableSche->setRowCount(0); + auto taskBrightness = json["taskBrightness"]; + auto brightness = json["defaultBrightnessPercentage"].toInt(-1); + if(brightness==-1) brightness = qRound(taskBrightness["defaultBrightness"].toInt() * 100.0 / max); + fdDefBright->setValue(brightness); + auto jsitems = taskBrightness["items"].toArray(); + auto brightnesses = json["brightnessPercentageList"].toArray(); + for(int i=0; irowCount(); + tableSche->insertRow(row); + + auto cellWgt = new QWidget; + auto hBox = new QHBoxLayout(cellWgt); + + auto slider = new QSlider(Qt::Horizontal); + slider->setRange(1, 100); + if(brightnesses.size() > i) slider->setValue(brightnesses[i].toInt()); + else slider->setValue(qRound(jsitems.at(i)["brightness"].toInt() * 100.0 / max)); + hBox->addWidget(slider); + + auto lb = new QLabel(QString::number(slider->value())+"%"); + connect(slider, &QSlider::valueChanged, lb, [lb](int value) { + lb->setText(QString::number(value)+"%"); + }); + hBox->addWidget(lb); + tableSche->setCellWidget(row, "bright", cellWgt); + + auto timeEdit = new QTimeEdit(QTime::fromString(schedule["startTime"].toString(), "HH:mm")); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "start", timeEdit); + + timeEdit = new QTimeEdit(QTime::fromString(schedule["endTime"].toString(), "HH:mm")); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "end", timeEdit); + } + return jsitems.count() > 0; +} +void CtrlBrightPanel::getScheduleJson(QJsonObject &json, int max) { + QJsonArray items, brightnesses; + for(int i=0; irowCount(); i++) { + QJsonObject item; + auto brightness = static_cast(tableSche->cellWidget(i, "bright")->layout()->itemAt(0)->widget())->value(); + if(max==0) brightnesses.append(brightness); + else item.insert("brightness", (brightness * max + 50) / 100); + item.insert("schedules", QJsonArray{QJsonObject{ + {"timeType", "Range"}, + {"startTime", static_cast(tableSche->cellWidget(i, "start"))->text()}, + {"endTime", static_cast(tableSche->cellWidget(i, "end"))->text()}, + {"dateType", "All"}, + {"filterType", "None"}, + {"monthFilter", QJsonArray()}, + {"weekFilter", QJsonArray()} + }}); + items.append(item); + } + QJsonObject taskBrightness{ + {"createBy", "alahover"}, + {"name", "TimingBrightness"}, + {"items", items} + }; + if(max==0) { + json.insert("defaultBrightnessPercentage", fdDefBright->value()); + json.insert("brightnessPercentageList", brightnesses); + } else { + auto def = (fdDefBright->value() * max + 50) / 100; + taskBrightness.insert("defaultBrightness", def); + taskBrightness.insert("brightness", def); + } + json.insert("taskBrightness", taskBrightness); +} diff --git a/LedOK/wDevicesManager/ctrlbrightpanel.h b/LedOK/device/ctrlbrightpanel.h similarity index 86% rename from LedOK/wDevicesManager/ctrlbrightpanel.h rename to LedOK/device/ctrlbrightpanel.h index 86f70ed..b2c47ba 100644 --- a/LedOK/wDevicesManager/ctrlbrightpanel.h +++ b/LedOK/device/ctrlbrightpanel.h @@ -1,15 +1,12 @@ #ifndef CTRLBRIGHTPANEL_H #define CTRLBRIGHTPANEL_H -#include "ledcard.h" -#include "base/table.h" -#include +#include "gutil/qgui.h" #include #include #include +#include #include -#include -#include class CtrlBrightPanel : public QWidget { Q_OBJECT @@ -22,12 +19,13 @@ protected: void transUi(); private: - bool restoreScheduleJson(QJsonObject, int = 100); - QJsonObject getScheduleJson(int = 100); + bool restoreScheduleJson(QJsonDocument &, int); + void getScheduleJson(QJsonObject &, int); QLabel *lbBrightCfg; QRadioButton *radioAuto; QRadioButton *radioManual; QRadioButton *radioSchedule; + QCheckBox *fdAdaptToOld; char mSensi{-1}; char mTask{-1}; diff --git a/LedOK/device/ctrlhdmipanel.cpp b/LedOK/device/ctrlhdmipanel.cpp new file mode 100644 index 0000000..cc46580 --- /dev/null +++ b/LedOK/device/ctrlhdmipanel.cpp @@ -0,0 +1,424 @@ +#include "ctrlhdmipanel.h" +#include "gutil/qgui.h" +#include "tools.h" +#include "globaldefine.h" +#include "base/waitingdlg.h" +#include +#include +#include +#include + +CtrlHdmiPanel::CtrlHdmiPanel(QWidget *parent) : QWidget(parent) { + auto vBox = new QVBoxLayout(this); + lbHdmiCfg = new QLabel; + lbHdmiCfg->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbHdmiCfg); + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + auto hBox = new QHBoxLayout(); + hBox->addStretch(); + + fdManual = new QRadioButton; + hBox->addWidget(fdManual); + hBox->addSpacing(40); + + fdSchedule = new QRadioButton; + hBox->addWidget(fdSchedule); + hBox->addStretch(); + + vBox->addLayout(hBox); + + auto stacked = new QStackedLayout; + vBox->addLayout(stacked); + { + auto vBox = new VBox(stacked); + vBox->addSpacing(20); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + fdAsync = new QRadioButton; + hBox->addWidget(fdAsync); + hBox->addSpacing(20); + fdHdmi = new QRadioButton("HDMI"); + hBox->addWidget(fdHdmi); + hBox->addSpacing(20); + fdHdmi2 = new QRadioButton("HDMI 2"); + hBox->addWidget(fdHdmi2); + hBox->addStretch(); + + auto btnGroup = new QButtonGroup(this); + btnGroup->addButton(fdAsync, 0); + btnGroup->addButton(fdHdmi, 1); + btnGroup->addButton(fdHdmi2, 2); + connect(btnGroup, &QButtonGroup::idToggled, this, [this](int id, bool checked) { + if(! checked) return; + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SyncSwitch"); + json.insert("_type", "SyncSwitch"); + json.insert("switchOn", (bool)id); + if(id) json.insert("number", id); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, checked ? tr("SyncSwitch") : tr("AnSyncSwitch")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + if(checked){ + Def_CtrlSetMulti(tr("SyncSwitch")) + } else { + Def_CtrlSetMulti(tr("AnSyncSwitch")) + } + } + } + }); + + vBox->addSpacing(20); + + hBox = new HBox(vBox); + hBox->addStretch(); + btnGetSync = new QPushButton; + btnGetSync->setMinimumSize(60, 30); + btnGetSync->setProperty("ssType", "progManageTool"); + connect(btnGetSync, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "IsSync"); + json.insert("_type", "IsSync"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("IsSync")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + auto switchOn = json["switchOn"]; + if(switchOn.isUndefined()) switchOn = json["result"]; + if(! switchOn.toBool()) fdAsync->setChecked(true); + else if(json["number"].toInt()==2) fdHdmi2->setChecked(true); + else fdHdmi->setChecked(true); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + auto switchOn = json["switchOn"]; + if(switchOn.isUndefined()) switchOn = json["result"]; + if(! switchOn.toBool()) err = tr("Async"); + else { + err = "HDMI"; + auto number = json["number"].toInt(); + if(number) err += " "+QString::number(number); + } + } + gFdResInfo->append(cardId+" "+err); + }); + } + } + }); + hBox->addWidget(btnGetSync); + hBox->addStretch(); + + vBox->addStretch(); + } + { + auto vBox = new VBox(stacked); + auto hBox = new HBox(vBox); + hBox->setSpacing(10); + + tableSche = new Table({ + {"start", "", 100}, + {"end", "", 100}, + {"0", "", 60}, + {"1", "", 60}, + {"2", "", 60}, + {"3", "", 60}, + {"4", "", 60}, + {"5", "", 60}, + {"6", "", 60} + }); + tableSche->setDefs(); + tableSche->setStyleSheet("Table {selection-background-color: #8ce;}"); + + btnScheAdd = new QPushButton; + btnScheAdd->setMinimumSize(QSize(60, 30)); + btnScheAdd->setProperty("ssType", "progManageTool"); + connect(btnScheAdd, &QPushButton::clicked, this, [this] { + int row = tableSche->appendRow(); + auto timeEdit = new QTimeEdit(QTime(0, 0)); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "start", timeEdit); + + timeEdit = new QTimeEdit(QTime(1, 0)); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "end", timeEdit); + + for(int i=0; i<7; i++) { + auto fd = new QCheckBox; + fd->setChecked(true); + tableSche->setCellWidget(row, QString::number(i), fd); + } + }); + hBox->addWidget(btnScheAdd); + + btnScheDel = new QPushButton; + btnScheDel->setMinimumSize(QSize(60, 30)); + btnScheDel->setProperty("ssType", "progManageTool"); + connect(btnScheDel, &QPushButton::clicked, this, [this] { + auto selected = tableSche->selectedRanges(); + if(! selected.isEmpty()) tableSche->model()->removeRows(selected[0].topRow(), selected[0].rowCount()); + }); + hBox->addWidget(btnScheDel); + + btnScheClear = new QPushButton; + btnScheClear->setMinimumSize(QSize(60, 30)); + btnScheClear->setProperty("ssType", "progManageTool"); + connect(btnScheClear, &QPushButton::clicked, tableSche, &Table::clearRows); + hBox->addWidget(btnScheClear); + hBox->addStretch(); + + btnScheImport = new QPushButton; + btnScheImport->setMinimumSize(QSize(0, 30)); + btnScheImport->setProperty("ssType", "progManageTool"); + connect(btnScheImport, &QPushButton::clicked, this, [this] { + auto dir = QSettings().value("CtrlScheduleDir").toString(); + if(dir.isEmpty()) dir = "/"; + QString scheFile = QFileDialog::getOpenFileName(this, tr("Import File"), dir, tr("Sync Schedule")+" (*.syncs)"); + if(scheFile.isEmpty()) return; + QFile scheQFile(scheFile); + if(! scheQFile.open(QIODevice::ReadOnly)) return; + auto data = scheQFile.readAll(); + scheQFile.close(); + restoreScheduleJson(QJsonDocument::fromJson(data).object()); + }); + hBox->addWidget(btnScheImport); + + btnScheExport = new QPushButton; + btnScheExport->setMinimumSize(QSize(0, 30)); + btnScheExport->setProperty("ssType", "progManageTool"); + connect(btnScheExport, &QPushButton::clicked, this, [this] { + QSettings settings; + auto dir = settings.value("CtrlScheduleDir").toString(); + if(dir.isEmpty()) dir = "/"; + QString scheFile = QFileDialog::getSaveFileName(this, tr("Save File"), dir, tr("Sync Schedule")+" (*.syncs)"); + if(scheFile.isEmpty()) return; + settings.setValue("CtrlScheduleDir", QFileInfo(scheFile).absolutePath()); + QFile scheQFile(scheFile); + if(! scheQFile.open(QIODevice::WriteOnly)) return; + scheQFile.write(QJsonDocument(getScheduleJson()).toJson()); + scheQFile.close(); + }); + hBox->addWidget(btnScheExport); + + labelSyncScheduleTip = new QLabel; + labelSyncScheduleTip->setWordWrap(true); + vBox->addWidget(labelSyncScheduleTip); + + vBox->addWidget(tableSche); + + hBox = new HBox(vBox); + hBox->addStretch(); + + btnScheSet = new QPushButton; + btnScheSet->setProperty("ssType", "progManageTool"); + btnScheSet->setMinimumSize(QSize(60, 30)); + connect(btnScheSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetTimingHdmiInTask"); + json.insert("_type", "SetTimingHdmiInTask"); + if(gSelCards->count() == 1) { + json.insert("HdmiInTask", getScheduleJson()); + auto waitingDlg = new WaitingDlg(this, tr("SetTimingHdmiInTask")); + Def_CtrlReqPre; + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + json.insert("HdmiInTask", getScheduleJson()); + Def_CtrlSetMulti(tr("SetTimingHdmiInTask")) + } + } + }); + hBox->addWidget(btnScheSet); + hBox->addStretch(); + + btnScheGet = new QPushButton; + btnScheGet->setMinimumSize(QSize(0, 30)); + btnScheGet->setProperty("ssType", "progManageTool"); + connect(btnScheGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetTimingHdmiInTask"); + json.insert("_type", "GetTimingHdmiInTask"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetTimingHdmiInTask")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + restoreScheduleJson(json["creenTask"].toObject()); + }); + } + }); + hBox->addWidget(btnScheGet); + + hBox->addStretch(); + } + + auto m_buttonGroup = new QButtonGroup; + m_buttonGroup->addButton(fdManual, 0); + m_buttonGroup->addButton(fdSchedule, 1); + connect(m_buttonGroup,SIGNAL(buttonClicked(int)),stacked,SLOT(setCurrentIndex(int))); + fdManual->setChecked(true); + stacked->setCurrentIndex(0); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void CtrlHdmiPanel::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} + +void CtrlHdmiPanel::init() { + bool isSingle = gSelCards->count()==1; + btnScheGet->setEnabled(isSingle); + if(! isSingle) { + fdHdmi2->setVisible(true); + return; + } + auto card = gSelCards->at(0); + fdHdmi2->setVisible(card->m_strCardId.startsWith("m8s", Qt::CaseInsensitive)); + + QJsonObject json; + json.insert("_id", "IsSync"); + json.insert("_type", "IsSync"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + auto switchOn = json["switchOn"]; + if(switchOn.isUndefined()) switchOn = json["result"]; + if(! switchOn.toBool()) fdAsync->setChecked(true); + else if(json["number"].toInt()==2) fdHdmi2->setChecked(true); + else fdHdmi->setChecked(true); + }); +} +void CtrlHdmiPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void CtrlHdmiPanel::transUi() { + lbHdmiCfg->setText(tr("HDMI Configuration")); + fdManual->setText(tr("Manual")); + fdSchedule->setText(tr("Schedule")); + + fdAsync->setText(tr("Async")); + btnGetSync->setText(tr("Readback")); + + tableSche->setHeaderText("start", tr("Start Time")); + tableSche->setHeaderText("end", tr("End Time")); + tableSche->setHeaderText("0", tr("SUN")); + tableSche->setHeaderText("1", tr("MON")); + tableSche->setHeaderText("2", tr("TUE")); + tableSche->setHeaderText("3", tr("WED")); + tableSche->setHeaderText("4", tr("THU")); + tableSche->setHeaderText("5", tr("FRI")); + tableSche->setHeaderText("6", tr("SAT")); + + btnScheAdd->setText(tr("Add")); + btnScheSet->setText(tr("Apply")); + btnScheClear->setText(tr("Clear")); + btnScheDel->setText(tr("Delete")); + btnScheImport->setText(tr("Import")); + btnScheExport->setText(tr("Export")); + labelSyncScheduleTip->setText(tr("By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period")); + btnScheSet->setText(tr("Apply")); + btnScheGet->setText(tr("Readback")); +} + +void CtrlHdmiPanel::restoreScheduleJson(QJsonObject oTaskSync) { + tableSche->setRowCount(0); + auto oSchedules = oTaskSync["schedules"].toArray(); + foreach(auto oSchedule, oSchedules) { + int row = tableSche->rowCount(); + tableSche->insertRow(row); + + auto timeEdit = new QTimeEdit(QTime::fromString(oSchedule["startTime"].toString()+":00")); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "start", timeEdit); + + timeEdit = new QTimeEdit(QTime::fromString(oSchedule["endTime"].toString()+":00")); + timeEdit->setDisplayFormat("HH:mm"); + timeEdit->setAlignment(Qt::AlignCenter); + tableSche->setCellWidget(row, "end", timeEdit); + + if(oSchedule["filterType"].toString()=="None") for(int i=0; i<7; i++) { + auto fd = new QCheckBox; + fd->setChecked(true); + tableSche->setCellWidget(row, QString::number(i), fd); + } else if(oSchedule["filterType"].toString()=="Week") { + auto weekFilter = oSchedule["weekFilter"].toArray(); + for(int i=0; i<7; i++) { + auto fd = new QCheckBox; + if(weekFilter.contains(i)) fd->setChecked(true); + tableSche->setCellWidget(row, QString::number(i), fd); + } + } + } +} +QJsonObject CtrlHdmiPanel::getScheduleJson() { + QJsonArray schedules; + for(int i=0; irowCount(); i++) { + QJsonObject schedule; + schedule["timeType"] = "Range"; + schedule["startTime"] = static_cast(tableSche->cellWidget(i, "start"))->text(); + schedule["endTime"] = static_cast(tableSche->cellWidget(i, "end"))->text(); + schedule["dateType"] = "All"; + schedule["monthFilter"] = QJsonArray(); + QJsonArray weekFilter; + for(int d=0; d<7; d++) if(static_cast(tableSche->cellWidget(i, QString::number(d)))->isChecked()) weekFilter.append(d); + if(weekFilter.size()>=7) { + schedule["filterType"] = "None"; + weekFilter = QJsonArray(); + } else schedule["filterType"] = "Week"; + schedule["weekFilter"] = weekFilter; + schedules.append(schedule); + } + return QJsonObject{ + {"createBy", "alahover"}, + {"name", "TimingScreen"}, + {"schedules", schedules} + }; +} diff --git a/LedOK/device/ctrlhdmipanel.h b/LedOK/device/ctrlhdmipanel.h new file mode 100644 index 0000000..b70a007 --- /dev/null +++ b/LedOK/device/ctrlhdmipanel.h @@ -0,0 +1,38 @@ +#ifndef CTRLHDMIPANEL_H +#define CTRLHDMIPANEL_H + +#include "base/switchcontrol.h" +#include "gutil/qgui.h" +#include +#include +#include + +class CtrlHdmiPanel : public QWidget { + Q_OBJECT +public: + explicit CtrlHdmiPanel(QWidget *parent = nullptr); + void restoreScheduleJson(QJsonObject oTaskSync); + QJsonObject getScheduleJson(); +protected: + void showEvent(QShowEvent *event) override; + void init(); + void changeEvent(QEvent *) override; + void transUi(); + +private: + QLabel *lbHdmiCfg; + QRadioButton *fdManual, *fdSchedule, *fdAsync, *fdHdmi, *fdHdmi2; + QPushButton *btnGetSync; + + Table *tableSche; + QPushButton *btnScheAdd; + QPushButton *btnScheDel; + QPushButton *btnScheClear; + QPushButton *btnScheImport; + QPushButton *btnScheExport; + QLabel *labelSyncScheduleTip; + QPushButton *btnScheSet; + QPushButton *btnScheGet; +}; + +#endif // CTRLHDMIPANEL_H diff --git a/LedOK/device/ctrlnetworkpanel.cpp b/LedOK/device/ctrlnetworkpanel.cpp new file mode 100644 index 0000000..5602eda --- /dev/null +++ b/LedOK/device/ctrlnetworkpanel.cpp @@ -0,0 +1,1021 @@ +#include "ctrlnetworkpanel.h" +#include "base/waitingdlg.h" +#include "globaldefine.h" +#include "tools.h" +#include "gutil/qgui.h" +#include +#include +#include +#include + +CtrlNetworkPanel::CtrlNetworkPanel(QWidget *parent) : QWidget(parent) { + auto vBox = new VBox(this); + + lbLanCfg = new QLabel; + QFont font = lbLanCfg->font(); + font.setPointSize(12); + lbLanCfg->setFont(font); + lbLanCfg->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbLanCfg); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + fdDhcp = new QRadioButton; + fdDhcp->setChecked(true); + hBox->addWidget(fdDhcp, 0, Qt::AlignTop); + + hBox->addSpacing(30); + + auto vBoxSpecifyIp = new VBox(hBox); + vBoxSpecifyIp->setContentsMargins(0, 0, 0, 0); + + fdSpecifyIp = new QRadioButton; + vBoxSpecifyIp->addWidget(fdSpecifyIp, 0, Qt::AlignCenter); + + auto grp = new QButtonGroup(this); + grp->addButton(fdDhcp); + grp->addButton(fdSpecifyIp); + + gBoxSpecifyIp = new QGroupBox; + gBoxSpecifyIp->setMaximumWidth(340); + gBoxSpecifyIp->setVisible(false); + connect(fdSpecifyIp, &QRadioButton::toggled, gBoxSpecifyIp, &QWidget::setVisible); + { + auto vvv = new VBox(gBoxSpecifyIp); + auto hhh = new HBox(vvv); + + labelIpAddress = new QLabel; + hhh->addWidget(labelIpAddress); + + fdIP = new QIPLineEdit; + fdIP->setFixedWidth(160); + hhh->addWidget(fdIP); + + hhh = new HBox(vvv); + + labelMaskAddress = new QLabel; + hhh->addWidget(labelMaskAddress); + + fdMask = new QIPLineEdit; + fdMask->setFixedWidth(160); + hhh->addWidget(fdMask); + + hhh = new HBox(vvv); + + labelGateway = new QLabel; + hhh->addWidget(labelGateway); + + fdGateWay = new QIPLineEdit; + fdGateWay->setFixedWidth(160); + hhh->addWidget(fdGateWay); + + hhh = new HBox(vvv); + + labelDnsAddress = new QLabel; + hhh->addWidget(labelDnsAddress); + + fdDns = new QIPLineEdit; + fdDns->setFixedWidth(160); + hhh->addWidget(fdDns); + } + vBoxSpecifyIp->addWidget(gBoxSpecifyIp); + + hBox->addStretch(); + + hBox = new HBox(vBox); + hBox->addStretch(); + + btnLanSet = new QPushButton; + btnLanSet->setMinimumSize(QSize(60, 30)); + btnLanSet->setProperty("ssType", "progManageTool"); + connect(btnLanSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QString ip = fdIP->text(); + QString mask = fdMask->text(); + QString gateWay = fdGateWay->text(); + QString dns = fdDns->text(); + if(fdDhcp->isChecked()) { + if(ip=="...") ip="0.255.255.255"; + if(mask=="...") mask="0.255.255.255"; + if(gateWay=="...") gateWay="0.255.255.255"; + if(dns=="...") dns="0.255.255.255"; + } else { + if(ip=="...") { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input IP address!")); + fdIP->setFocus(); + return; + } + if(!isTextValid(ip)) { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Your IP Address is Invalid!")+"["+ip+"]"); + fdIP->setFocus(); + return; + } + if(mask=="...") { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input Mask address!")); + fdMask->setFocus(); + return; + } + if(!isTextValid(mask)) { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Your Mask Address is Invalid!")); + fdMask->setFocus(); + return; + } + if(gateWay=="...") { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input Gateway address!")); + fdGateWay->setFocus(); + return; + } + if(!isTextValid(gateWay)) { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Your Gateway Address is Invalid!")); + fdGateWay->setFocus(); + return; + } + if(dns=="...") { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input DNS address!")); + fdDns->setFocus(); + return; + } + if (!isTextValid(dns)) { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Your DNS Address is Invalid!")); + fdDns->setFocus(); + return; + } + } + QJsonObject json; + json.insert("_id", "SetEthernet"); + json.insert("_type", "SetEthernet"); + json.insert("dhcp", fdDhcp->isChecked()); + json.insert("ip", ip); + json.insert("netMask", mask); + json.insert("gateWay", gateWay); + json.insert("dns", dns); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetEthernet")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetEthernet")) + } + } + }); + hBox->addWidget(btnLanSet); + + hBox->addSpacing(50); + + btnLanGet = new QPushButton; + btnLanGet->setMinimumSize(QSize(60, 30)); + btnLanGet->setProperty("ssType", "progManageTool"); + connect(btnLanGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetEthernet"); + json.insert("_type", "GetEthernet"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetEthernet")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + if(json["dhcp"].toBool()) { + fdDhcp->setChecked(true); + gBoxSpecifyIp->setVisible(false); + } else { + fdSpecifyIp->setChecked(true); + gBoxSpecifyIp->setVisible(true); + } + fdIP->setText(json["ipAddr"].toString()); + fdMask->setText(json["netMask"].toString()); + fdGateWay->setText(json["gateWay"].toString()); + fdDns->setText(json["dnsAddr"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["dhcp"].toBool() ? tr("DHCP IP") : tr("STATIC IP"); + gFdResInfo->append(cardId+" "+tr("GetEthernet")+" "+err); + gFdResInfo->append(" IP: "+json["ipAddr"].toString()); + gFdResInfo->append(" Mask: "+json["netMask"].toString()); + gFdResInfo->append(" GateWay: "+json["gateWay"].toString()); + gFdResInfo->append(" Dns: "+json["dnsAddr"].toString()); + }); + } + } + }); + hBox->addWidget(btnLanGet); + + hBox->addStretch(); + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + label_5 = new QLabel; + label_5->setFont(font); + label_5->setAlignment(Qt::AlignCenter); + vBox->addWidget(label_5); + + hBox = new HBox(vBox); + hBox->addStretch(); + + auto stackedWifi = new QStackedLayout; + fdIsWifi = new QRadioButton; + connect(fdIsWifi, &QRadioButton::toggled, this, [stackedWifi](bool checked) { + stackedWifi->setCurrentIndex(checked ? 0 : 1); + }); + hBox->addWidget(fdIsWifi); + hBox->addSpacing(50); + + fdIsHotspot = new QRadioButton; + hBox->addWidget(fdIsHotspot); + hBox->addStretch(); + + vBox->addLayout(stackedWifi); + { + auto vvv = new VBox(stackedWifi); + hBox = new HBox(vvv); + + lbWifiName = new QLabel; + lbWifiName->setMinimumWidth(80); + hBox->addWidget(lbWifiName); + + fdWifiName = new QComboBox; + fdWifiName->setEditable(true); + fdWifiName->setMinimumWidth(200); + fdWifiName->setSizeAdjustPolicy(QComboBox::AdjustToContents); + hBox->addWidget(fdWifiName); + + btnScan = new QPushButton; + btnScan->setMinimumWidth(60); + btnScan->setProperty("ssType", "progManageTool"); + connect(btnScan, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetWifiList"); + json.insert("_type", "GetWifiList"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetWifiList")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + auto wifis = json["wifiList"].toArray(); + auto cur = fdWifiName->currentText(); + fdWifiName->clear(); + foreach(auto wifi, wifis) fdWifiName->addItem(QIcon(":/res/signal-"+QString::number((wifi["signal"].toInt()+19)/20)+".png"), wifi["ssid"].toString()); + if(! cur.isEmpty()) fdWifiName->setCurrentText(cur); + }); + } + }); + hBox->addWidget(btnScan); + hBox->addStretch(); + + hBox = new HBox(vvv); + + lbWifiPassword = new QLabel; + lbWifiPassword->setMinimumWidth(80); + hBox->addWidget(lbWifiPassword); + + fdWifiPassword = new QLineEdit; + fdWifiPassword->setFixedWidth(200); + fdWifiPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit); + hBox->addWidget(fdWifiPassword); + hBox->addStretch(); + + vvv->addStretch(); + + vvv = new VBox(stackedWifi); + hBox = new HBox(vvv); + + lbHotspotName = new QLabel; + lbHotspotName->setMinimumWidth(80); + hBox->addWidget(lbHotspotName); + + fdHotspotName = new QLineEdit; + fdHotspotName->setFixedWidth(200); + hBox->addWidget(fdHotspotName); + hBox->addStretch(); + + hBox = new HBox(vvv); + + lbHotspotPassword = new QLabel; + lbHotspotPassword->setMinimumWidth(80); + hBox->addWidget(lbHotspotPassword); + + fdHotspotPassword = new QLineEdit; + fdHotspotPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit); + fdHotspotPassword->setFixedWidth(200); + hBox->addWidget(fdHotspotPassword); + hBox->addStretch(); + + vvv->addStretch(); + } + fdIsWifi->setChecked(true); + + hBox = new HBox(vBox); + hBox->addStretch(); + + btnWiFiSet = new QPushButton; + btnWiFiSet->setMinimumSize(QSize(60, 30)); + btnWiFiSet->setProperty("ssType", "progManageTool"); + connect(btnWiFiSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + if(fdIsWifi->isChecked()) { + QJsonObject json; + json.insert("_id", "ConfigurationWiFi"); + json.insert("_type", "ConfigurationWiFi"); + json.insert("ssid", fdWifiName->currentText()); + json.insert("password", fdWifiPassword->text()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("ConfigurationWiFi")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("ConfigurationWiFi")) + } + } + } else if(fdIsHotspot->isChecked()) { + QJsonObject json; + json.insert("_id", "ConfigurationHotSpot"); + json.insert("_type", "ConfigurationHotSpot"); + json.insert("apName", fdHotspotName->text()); + json.insert("password", fdHotspotPassword->text()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("ConfigurationHotSpot")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("ConfigurationHotSpot")) + } + } + } + }); + hBox->addWidget(btnWiFiSet); + hBox->addSpacing(50); + + btnWiFiGet = new QPushButton; + btnWiFiGet->setMinimumSize(QSize(60, 30)); + btnWiFiGet->setProperty("ssType", "progManageTool"); + connect(btnWiFiGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "IsPortableHotSpot"); + json.insert("_type", "IsPortableHotSpot"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("IsPortableHotSpot")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdWifiName->setCurrentText(json["wifi"].toString()); + auto hotSpots = json["hotSpots"].toString(); + fdHotspotName->setText(hotSpots); + if(hotSpots.isEmpty()) fdIsWifi->setChecked(true); + else fdIsHotspot->setChecked(true); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + err = tr("success"); + auto wifi = json["wifi"].toString(); + if(! wifi.isEmpty()) err += " "+tr("WifiName")+":"+wifi; + auto hotSpots = json["hotSpots"].toString(); + if(! hotSpots.isEmpty()) err += " "+tr("ApName")+":"+hotSpots; + } + gFdResInfo->append(cardId+" "+tr("IsPortableHotSpot")+" "+err); + }); + } + } + }); + hBox->addWidget(btnWiFiGet); + + hBox->addStretch(); + + + line_3 = new QFrame; + line_3->setFrameShape(QFrame::HLine); + line_3->setFrameShadow(QFrame::Sunken); + + vBox->addWidget(line_3); + + lbCellularConfig = new QLabel; + lbCellularConfig->setFont(font); + + vBox->addWidget(lbCellularConfig, 0, Qt::AlignHCenter); + + hBox = new HBox(vBox); + + fdEnableCellular = new QCheckBox; + fdEnableCellular->setChecked(true); + connect(fdEnableCellular, &QCheckBox::toggled, this, [=](bool checked) { + groupApn->setEnabled(checked); + fdMcc->setEnabled(checked); + fdCarrierName->setEnabled(checked); + + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetSwitchSimData"); + json.insert("_type", "SetSwitchSimData"); + json.insert("enable", checked); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetSwitchSimData")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetSwitchSimData")) + } + } + }); + hBox->addWidget(fdEnableCellular); + + btnSIMStatusGet = new QPushButton; + btnSIMStatusGet->setMinimumHeight(30); + btnSIMStatusGet->setProperty("ssType", "progManageTool"); + connect(btnSIMStatusGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetSIMStatus"); + json.insert("_type", "GetSIMStatus"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetSIMStatus")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->close(); + QString str4GStatus = tr("状态:"); + auto state = json["state"].toInt(); + if(state<2) str4GStatus += tr("未知"); + else if(state==2) str4GStatus += tr("锁定状态,需要用户的PIN码解锁"); + else if(state==3) str4GStatus += tr("锁定状态,需要用户的PUK码解锁"); + else if(state==4) str4GStatus += tr("锁定状态,需要网络的PIN码解锁"); + else if(state==5) str4GStatus += tr("就绪"); + auto imsi = json["imsi"].toString(); + if(imsi.isEmpty()) str4GStatus += "\n"+tr("no checked sim card"); + else { + str4GStatus += "\nIMSI: "+imsi+"\n"; + fdMcc->setCurrentText(imsi.left(3)); + str4GStatus += tr("国家码:") + json["countryCode"].toString() + "(" + imsi.left(3) + ")\n"; + str4GStatus += tr("号码:") + json["phoneNumber"].toString() + "\n"; + str4GStatus += tr("用户:") + json["user"].toString() + "\n"; + str4GStatus += tr("信号:"); + switch(json["serviceState"].toInt()) { + case 0: str4GStatus+=tr("信号正常")+"\r\n"; break; + case 1: str4GStatus+=tr("不在服务区")+"\r\n"; break; + case 2: str4GStatus+=tr("仅限紧急呼叫")+"\r\n"; break; + case 3: str4GStatus+=tr("射频已经关闭")+"\r\n"; break; + } + str4GStatus += tr("网络:"); + switch(json["networkType"].toInt()) { + case 0: str4GStatus+=tr("网络类型未知")+"\r\n"; break; + case 1: str4GStatus+=tr("GPRS网络")+"\r\n"; break; + case 2: str4GStatus+=tr("EDGE网络")+"\r\n"; break; + case 3: str4GStatus+=tr("UMTS网络")+"\r\n"; break; + case 4: str4GStatus+=tr("CDMA网络,IS95A 或 IS95B.")+"\r\n"; break; + case 5: str4GStatus+=tr("EVDO网络, revision 0.")+"\r\n"; break; + case 6: str4GStatus+=tr("EVDO网络, revision A.")+"\r\n"; break; + case 7: str4GStatus+=tr("1xRTT网络")+"\r\n"; break; + case 8: str4GStatus+=tr("HSDPA网络")+"\r\n"; break; + case 9: str4GStatus+=tr("HSUPA网络")+"\r\n"; break; + case 10: str4GStatus+=tr("HSPA网络")+"\r\n"; break; + } + str4GStatus += tr("漫游:") + (json["roaming"].toBool() ? tr("Yes") : tr("No")) + "\n"; + str4GStatus += tr("数据连接状态:"); + switch(json["dataState"].toInt()) { + case 0: str4GStatus+=tr("断开")+"\r\n"; break; + case 1: str4GStatus+=tr("正在连接")+"\r\n"; break; + case 2: str4GStatus+=tr("已连接")+"\r\n"; break; + case 3: str4GStatus+=tr("暂停")+"\r\n"; break; + } + str4GStatus += tr("数据活动休眠状态:"); + switch(json["dataActivity"].toInt()) { + case 0: str4GStatus+=tr("活动,但无数据发送和接收")+"\r\n"; break; + case 1: str4GStatus+=tr("活动,正在接收数据")+"\r\n"; break; + case 2: str4GStatus+=tr("活动,正在发送数据")+"\r\n"; break; + case 3: str4GStatus+=tr("活动,正在接收和发送数据")+"\r\n"; break; + case 4: str4GStatus+=tr("休眠状态")+"\r\n"; break; + } + str4GStatus += tr("信号强度:") + QString::number(json["signalStrength"].toInt())+"\n"; + } + QMessageBox::information(gMainWin, tr("Tip"), str4GStatus); + }); + } + }); + hBox->addWidget(btnSIMStatusGet); + hBox->addStretch(); + + groupApn = new QGroupBox; + vBox->addWidget(groupApn); + auto vvv = new VBox(groupApn); + + lbCheckStatusTip = new QLabel(groupApn); + lbCheckStatusTip->setWordWrap(true); + vvv->addWidget(lbCheckStatusTip); + + hBox = new HBox(vvv); + + label_2 = new QLabel(groupApn); + hBox->addWidget(label_2); + + fdMcc = new QComboBox; + fdMcc->setMinimumWidth(80); + fdMcc->setEditable(true); + connect(fdMcc, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [=](int index) { + if(index < 1) return; + fdCarrierName->clear(); + fdCarrierName->addItem(""); + auto apnInfos = fdMcc->itemData(index).toJsonArray(); + foreach(auto apnInfo, apnInfos) fdCarrierName->addItem(apnInfo["carrier"].toString(), apnInfo); + }); + hBox->addWidget(fdMcc); + + hBox->addWidget(new QLabel("->")); + + label_3 = new QLabel(groupApn); + hBox->addWidget(label_3); + + fdCarrierName = new QComboBox; + fdCarrierName->setMinimumSize(QSize(200, 0)); + fdCarrierName->setEditable(true); + connect(fdCarrierName, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [=](int index) { + if(index < 1) return; + auto json = fdCarrierName->itemData(index).toJsonObject(); + fdCus_Name->setText(json["carrier"].toString()); + fdCus_apn->setText(json["apn"].toString()); + fdCus_User->setText(json["user"].toString()); + fdCus_pwd->setText(json["password"].toString()); + fdCus_type->setText(json["type"].toString()); + fdCus_server->setText(json["server"].toString()); + fdCus_proxy->setText(json["proxy"].toString()); + fdCus_port->setText(json["port"].toString()); + fdCus_mmsc->setText(json["mmsc"].toString()); + fdCus_mmsProxy->setText(json["mmsproxy"].toString()); + fdCus_mmsPort->setText(json["mmsport"].toString()); + }); + hBox->addWidget(fdCarrierName); + + hBox->addStretch(); + + hBox = new HBox(vvv); + hBox->addStretch(); + + auto grid = new QGridLayout(); + hBox->addLayout(grid); + + auto label = new QLabel("APN"); + label->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(label, 0, 0); + grid->addWidget(lbCus_Name = new QLabel, 1, 0); + lbCus_Name->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_User = new QLabel, 2, 0); + lbCus_User->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_pwd = new QLabel, 3, 0); + lbCus_pwd->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_type = new QLabel, 4, 0); + lbCus_type->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_server = new QLabel, 5, 0); + lbCus_server->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_port = new QLabel, 0, 2); + lbCus_port->setMinimumWidth(80); + lbCus_port->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_proxy = new QLabel, 1, 2); + lbCus_proxy->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(label = new QLabel("mmsc"), 2, 2); + label->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_mmsPort = new QLabel, 3, 2); + lbCus_mmsPort->setAlignment((Qt::Alignment)AlignRight); + grid->addWidget(lbCus_mmsProxy = new QLabel, 4, 2); + lbCus_mmsProxy->setAlignment((Qt::Alignment)AlignRight); + + fdCus_apn = new QLineEdit; + fdCus_Name = new QLineEdit; + fdCus_User = new QLineEdit; + fdCus_pwd = new QLineEdit; + fdCus_type = new QLineEdit; + fdCus_server = new QLineEdit; + fdCus_port = new QLineEdit; + fdCus_proxy = new QLineEdit; + fdCus_mmsc = new QLineEdit; + fdCus_mmsPort = new QLineEdit; + fdCus_mmsProxy = new QLineEdit; + + fdCus_apn->setMinimumWidth(260); + fdCus_port->setMinimumWidth(260); + grid->addWidget(fdCus_apn, 0, 1); + grid->addWidget(fdCus_Name, 1, 1); + grid->addWidget(fdCus_User, 2, 1); + grid->addWidget(fdCus_pwd, 3, 1); + grid->addWidget(fdCus_type, 4, 1); + grid->addWidget(fdCus_server, 5, 1); + grid->addWidget(fdCus_port, 0, 3); + grid->addWidget(fdCus_proxy, 1, 3); + grid->addWidget(fdCus_mmsc, 2, 3); + grid->addWidget(fdCus_mmsPort, 3, 3); + grid->addWidget(fdCus_mmsProxy, 4, 3); + + auto hhhh = new HBox; + btnAPNCusSet = new QPushButton; + btnAPNCusSet->setMinimumSize(QSize(60, 30)); + btnAPNCusSet->setProperty("ssType", "progManageTool"); + connect(btnAPNCusSet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetAPN"); + json.insert("_type", "SetAPN"); + json.insert("carrier", fdCus_Name->text()); + json.insert("apn", fdCus_apn->text()); + json.insert("user", fdCus_User->text()); + json.insert("password", fdCus_pwd->text()); + json.insert("type", fdCus_type->text()); + json.insert("server", fdCus_server->text()); + json.insert("proxy", fdCus_proxy->text()); + json.insert("port", fdCus_port->text()); + json.insert("mmsc", fdCus_mmsc->text()); + json.insert("mmsproxy", fdCus_mmsProxy->text()); + json.insert("mmsport", fdCus_mmsPort->text()); + + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetAPN")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [=] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetAPN")) + } + } + }); + hhhh->addWidget(btnAPNCusSet); + hhhh->addStretch(); + + btnAPNCusGet = new QPushButton; + btnAPNCusGet->setMinimumSize(QSize(60, 30)); + btnAPNCusGet->setProperty("ssType", "progManageTool"); + connect(btnAPNCusGet, &QPushButton::clicked, this, [=] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetCurrentAPN"); + json.insert("_type", "GetCurrentAPN"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetCurrentAPN")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [=] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdCus_Name->setText(json["carrier"].toString()); + fdCus_apn->setText(json["apn"].toString()); + fdCus_User->setText(json["user"].toString()); + fdCus_pwd->setText(json["password"].toString()); + fdCus_type->setText(json["type"].toString()); + fdCus_server->setText(json["server"].toString()); + fdCus_proxy->setText(json["proxy"].toString()); + fdCus_port->setText(json["port"].toString()); + fdCus_mmsc->setText(json["mmsc"].toString()); + fdCus_mmsProxy->setText(json["mmsproxy"].toString()); + fdCus_mmsPort->setText(json["mmsport"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + err = json["apn"].toString(); + auto user = json["user"].toString(); + if(! user.isEmpty()) err += ", User:"+user+", Password:"+json["password"].toString(); + } + gFdResInfo->append(cardId+" "+tr("GetCurrentAPN")+" "+err); + }); + } + } + }); + hhhh->addWidget(btnAPNCusGet); + + grid->addLayout(hhhh, 5, 3); + + hBox->addStretch(); + + + vBox->addSpacing(20); + + hBox = new HBox(vBox); + hBox->setContentsMargins(-1, 0, 10, -1); + label_10 = new QLabel; + + hBox->addWidget(label_10); + + fdFightModel = new SwitchControl; + fdFightModel->setMinimumSize(QSize(80, 35)); + fdFightModel->setSliderColor(QColor(0, 0, 0),QColor(0, 160, 230)); + fdFightModel->setBgColor(QColor(200,200,200),QColor(0,200,0)); + fdFightModel->setTextColor(QColor(100,100,100),QColor(0, 160, 230)); + fdFightModel->setText(tr("OFF"), tr("ON")); + connect(fdFightModel, &SwitchControl::checkedChanged, this, [=](bool checked) { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "ContrFlightMode"); + json.insert("_type", "ContrFlightMode"); + json.insert("state", checked); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("ContrFlightMode")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("ContrFlightMode")) + } + } + }); + hBox->addWidget(fdFightModel); + + btnFlightModelGet = new QPushButton; + btnFlightModelGet->setMinimumSize(QSize(0, 30)); + btnFlightModelGet->setProperty("ssType", "progManageTool"); + connect(btnFlightModelGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetFlightModeState"); + json.insert("_type", "GetFlightModeState"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetFlightModeState")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdFightModel->setCheckedStatus(json["result"].toBool()); + fdFightModel->update(); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["result"].toBool() ? "true" : "false"; + gFdResInfo->append(cardId+" "+tr("GetFlightModeState")+" "+err); + }); + } + } + }); + hBox->addWidget(btnFlightModelGet); + hBox->addStretch(); + + vBox->addStretch(); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void CtrlNetworkPanel::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void CtrlNetworkPanel::init() { + bool isSingle = gSelCards->count()==1; + btnScan->setEnabled(isSingle); + + if(! isSingle) return; + auto card = gSelCards->at(0); + + QJsonObject json; + json.insert("_id", "GetEthernet"); + json.insert("_type", "GetEthernet"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + + if(json["dhcp"].toBool()) { + fdDhcp->setChecked(true); + gBoxSpecifyIp->setVisible(false); + } else { + fdSpecifyIp->setChecked(true); + gBoxSpecifyIp->setVisible(true); + } + fdIP->setText(json["ipAddr"].toString()); + fdGateWay->setText(json["gateWay"].toString()); + fdMask->setText(json["netMask"].toString()); + fdDns->setText(json["dnsAddr"].toString()); + }); + + json = QJsonObject(); + json.insert("_id", "GetWifiList"); + json.insert("_type", "GetWifiList"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + auto wifis = json["wifiList"].toArray(); + fdWifiName->clear(); + foreach(auto wifi, wifis) fdWifiName->addItem(QIcon(":/res/signal-"+QString::number((wifi["signal"].toInt()+19)/20)+".png"), wifi["ssid"].toString()); + { + QJsonObject json; + json.insert("_id", "IsPortableHotSpot"); + json.insert("_type", "IsPortableHotSpot"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + auto wifi = json["wifi"].toString(); + fdWifiName->setCurrentText(wifi); + auto hotSpots = json["hotSpots"].toString(); + fdHotspotName->setText(hotSpots); + if(hotSpots.isEmpty()) fdIsWifi->setChecked(true); + else fdIsHotspot->setChecked(true); + }); + } + }); + + json = QJsonObject(); + json.insert("_id", "GetSwitchSimData"); + json.insert("_type", "GetSwitchSimData"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + bool b = json["enable"].toBool(); + fdEnableCellular->setChecked(b); + fdMcc->setEnabled(b); + fdCarrierName->setEnabled(b); + }); + + json = QJsonObject(); + json.insert("_id", "GetAPNList"); + json.insert("_type", "GetAPNList"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdMcc->clear(); + fdMcc->addItem(""); + auto apns = json["apns"].toArray(); + foreach(auto apn, apns) { + QString mcc = apn["mcc"].toString(); + for(int i=0; icount(); i++) if(mcc==fdMcc->itemText(i)) { + auto var = fdMcc->itemData(i); + fdMcc->setItemData(i, QVariant()); + ((QJsonArray *)var.data())->append(apn); + fdMcc->setItemData(i, var); + goto end; + } + fdMcc->addItem(mcc, QJsonArray{apn}); + end:; + } + }); + + getCurrentAPN(card->m_strCardIp); + + json = QJsonObject(); + json.insert("_id", "GetFlightModeState"); + json.insert("_type", "GetFlightModeState"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdFightModel->setCheckedStatus(json["result"].toBool()); + fdFightModel->update(); + }); +} + +void CtrlNetworkPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void CtrlNetworkPanel::transUi() { + lbLanCfg->setText(tr("Wire Enther(RJ45) Configuration")); + fdDhcp->setText(tr("DHCP")); + fdSpecifyIp->setText(tr("Specify IP")); + lbHotspotName->setText(tr("AP name")); + labelGateway->setText(tr("Gateway")); + lbWifiName->setText(tr("WiFi name")); + labelIpAddress->setText(tr("IP Address")); + lbHotspotPassword->setText(tr("Password")); + labelDnsAddress->setText(tr("DNS Address")); + labelMaskAddress->setText(tr("Subnet mask")); + lbWifiPassword->setText(tr("Password")); + btnScan->setText(tr("Scan")); + btnWiFiSet->setText(tr("Set")); + btnLanSet->setText(tr("Set")); + btnWiFiGet->setText(tr("Readback")); + btnLanGet->setText(tr("Readback")); + fdIsWifi->setText(tr("WiFi Mode")); + fdIsHotspot->setText(tr("Ap Mode")); + label_5->setText(tr("WIFI Configuration")); + fdHotspotPassword->setPlaceholderText(tr("Input password")); + fdWifiPassword->setPlaceholderText(tr("Input password")); + fdHotspotName->setPlaceholderText(tr("Input ap name")); + lbCellularConfig->setText(tr("Cellular Config")); + lbCheckStatusTip->setText(tr("Through the check status button")); + fdEnableCellular->setText(tr("Enable Cellular Data")); + + groupApn->setTitle(tr("Set APN Info")); + label_2->setText(tr("Country ID(mcc):")); + label_3->setText(tr("Carrier Name")); + fdCus_apn->setPlaceholderText(tr("APN(Required)")); + btnFlightModelGet->setText(tr("Readback")); + btnSIMStatusGet->setText(tr("Get cellular network status information")); + label_10->setText(tr("Flight Mode")); + + lbCus_Name->setText(tr("Carrier Name")); + lbCus_User->setText(tr("User")); + lbCus_pwd->setText(tr("Password")); + lbCus_type->setText(tr("Type")); + lbCus_server->setText(tr("Server")); + lbCus_port->setText(tr("Port")); + lbCus_proxy->setText(tr("Proxy")); + lbCus_mmsPort->setText(tr("MMS Port")); + lbCus_mmsProxy->setText(tr("MMS Proxy")); + btnAPNCusSet->setText(tr("Set")); + btnAPNCusGet->setText(tr("Readback")); +} + +void CtrlNetworkPanel::getCurrentAPN(QString &ip) { + QJsonObject json; + json.insert("_id", "GetCurrentAPN"); + json.insert("_type", "GetCurrentAPN"); + auto reply = Tools::netManager().post(reqForJson("http://"+ip+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdCus_Name->setText(json["carrier"].toString()); + fdCus_apn->setText(json["apn"].toString()); + fdCus_User->setText(json["user"].toString()); + fdCus_pwd->setText(json["password"].toString()); + fdCus_type->setText(json["type"].toString()); + fdCus_server->setText(json["server"].toString()); + fdCus_proxy->setText(json["proxy"].toString()); + fdCus_port->setText(json["port"].toString()); + fdCus_mmsc->setText(json["mmsc"].toString()); + fdCus_mmsProxy->setText(json["mmsproxy"].toString()); + fdCus_mmsPort->setText(json["mmsport"].toString()); + }); +} diff --git a/LedOK/device/ctrlnetworkpanel.h b/LedOK/device/ctrlnetworkpanel.h new file mode 100644 index 0000000..315e31b --- /dev/null +++ b/LedOK/device/ctrlnetworkpanel.h @@ -0,0 +1,88 @@ +#ifndef CTRLNETWORKPANEL_H +#define CTRLNETWORKPANEL_H + +#include +#include +#include +#include "base/qiplineedit.h" +#include "base/switchcontrol.h" +#include +#include +#include +#include +#include + +struct ApnInfo { + QString apn; + QString carrier; + QString mcc; + QString mmsc; + QString mmsport; + QString mmsproxy; + QString mnc; + QString password; + QString port; + QString proxy; + QString server; + QString type; + QString user; +}; +class CtrlNetworkPanel : public QWidget { + Q_OBJECT +public: + explicit CtrlNetworkPanel(QWidget *parent = nullptr); + void getCurrentAPN(QString &); +protected: + void showEvent(QShowEvent *event) override; + void init(); + void changeEvent(QEvent *) override; + void transUi(); + +private: + QLabel *lbLanCfg; + QRadioButton *fdDhcp, *fdSpecifyIp; + QGroupBox *gBoxSpecifyIp; + QLabel *labelIpAddress; + QIPLineEdit *fdIP; + QLabel *labelMaskAddress; + QIPLineEdit *fdGateWay; + QLabel *labelGateway; + QIPLineEdit *fdMask; + QLabel *labelDnsAddress; + QIPLineEdit *fdDns; + QPushButton *btnLanSet; + QPushButton *btnLanGet; + QLabel *label_5; + QLabel *lbWifiName; + QLabel *lbWifiPassword; + + QRadioButton *fdIsWifi, *fdIsHotspot; + QComboBox *fdWifiName; + QLineEdit *fdWifiPassword; + QPushButton *btnScan; + QPushButton *btnWiFiSet; + QPushButton *btnWiFiGet; + QLabel *lbHotspotName; + QLabel *lbHotspotPassword; + QLineEdit *fdHotspotName; + QLineEdit *fdHotspotPassword; + QFrame *line_3; + QLabel *lbCellularConfig; + QCheckBox *fdEnableCellular; + QPushButton *btnSIMStatusGet; + QGroupBox *groupApn; + QLabel *lbCheckStatusTip; + QLabel *label_2; + QComboBox *fdMcc; + QLabel *label_3; + QComboBox *fdCarrierName; + QPushButton *btnAPNCusSet, *btnAPNCusGet; + QLabel *label_10; + SwitchControl *fdFightModel; + QPushButton *btnFlightModelGet; + + QLabel *lbCus_Name, *lbCus_User, *lbCus_pwd, *lbCus_mmsPort, *lbCus_mmsProxy, *lbCus_port, *lbCus_proxy, *lbCus_server, *lbCus_type; + QLineEdit *fdCus_apn, *fdCus_Name, *fdCus_User, *fdCus_pwd, *fdCus_type, *fdCus_server, *fdCus_port, *fdCus_proxy, *fdCus_mmsc, *fdCus_mmsPort, *fdCus_mmsProxy; +}; + +#endif // CTRLNETWORKPANEL_H diff --git a/LedOK/device/ctrlpwdpanel.cpp b/LedOK/device/ctrlpwdpanel.cpp new file mode 100644 index 0000000..6ea7bff --- /dev/null +++ b/LedOK/device/ctrlpwdpanel.cpp @@ -0,0 +1,253 @@ +#include "ctrlpwdpanel.h" +#include "gutil/qgui.h" +#include "base/waitingdlg.h" +#include "QFileDialog" +#include +#include +#include +#include "tools.h" + +CtrlPwdPanel::CtrlPwdPanel(QWidget *parent) : QWidget(parent) { + auto vBox = new VBox(this); + lbPwdConfig = new QLabel; + lbPwdConfig->setAlignment(Qt::AlignCenter); + vBox->addWidget(lbPwdConfig); + vBox->addSpacing(20); + + auto grid = new Grid(vBox); + grid->setColumnStretch(0, 1); + grid->setColumnStretch(3, 1); + + lbOldPwd = new QLabel; + grid->addWidget(lbOldPwd, 0, 1); + + lbNewPwd = new QLabel; + grid->addWidget(lbNewPwd, 1, 1); + + lbPwdAgain = new QLabel; + grid->addWidget(lbPwdAgain, 2, 1); + + fdOldPwd = new QLineEdit; + fdOldPwd->setFixedSize(160, 30); + fdOldPwd->setEchoMode(QLineEdit::PasswordEchoOnEdit); + grid->addWidget(fdOldPwd, 0, 2); + + fdNewPwd = new QLineEdit; + fdNewPwd->setFixedSize(160, 30); + fdNewPwd->setEchoMode(QLineEdit::PasswordEchoOnEdit); + grid->addWidget(fdNewPwd, 1, 2); + + fdPwdAgain = new QLineEdit; + fdPwdAgain->setFixedSize(160, 30); + fdPwdAgain->setEchoMode(QLineEdit::PasswordEchoOnEdit); + grid->addWidget(fdPwdAgain, 2, 2); + + vBox->addSpacing(20); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + btnPwdSet = new QPushButton; + btnPwdSet->setMinimumSize(60, 30); + btnPwdSet->setProperty("ssType", "progManageTool"); + connect(btnPwdSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + if(fdOldPwd->isVisible() && fdOldPwd->text().isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("InputOriginalPasswordTip")); + return; + } + if(fdNewPwd->text().isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("InputNewPasswordTip")); + return; + } + if(fdPwdAgain->text().isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("InputRepeatPasswordTip")); + return; + } + if(fdNewPwd->text() != fdPwdAgain->text()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("InputRepeatPasswordNotSameTip")); + return; + } + auto res = QMessageBox::information(gMainWin, tr("Tip Info"), tr("After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation?"), QMessageBox::Ok, QMessageBox::Cancel); + if(res != QMessageBox::Ok) return; + QJsonObject json; + json.insert("_id", "SetControllerPassword"); + json.insert("_type", "SetControllerPassword"); + json.insert("pwd", fdOldPwd->text()); + json.insert("newPwd", fdNewPwd->text()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetControllerPassword")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, card, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + if(json["result"].toInt()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), tr("OriginalPasswordErrorTip")); + return; + } + waitingDlg->success(); + lbOldPwd->show(); + fdOldPwd->show(); + btnPwdClear->show(); + btnPwdSet->setText(tr("Modify password")); + card->bPassword = true; + fdNewPwd->clear(); + fdPwdAgain->clear(); + fdOldPwd->clear(); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, card, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + if(json["result"].toInt()) err = tr("OriginalPasswordErrorTip"); + else { + err = tr("Success"); + lbOldPwd->show(); + fdOldPwd->show(); + btnPwdClear->show(); + btnPwdSet->setText(tr("Modify password")); + card->bPassword = true; + } + } + gFdResInfo->append(card->m_strCardId+" "+tr("SetControllerPassword")+" "+err); + }); + } + } + }); + hBox->addWidget(btnPwdSet); + + btnPwdClear = new QPushButton; + btnPwdClear->setMinimumSize(60, 30); + btnPwdClear->setProperty("ssType", "progManageTool"); + connect(btnPwdClear, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + if(fdOldPwd->isVisible() && fdOldPwd->text().isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("InputOriginalPasswordTip")); + return; + } + QJsonObject json; + json.insert("_id", "SetControllerPassword"); + json.insert("_type", "SetControllerPassword"); + json.insert("pwd", fdOldPwd->text()); + json.insert("newPwd",""); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetControllerPassword")+" ..."); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, card, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + if(json["result"].toInt()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Tip"), tr("OriginalPasswordErrorTip")); + return; + } + waitingDlg->success(); + lbOldPwd->hide(); + fdOldPwd->hide(); + btnPwdClear->hide(); + btnPwdSet->setText(tr("Set encryption")); + card->bPassword = false; + fdNewPwd->clear(); + fdPwdAgain->clear(); + fdOldPwd->clear(); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, card, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) { + if(json["result"].toInt()) err = tr("OriginalPasswordErrorTip"); + else { + err = tr("Success"); + lbOldPwd->hide(); + fdOldPwd->hide(); + btnPwdClear->hide(); + btnPwdSet->setText(tr("Set encryption")); + card->bPassword = false; + } + } + gFdResInfo->append(card->m_strCardId+" "+tr("SetControllerPassword")+" "+err); + }); + } + } + }); + hBox->addWidget(btnPwdClear); + hBox->addStretch(); + + vBox->addStretch(); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void CtrlPwdPanel::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void CtrlPwdPanel::init() { + bool isSingle = gSelCards->count()==1; + if(! isSingle) return; + auto card = gSelCards->at(0); + + QJsonObject json; + json.insert("_id", "HasControllerPassword"); + json.insert("_type", "HasControllerPassword"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, card, [=] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + if(json["result"].toBool()) { + lbOldPwd->show(); + fdOldPwd->show(); + btnPwdClear->show(); + btnPwdSet->setText(tr("Modify password")); + card->bPassword = true; + } else { + lbOldPwd->hide(); + fdOldPwd->hide(); + btnPwdClear->hide(); + btnPwdSet->setText(tr("Set encryption")); + card->bPassword = false; + } + }); +} +void CtrlPwdPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void CtrlPwdPanel::transUi() { + lbPwdConfig->setText(tr("Set Password")); + lbOldPwd->setText(tr("Original password")); + lbNewPwd->setText(tr("New password")); + lbPwdAgain->setText(tr("Enter again")); + fdOldPwd->setPlaceholderText(tr("original password")); + fdNewPwd->setPlaceholderText(tr("New password")); + fdPwdAgain->setPlaceholderText(tr("Repeat new password")); + btnPwdSet->setText(tr("Set encryption")); + btnPwdClear->setText(tr("Cancel encryption")); +} diff --git a/LedOK/device/ctrlpwdpanel.h b/LedOK/device/ctrlpwdpanel.h new file mode 100644 index 0000000..d6055b4 --- /dev/null +++ b/LedOK/device/ctrlpwdpanel.h @@ -0,0 +1,30 @@ +#ifndef CTRLPWDPANEL_H +#define CTRLPWDPANEL_H + +#include +#include +#include + +class CtrlPwdPanel : public QWidget { + Q_OBJECT +public: + explicit CtrlPwdPanel(QWidget *parent = nullptr); +protected: + void showEvent(QShowEvent *event) override; + void init(); + void changeEvent(QEvent *) override; + void transUi(); + +private: + QLabel *lbPwdConfig; + QLabel *lbOldPwd; + QLabel *lbNewPwd; + QLabel *lbPwdAgain; + QLineEdit *fdOldPwd; + QLineEdit *fdNewPwd; + QLineEdit *fdPwdAgain; + QPushButton *btnPwdSet; + QPushButton *btnPwdClear; +}; + +#endif // CTRLPWDPANEL_H diff --git a/LedOK/wDevicesManager/ctrlverifyclockpanel.cpp b/LedOK/device/ctrlverifyclockpanel.cpp similarity index 89% rename from LedOK/wDevicesManager/ctrlverifyclockpanel.cpp rename to LedOK/device/ctrlverifyclockpanel.cpp index d99f529..49f74b5 100644 --- a/LedOK/wDevicesManager/ctrlverifyclockpanel.cpp +++ b/LedOK/device/ctrlverifyclockpanel.cpp @@ -1,925 +1,893 @@ -#include "ctrlverifyclockpanel.h" -#include "base/waitingdlg.h" -#include "globaldefine.h" -#include "gqt.h" -#include "tools.h" -#include -#include -#include - -CtrlVerifyClockPanel::CtrlVerifyClockPanel(QWidget *parent) : QWidget(parent) { - auto vBox = new VBox(this); - auto hBox = new HBox(vBox); - hBox->setContentsMargins(-1, 0, -1, -1); - - label = new QLabel; - hBox->addWidget(label); - - fdTimezone = new QComboBox; - fdTimezone->setMinimumWidth(200); - fdTimezone->addItem("Africa/Brazzaville");//西部非洲标准时间 (布拉扎维) - fdTimezone->addItem("Africa/Cairo");//东欧标准时间 (开罗) - fdTimezone->addItem("Africa/Casablanca");//卡萨布兰卡 - fdTimezone->addItem("Africa/Harare");//中部非洲标准时间 (哈拉雷) - fdTimezone->addItem("Africa/Nairobi");//东部非洲标准时间 (内罗毕) - fdTimezone->addItem("Africa/Windhoek");//温得和克 - fdTimezone->addItem("America/Anchorage");//>安克雷奇 - fdTimezone->addItem("America/Argentina/Buenos_Aires");//布宜诺斯艾利斯 - fdTimezone->addItem("America/Barbados");//>大西洋时间 (巴巴多斯) - fdTimezone->addItem("America/Bogota");//>哥伦比亚时间 (波哥大) - fdTimezone->addItem("America/Caracas");//>委内瑞拉时间 (加拉加斯) - fdTimezone->addItem("America/Chicago");//>美国中部时间 (芝加哥) - fdTimezone->addItem("America/Chihuahua");//>奇瓦瓦 - fdTimezone->addItem("America/Costa_Rica");//>美国中部时间 (哥斯达黎加) - fdTimezone->addItem("America/Denver");//>美国山区时间 (丹佛) - fdTimezone->addItem("America/Godthab");//戈特霍布 - fdTimezone->addItem("America/Los_Angeles");//>美国太平洋时间 (洛杉矶) - fdTimezone->addItem("America/Manaus");//亚马逊标准时间 (马瑙斯) - fdTimezone->addItem("America/Mexico_City");//>美国中部时间 (墨西哥城) - fdTimezone->addItem("America/Montevideo");//乌拉圭时间 (蒙得维的亚) - fdTimezone->addItem("America/New_York");//>美国东部时间 (纽约) - fdTimezone->addItem("America/Phoenix");//>美国山区时间 (凤凰城) - fdTimezone->addItem("America/Regina");//>美国中部时间 (里贾纳) - fdTimezone->addItem("America/Santiago");//圣地亚哥 - fdTimezone->addItem("America/Sao_Paulo");//圣保罗 - fdTimezone->addItem("America/St_Johns");//纽芬兰时间 (圣约翰) - fdTimezone->addItem("America/Tijuana");//>美国太平洋时间 (提华纳) - fdTimezone->addItem("Asia/Almaty");//阿拉木图 - fdTimezone->addItem("Asia/Amman");//东欧标准时间 (安曼) - fdTimezone->addItem("Asia/Baghdad");//巴格达 - fdTimezone->addItem("Asia/Baku");//巴库 - fdTimezone->addItem("Asia/Bangkok");//曼谷 - fdTimezone->addItem("Asia/Beirut");//东欧标准时间 (贝鲁特) - fdTimezone->addItem("Asia/Calcutta");//加尔各答 - fdTimezone->addItem("Asia/Colombo");//科伦坡 - fdTimezone->addItem("Asia/Dubai");//迪拜 - fdTimezone->addItem("Asia/Hong_Kong");//香港时间 (香港) - fdTimezone->addItem("Asia/Irkutsk");//伊尔库茨克时间 (伊尔库茨克) - fdTimezone->addItem("Asia/Jerusalem");//以色列时间 (耶路撒冷) - fdTimezone->addItem("Asia/Kabul");//阿富汗时间 (喀布尔) - fdTimezone->addItem("Asia/Karachi");//卡拉奇 - fdTimezone->addItem("Asia/Katmandu");//尼泊尔时间 (加德满都) - fdTimezone->addItem("Asia/Krasnoyarsk");//克拉斯诺亚尔斯克 - fdTimezone->addItem("Asia/Kuala_Lumpur");//吉隆坡 - fdTimezone->addItem("Asia/Kuwait");//科威特 - fdTimezone->addItem("Asia/Magadan");//马加丹时间 (马加丹) - fdTimezone->addItem("Asia/Oral");//乌拉尔 - fdTimezone->addItem("Asia/Rangoon");//缅甸时间 (仰光) - fdTimezone->addItem("Asia/Seoul");//首尔 - fdTimezone->addItem("Asia/Shanghai");//中国标准时间 (北京) - fdTimezone->addItem("Asia/Taipei");//台北时间 (台北) - fdTimezone->addItem("Asia/Tbilisi");//第比利斯 - fdTimezone->addItem("Asia/Tehran");//伊朗标准时间 (德黑兰) - fdTimezone->addItem("Asia/Tokyo");//日本时间 (东京) - fdTimezone->addItem("Asia/Vladivostok");//海参崴时间 (符拉迪沃斯托克) - fdTimezone->addItem("Asia/Yakutsk");//雅库茨克时间 (雅库茨克) - fdTimezone->addItem("Asia/Yekaterinburg");//叶卡捷林堡 - fdTimezone->addItem("Asia/Yerevan");//埃里温 - fdTimezone->addItem("Atlantic/Azores");//亚述尔群岛 - fdTimezone->addItem("Atlantic/Cape_Verde");//佛得角 - fdTimezone->addItem("Atlantic/South_Georgia");//南乔治亚 - fdTimezone->addItem("Australia/Adelaide");//阿德莱德 - fdTimezone->addItem("Australia/Brisbane");//布里斯班 - fdTimezone->addItem("Australia/Darwin");//达尔文 - fdTimezone->addItem("Australia/Hobart");//霍巴特 - fdTimezone->addItem("Australia/Perth");//佩思 - fdTimezone->addItem("Australia/Sydney");//悉尼 - fdTimezone->addItem("Europe/Amsterdam");//中欧标准时间 (阿姆斯特丹) - fdTimezone->addItem("Europe/Athens");//东欧标准时间 (雅典) - fdTimezone->addItem("Europe/Belgrade");//中欧标准时间 (贝尔格莱德) - fdTimezone->addItem("Europe/Brussels");//中欧标准时间 (布鲁塞尔) - fdTimezone->addItem("Europe/Helsinki");//东欧标准时间 (赫尔辛基) - fdTimezone->addItem("Europe/London");//格林尼治标准时间 (伦敦) - fdTimezone->addItem("Europe/Minsk");//明斯克 - fdTimezone->addItem("Europe/Moscow");//莫斯科 - fdTimezone->addItem("Europe/Sarajevo");//中欧标准时间 (萨拉热窝) - fdTimezone->addItem("Pacific/Auckland");//奥克兰 - fdTimezone->addItem("Pacific/Fiji");//斐济 - fdTimezone->addItem("Pacific/Guam");//关岛 - fdTimezone->addItem("Pacific/Honolulu"); - fdTimezone->addItem("Pacific/Majuro"); - fdTimezone->addItem("Pacific/Midway"); - fdTimezone->addItem("Pacific/Tongatapu");//东加塔布 - hBox->addWidget(fdTimezone); - - fdTimeZoneSet = new QPushButton; - connect(fdTimeZoneSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetTimezone"); - json.insert("_type", "SetTimezone"); - json.insert("timezone", fdTimezone->currentText()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetTimezone")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetTimezone")) - } - } - }); - hBox->addWidget(fdTimeZoneSet); - hBox->addSpacing(20); - - lbLang = new QLabel; - hBox->addWidget(lbLang); - - fdIsEn = new QRadioButton; - hBox->addWidget(fdIsEn); - - fdIsCn = new QRadioButton; - hBox->addWidget(fdIsCn); - - btnLangSet = new QPushButton; - connect(btnLangSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetLanguage"); - json.insert("_type", "SetLanguage"); - json.insert("language", fdIsCn->isChecked() ? 1 : 0); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, "设置语言"); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti("设置语言") - } - } - }); - hBox->addWidget(btnLangSet); - - btnLangGet = new QPushButton; - connect(btnLangGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetLanguage"); - json.insert("_type", "GetLanguage"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, "获取语言"); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - if(json["language"].toInt()==1) fdIsCn->setChecked(true); - else fdIsEn->setChecked(true); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = json["language"].toInt()==1 ? "中文" : "英文"; - gFdResInfo->append(card->m_strCardId+" 获取语言 "+err); - }); - } - } - }); - hBox->addWidget(btnLangGet); - hBox->addStretch(); - - - labelVerifyClockConfiguration = new QLabel; - labelVerifyClockConfiguration->setAlignment(Qt::AlignCenter); - vBox->addWidget(labelVerifyClockConfiguration); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - hBox = new HBox(vBox); - auto vvv = new VBox(hBox); - - btnSyncTime = new QPushButton(tr("Verify to Computer time")); - btnSyncTime->setMinimumSize(QSize(60, 30)); - connect(btnSyncTime, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SyncTime"); - json.insert("_type", "SyncTime"); - json.insert("time", QDateTime::currentDateTime().toMSecsSinceEpoch()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SyncTime")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SyncTime")) - } - } - }); - vvv->addWidget(btnSyncTime); - - groupBox_5 = new QGroupBox; - vvv->addWidget(groupBox_5); - - auto vvvv = new QVBoxLayout(groupBox_5); - vvvv->addStretch(); - - btnDateGet = new QPushButton; - btnDateGet->setMinimumSize(QSize(0, 30)); - connect(btnDateGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetControllerDate"); - json.insert("_type", "GetControllerDate"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetControllerDate")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - labelCurTime->setText(json["date"].toString()); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = json["date"].toString(); - gFdResInfo->append(card->m_strCardId+" "+tr("GetControllerDate")+" "+err); - }); - } - } - }); - vvvv->addWidget(btnDateGet); - - labelCurTime = new QLabel; - vvvv->addWidget(labelCurTime); - vvvv->addStretch(); - - - hBox->addSpacing(20); - - - groupBox = new QGroupBox; - groupBox->setCheckable(true); - vvv = new VBox(groupBox); - vvv->setSpacing(3); - - auto hhh = new HBox(vvv); - fdIsLora = new QRadioButton("Lora"); - hhh->addWidget(fdIsLora); - fdIsGPS = new QRadioButton("GPS"); - hhh->addWidget(fdIsGPS); - fdIsNTP = new QRadioButton("NTP"); - hhh->addWidget(fdIsNTP); - fdIsLan = new QRadioButton; - hhh->addWidget(fdIsLan); - - horizontalLayout_5 = new QHBoxLayout(); - horizontalLayout_5->setContentsMargins(0, 0, 0, 0); - - labelSyncTimeInterval = new QLabel(groupBox); - horizontalLayout_5->addWidget(labelSyncTimeInterval); - - lineEdit_3 = new QLineEdit(groupBox); - lineEdit_3->setMinimumSize(QSize(160, 30)); - lineEdit_3->setMaximumSize(QSize(160, 16777215)); - lineEdit_3->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - - horizontalLayout_5->addWidget(lineEdit_3); - - labelmintime = new QLabel(groupBox); - - horizontalLayout_5->addWidget(labelmintime); - - - vvv->addLayout(horizontalLayout_5); - - horizontalLayout_9 = new QHBoxLayout(); - horizontalLayout_9->setContentsMargins(-1, 0, -1, -1); - labelIdCode = new QLabel(groupBox); - - horizontalLayout_9->addWidget(labelIdCode); - - lineEditIdCode = new QLineEdit(groupBox); - lineEditIdCode->setMinimumSize(QSize(0, 30)); - lineEditIdCode->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - - horizontalLayout_9->addWidget(lineEditIdCode); - - vvv->addLayout(horizontalLayout_9); - - horizontalLayout_10 = new QHBoxLayout(); - horizontalLayout_10->setContentsMargins(-1, 0, -1, -1); - labelTimeOffset = new QLabel(groupBox); - - horizontalLayout_10->addWidget(labelTimeOffset); - - lineEditTimeOffset = new QLineEdit(groupBox); - lineEditTimeOffset->setMinimumSize(QSize(0, 30)); - lineEditTimeOffset->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - - horizontalLayout_10->addWidget(lineEditTimeOffset); - - - vvv->addLayout(horizontalLayout_10); - - horizontalLayout_13 = new QHBoxLayout(); - horizontalLayout_13->setContentsMargins(-1, 0, -1, -1); - checkBoxBrightness = new QCheckBox(groupBox); - - horizontalLayout_13->addWidget(checkBoxBrightness); - - checkBoxVolume = new QCheckBox(groupBox); - - horizontalLayout_13->addWidget(checkBoxVolume); - - checkBoxScreenSwitch = new QCheckBox(groupBox); - - horizontalLayout_13->addWidget(checkBoxScreenSwitch); - - - vvv->addLayout(horizontalLayout_13); - - horizontalLayout_7 = new QHBoxLayout(); - horizontalLayout_7->setContentsMargins(-1, 0, -1, -1); - pushButtonSetSync = new QPushButton(groupBox); - pushButtonSetSync->setMinimumSize(QSize(60, 30)); - connect(pushButtonSetSync, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetingSyncMethod"); - json.insert("_type", "SetingSyncMethod"); - json.insert("ntpServer", labelNtpServerAddress->text()); - json.insert("delaySync", lineEditTimeOffset->text().toInt()); - json.insert("identificationCode",lineEditIdCode->text()); - json.insert("brightness", checkBoxBrightness->isChecked() ? "serial" : "none"); - json.insert("volume", checkBoxVolume->isChecked() ? "serial" : "none"); - json.insert("screenSwitch", checkBoxScreenSwitch->isChecked() ? "serial" : "none"); - if(fdIsLora->isChecked()) json.insert("time", "serial"); - else if(fdIsNTP->isChecked()) { - json.insert("time", "ntp"); - json.insert("checkNtpTime", lineEdit_3->text().toInt()); - } else if(fdIsGPS->isChecked()) json.insert("time", "gps"); - else if(fdIsLan->isChecked()) json.insert("time", "Lan"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetingSyncMethod")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetingSyncMethod")) - } - } - }); - horizontalLayout_7->addWidget(pushButtonSetSync); - - fdSyncGet = new QPushButton; - fdSyncGet->setMinimumSize(QSize(60, 30)); - connect(fdSyncGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetingSyncMethod"); - json.insert("_type", "GetingSyncMethod"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetingSyncMethod")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - dealGetSync(json); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QByteArray data; - QString err = checkReplyForJson(reply, &json, &data); - if(err.isEmpty()) { - QString strOtherSyncItem = tr("screenSwitch") + ":" + (json["screenSwitch"].toBool() ? tr("YES") : tr("NO")) - + " " + tr("volume") + ":" + (json["volume"].toBool() ? tr("YES") : tr("NO")) - + " " + tr("brightness") + ":" + (json["brightness"].toBool() ? tr("YES") : tr("NO")); - QString lastSynchronousTime = QDateTime::fromMSecsSinceEpoch(json["lastSynchronousTime"].toDouble()).toString("yyyy-MM-dd HH:mm:ss"); - QString time = json["time"].toString(); - QString lower = time.toLower(); - if(lower=="serial") { - err = "Lora\n "+tr("identificationCode")+": "+json["identificationCode"].toString()+"\n " - +tr("delaySync")+": "+QString::number(json["delaySync"].toInt())+tr("msec")+"\n " - +tr("OtherSyncItem")+": "+strOtherSyncItem+"\n " - +tr("lastSynchronousTime")+": "+lastSynchronousTime; - } else if(lower=="ntp") { - err = time+"\n "+tr("checkNtpTime")+": "+QString::number(json["checkNtpTime"].toInt())+"\n " - +tr("OtherSyncItem")+": "+strOtherSyncItem+"\n " - +tr("lastSynchronousTime")+": "+lastSynchronousTime; - } else if(lower=="gps") { - err = time+"\n "+tr("OtherSyncItem")+": "+strOtherSyncItem+"\n "+tr("lastSynchronousTime")+": "+lastSynchronousTime; - } else if(lower=="lan") { - err = tr("LAN")+"\n "+tr("identificationCode")+": "+json["identificationCode"].toString()+"\n " - +tr("delaySync")+": "+QString::number(json["delaySync"].toInt())+tr("msec")+"\n " - +tr("OtherSyncItem")+": "+strOtherSyncItem+"\n " - +tr("lastSynchronousTime")+": "+lastSynchronousTime; - } else { - err = time+"\n "+data; - } - } - gFdResInfo->append(card->m_strCardId+" "+tr("GetingSyncMethod")+" "+err); - }); - } - } - }); - horizontalLayout_7->addWidget(fdSyncGet); - - vvv->addLayout(horizontalLayout_7); - vvv->addStretch(); - - groupBox_4 = new QGroupBox(groupBox); - groupBox_4->setMinimumSize(QSize(0, 20)); - horizontalLayout_11 = new QHBoxLayout(groupBox_4); - horizontalLayout_11->setSpacing(6); - horizontalLayout_11->setContentsMargins(0, 0, 0, 0); - radioButton_4 = new QRadioButton(groupBox_4); - - buttonGroup_2 = new QButtonGroup(this); - buttonGroup_2->addButton(radioButton_4); - radioButton_4->setChecked(true); - - horizontalLayout_11->addWidget(radioButton_4, 0, Qt::AlignHCenter); - - radioButton_5 = new QRadioButton(groupBox_4); - buttonGroup_2->addButton(radioButton_5); - - horizontalLayout_11->addWidget(radioButton_5, 0, Qt::AlignHCenter); - - - vvv->addWidget(groupBox_4); - - horizontalLayout_12 = new QHBoxLayout(); - horizontalLayout_12->setContentsMargins(-1, 0, -1, -1); - btnLoraMasterSet = new QPushButton(groupBox); - btnLoraMasterSet->setMinimumSize(QSize(0, 30)); - connect(btnLoraMasterSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "MasterSlaveSwitch"); - json.insert("_type", "MasterSlaveSwitch"); - bool isMaster = buttonGroup_2->checkedId()==0; - json.insert("master", isMaster); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, isMaster ? tr("MasterSwitch ") : tr("SlaveSwitch ")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card, isMaster] { - QString err = checkReplyForJson(reply); - gFdResInfo->append(card->m_strCardId+" "+(isMaster ? tr("MasterSwitch ") : tr("SlaveSwitch "))+" "+(err.isEmpty()?QCoreApplication::translate("Def","Success"):err)); - }); - } - } - }); - horizontalLayout_12->addWidget(btnLoraMasterSet); - - btnLoraMasterGet = new QPushButton(groupBox); - btnLoraMasterGet->setMinimumSize(QSize(0, 30)); - connect(btnLoraMasterGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "IsMasterSlave"); - json.insert("_type", "IsMasterSlave"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("IsMasterSlave")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - bool isMaster = json["result"].toBool(); - radioButton_4->setChecked(isMaster); - radioButton_5->setChecked(! isMaster); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = json["result"].toBool() ? tr("Master") : tr("Slave"); - gFdResInfo->append(card->m_strCardId+" "+tr("Lora identity")+" "+err); - }); - } - } - }); - horizontalLayout_12->addWidget(btnLoraMasterGet); - - vvv->addLayout(horizontalLayout_12); - - hBox->addWidget(groupBox); - - hBox->addSpacing(20); - - groupNTP = new QGroupBox; - vvv = new VBox(groupNTP); - - hhh = new HBox(vvv); - labelNtpServerAddress = new QLabel(groupNTP); - hhh->addWidget(labelNtpServerAddress); - - fdNtpServer = new QLineEdit(groupNTP); - fdNtpServer->setMinimumSize(QSize(160, 30)); - fdNtpServer->setMaximumSize(QSize(160, 16777215)); - fdNtpServer->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - hhh->addWidget(fdNtpServer); - hhh->addStretch(); - - vvv->addSpacing(20); - - hhh = new HBox(vvv); - btnNtpSet = new QPushButton; - btnNtpSet->setMinimumSize(QSize(60, 30)); - connect(btnNtpSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetNtpServer"); - json.insert("_type", "SetNtpServer"); - json.insert("ntpServer", fdNtpServer->text()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetNtpServer")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetNtpServer")) - } - } - }); - hhh->addWidget(btnNtpSet); - - btnNtpGet = new QPushButton; - btnNtpGet->setMinimumSize(QSize(60, 30)); - connect(btnNtpGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetNtpServer"); - json.insert("_type", "GetNtpServer"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetNtpServer")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - fdNtpServer->setText(json["ntpServer"].toString()); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = json["ntpServer"].toString(); - gFdResInfo->append(card->m_strCardId+" "+tr("GetNtpServer")+" "+err); - }); - } - } - }); - hhh->addWidget(btnNtpGet); - - vvv->addStretch(); - - hBox->addWidget(groupNTP); - hBox->addStretch(); - - vBox->addStretch(); - - label->setText(tr("TimeZone")); - lbLang->setText(tr("Language:")); - fdIsEn->setText(tr("English")); - fdIsCn->setText(tr("\344\270\255\346\226\207")); - labelVerifyClockConfiguration->setText(tr("Verify Clock Configuration")); - groupBox_5->setTitle(tr("Cur time of controller")); - groupBox->setTitle(tr("Enable Synchronous playing")); - fdIsLan->setText(tr("LAN")); - labelSyncTimeInterval->setText(tr("Sync time interval")); - lineEdit_3->setPlaceholderText(tr("Sync time interval")); - labelmintime->setText(tr("(min/time)")); - labelIdCode->setText(tr("Sync identificationCode")); - lineEditIdCode->setPlaceholderText(tr("identification code")); - labelTimeOffset->setText(tr("Time offset(msec)")); - checkBoxBrightness->setText(tr("Brightness")); - checkBoxVolume->setText(tr("Volume")); - checkBoxScreenSwitch->setText(tr("Screen on/off")); - radioButton_4->setText(tr("Slave")); - radioButton_5->setText(tr("Master ")); - groupNTP->setTitle(tr("NTP Server")); - labelNtpServerAddress->setText(tr("NTP Server address")); - fdNtpServer->setPlaceholderText(tr("NTP Server address")); - - btnNtpSet->setProperty("ssType", "progManageTool"); - pushButtonSetSync->setProperty("ssType", "progManageTool"); - btnSyncTime->setProperty("ssType", "progManageTool"); - fdSyncGet->setProperty("ssType", "progManageTool"); - btnNtpGet->setProperty("ssType", "progManageTool"); - - btnLoraMasterSet->setProperty("ssType", "progManageTool"); - btnLoraMasterGet->setProperty("ssType", "progManageTool"); - btnDateGet->setProperty("ssType", "progManageTool"); - fdTimeZoneSet->setProperty("ssType", "progManageTool"); - buttonGroup_2->setId(radioButton_4, 0); - buttonGroup_2->setId(radioButton_5, 1); - - fdIsLora->setChecked(true); - labelIdCode->setVisible(true); - lineEditIdCode->setVisible(true); - labelTimeOffset->setVisible(true); - lineEditTimeOffset->setVisible(true); - lineEdit_3->setVisible(false); - labelSyncTimeInterval->setVisible(false); - labelmintime->setVisible(false); - - //按钮事件绑定 - connect(fdIsGPS,SIGNAL(clicked()),this,SLOT(OnRadioButton())); - connect(fdIsLora,SIGNAL(clicked()),this,SLOT(OnRadioButton2())); - connect(fdIsNTP,SIGNAL(clicked()),this,SLOT(OnRadioButton3())); - connect(fdIsLan,SIGNAL(clicked()),this,SLOT(OnRadioButton6())); - - //MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent) - - connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { - if(isVisible()) init(); - }); - transUi(); -} - -void CtrlVerifyClockPanel::showEvent(QShowEvent *event) { - QWidget::showEvent(event); - init(); -} -void CtrlVerifyClockPanel::init() { - bool isSingle = gSelCards->count()==1; - if(! isSingle) return; - auto card = gSelCards->at(0); - - QJsonObject json; - json.insert("_id", "GetingSyncMethod"); - json.insert("_type", "GetingSyncMethod"); - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - dealGetSync(json); - }); - - json = QJsonObject(); - json.insert("_id", "GetTimezone"); - json.insert("_type", "GetTimezone"); - reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - fdTimezone->setCurrentText(json["timezone"].toString()); - }); - - json = QJsonObject(); - json.insert("_id", "GetLanguage"); - json.insert("_type", "GetLanguage"); - reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - if(json["language"].toInt()==1) fdIsCn->setChecked(true); - else fdIsEn->setChecked(true); - }); -} -void CtrlVerifyClockPanel::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void CtrlVerifyClockPanel::transUi() { - labelNtpServerAddress->setText(tr("NTP Server address")); - labelTimeOffset->setText(tr("Time offset(msec)")); - labelVerifyClockConfiguration->setText(tr("Verify clock configuration")); - lbLang->setText(tr("Language:")); - btnNtpSet->setText(tr("Set")); - pushButtonSetSync->setText(tr("Set")); - btnLangSet->setText(tr("Set")); - btnSyncTime->setText(tr("Verify to Computer time")); - fdTimeZoneSet->setText(tr("Set")); - btnLoraMasterSet->setText(tr("Set")); - btnLangGet->setText(tr("Readback")); - btnLoraMasterGet->setText(tr("Readback")); - btnNtpGet->setText(tr("Readback")); - fdSyncGet->setText(tr("Readback")); - btnDateGet->setText(tr("Readback")); - groupNTP->setTitle(tr("NTP Server")); - groupBox->setTitle(tr("Enable Synchronous playing")); - radioButton_4->setText(tr("Master")); - radioButton_5->setText(tr("Slave")); - labelSyncTimeInterval->setText(tr("Sync time interval")); - labelIdCode->setText(tr("Identification Code")); - checkBoxBrightness->setText(tr("Brightness")); - checkBoxVolume->setText(tr("Volume")); - checkBoxScreenSwitch->setText(tr("Screen on/off")); - - groupBox_5->setTitle(tr("Cur time of controller")); - - fdNtpServer->setPlaceholderText(tr("NTP Server address")); - lineEdit_3->setPlaceholderText(tr("Sync time interval")); - lineEditIdCode->setPlaceholderText(tr("identification code")); - label->setText(tr("TimeZone")); -} -void CtrlVerifyClockPanel::dealGetSync(QJsonDocument &json) { - QString strType = json["time"].toString().toLower(); - if(strType=="serial" || strType=="lan") { - if(strType=="serial") fdIsLora->setChecked(true); - else fdIsLan->setChecked(true); - lineEditIdCode->setText(json["identificationCode"].toString()); - lineEditTimeOffset->setText(QString::number(json["delaySync"].toInt())); - labelIdCode->setVisible(true); - lineEditIdCode->setVisible(true); - labelTimeOffset->setVisible(true); - lineEditTimeOffset->setVisible(true); - lineEdit_3->setVisible(false); - labelSyncTimeInterval->setVisible(false); - labelmintime->setVisible(false); - checkBoxScreenSwitch->setChecked(json["screenSwitch"].toString()!="NONE"); - checkBoxVolume->setChecked(json["volume"].toString()!="NONE"); - checkBoxBrightness->setChecked(json["brightness"].toString()!="NONE"); - checkBoxScreenSwitch->setVisible(true); - checkBoxVolume->setVisible(true); - checkBoxBrightness->setVisible(true); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); - } else if(strType=="ntp") { - fdIsNTP->setChecked(true); - lineEdit_3->setText(QString::number(json["checkNtpTime"].toInt())); - labelIdCode->setVisible(false); - lineEditIdCode->setVisible(false); - labelTimeOffset->setVisible(false); - lineEditTimeOffset->setVisible(false); - lineEdit_3->setVisible(true); - labelSyncTimeInterval->setVisible(true); - labelmintime->setVisible(true); - groupBox_4->setVisible(false); - radioButton_4->setVisible(false); - radioButton_5->setVisible(false); - btnLoraMasterSet->setVisible(false); - btnLoraMasterGet->setVisible(false); - checkBoxScreenSwitch->setVisible(false); - checkBoxVolume->setVisible(false); - checkBoxBrightness->setVisible(false); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); - } else if(strType=="gps") { - fdIsGPS->setChecked(true); - labelIdCode->setVisible(false); - lineEditIdCode->setVisible(false); - labelTimeOffset->setVisible(false); - lineEditTimeOffset->setVisible(false); - labelSyncTimeInterval->setVisible(false); - lineEdit_3->setVisible(false); - labelmintime->setVisible(false); - groupBox_4->setVisible(false); - radioButton_4->setVisible(false); - radioButton_5->setVisible(false); - btnLoraMasterSet->setVisible(false); - btnLoraMasterGet->setVisible(false); - checkBoxScreenSwitch->setVisible(false); - checkBoxVolume->setVisible(false); - checkBoxBrightness->setVisible(false); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); - } -} -void CtrlVerifyClockPanel::OnRadioButton()//gps -{ - labelIdCode->setVisible(false); - lineEditIdCode->setVisible(false); - labelTimeOffset->setVisible(false); - lineEditTimeOffset->setVisible(false); - labelSyncTimeInterval->setVisible(false); - lineEdit_3->setVisible(false); - labelmintime->setVisible(false); - groupBox_4->setVisible(false); - radioButton_4->setVisible(false); - radioButton_5->setVisible(false); - btnLoraMasterSet->setVisible(false); - btnLoraMasterGet->setVisible(false); - checkBoxScreenSwitch->setVisible(false); - checkBoxVolume->setVisible(false); - checkBoxBrightness->setVisible(false); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); -} -void CtrlVerifyClockPanel::OnRadioButton2()//lora -{ - labelIdCode->setVisible(true); - lineEditIdCode->setVisible(true); - labelTimeOffset->setVisible(true); - lineEditTimeOffset->setVisible(true); - lineEdit_3->setVisible(false); - labelSyncTimeInterval->setVisible(false); - labelmintime->setVisible(false); - groupBox_4->setVisible(true); - radioButton_4->setVisible(true); - radioButton_5->setVisible(true); - btnLoraMasterSet->setVisible(true); - btnLoraMasterGet->setVisible(true); - checkBoxScreenSwitch->setVisible(true); - checkBoxVolume->setVisible(true); - checkBoxBrightness->setVisible(true); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); -} - -void CtrlVerifyClockPanel::OnRadioButton3()//ntp -{ - labelIdCode->setVisible(false); - lineEditIdCode->setVisible(false); - labelTimeOffset->setVisible(false); - lineEditTimeOffset->setVisible(false); - lineEdit_3->setVisible(true); - labelSyncTimeInterval->setVisible(true); - labelmintime->setVisible(true); - groupBox_4->setVisible(false); - radioButton_4->setVisible(false); - radioButton_5->setVisible(false); - btnLoraMasterSet->setVisible(false); - btnLoraMasterGet->setVisible(false); - checkBoxScreenSwitch->setVisible(false); - checkBoxVolume->setVisible(false); - checkBoxBrightness->setVisible(false); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); -} -void CtrlVerifyClockPanel::OnRadioButton6() { - labelIdCode->setVisible(true); - lineEditIdCode->setVisible(true); - labelTimeOffset->setVisible(true); - lineEditTimeOffset->setVisible(true); - lineEdit_3->setVisible(false); - labelSyncTimeInterval->setVisible(false); - labelmintime->setVisible(false); - groupBox_4->setVisible(true); - radioButton_4->setVisible(true); - radioButton_5->setVisible(true); - btnLoraMasterSet->setVisible(true); - btnLoraMasterGet->setVisible(true); - checkBoxScreenSwitch->setVisible(true); - checkBoxVolume->setVisible(true); - checkBoxBrightness->setVisible(true); - pushButtonSetSync->setVisible(true); - fdSyncGet->setVisible(true); -} +#include "ctrlverifyclockpanel.h" +#include "base/waitingdlg.h" +#include "globaldefine.h" +#include "gutil/qgui.h" +#include "tools.h" +#include +#include +#include + +CtrlVerifyClockPanel::CtrlVerifyClockPanel(QWidget *parent) : QWidget(parent) { + auto vBox = new VBox(this); + auto hBox = new HBox(vBox); + + label = new QLabel; + hBox->addWidget(label); + + fdTimezone = new QComboBox; + fdTimezone->setMinimumWidth(200); + fdTimezone->addItem("Africa/Brazzaville");//西部非洲标准时间 (布拉扎维) + fdTimezone->addItem("Africa/Cairo");//东欧标准时间 (开罗) + fdTimezone->addItem("Africa/Casablanca");//卡萨布兰卡 + fdTimezone->addItem("Africa/Harare");//中部非洲标准时间 (哈拉雷) + fdTimezone->addItem("Africa/Nairobi");//东部非洲标准时间 (内罗毕) + fdTimezone->addItem("Africa/Windhoek");//温得和克 + fdTimezone->addItem("America/Anchorage");//>安克雷奇 + fdTimezone->addItem("America/Argentina/Buenos_Aires");//布宜诺斯艾利斯 + fdTimezone->addItem("America/Barbados");//>大西洋时间 (巴巴多斯) + fdTimezone->addItem("America/Bogota");//>哥伦比亚时间 (波哥大) + fdTimezone->addItem("America/Caracas");//>委内瑞拉时间 (加拉加斯) + fdTimezone->addItem("America/Chicago");//>美国中部时间 (芝加哥) + fdTimezone->addItem("America/Chihuahua");//>奇瓦瓦 + fdTimezone->addItem("America/Costa_Rica");//>美国中部时间 (哥斯达黎加) + fdTimezone->addItem("America/Denver");//>美国山区时间 (丹佛) + fdTimezone->addItem("America/Godthab");//戈特霍布 + fdTimezone->addItem("America/Los_Angeles");//>美国太平洋时间 (洛杉矶) + fdTimezone->addItem("America/Manaus");//亚马逊标准时间 (马瑙斯) + fdTimezone->addItem("America/Mexico_City");//>美国中部时间 (墨西哥城) + fdTimezone->addItem("America/Montevideo");//乌拉圭时间 (蒙得维的亚) + fdTimezone->addItem("America/New_York");//>美国东部时间 (纽约) + fdTimezone->addItem("America/Phoenix");//>美国山区时间 (凤凰城) + fdTimezone->addItem("America/Regina");//>美国中部时间 (里贾纳) + fdTimezone->addItem("America/Santiago");//圣地亚哥 + fdTimezone->addItem("America/Sao_Paulo");//圣保罗 + fdTimezone->addItem("America/St_Johns");//纽芬兰时间 (圣约翰) + fdTimezone->addItem("America/Tijuana");//>美国太平洋时间 (提华纳) + fdTimezone->addItem("Asia/Almaty");//阿拉木图 + fdTimezone->addItem("Asia/Amman");//东欧标准时间 (安曼) + fdTimezone->addItem("Asia/Baghdad");//巴格达 + fdTimezone->addItem("Asia/Baku");//巴库 + fdTimezone->addItem("Asia/Bangkok");//曼谷 + fdTimezone->addItem("Asia/Beirut");//东欧标准时间 (贝鲁特) + fdTimezone->addItem("Asia/Calcutta");//加尔各答 + fdTimezone->addItem("Asia/Colombo");//科伦坡 + fdTimezone->addItem("Asia/Dubai");//迪拜 + fdTimezone->addItem("Asia/Hong_Kong");//香港时间 (香港) + fdTimezone->addItem("Asia/Irkutsk");//伊尔库茨克时间 (伊尔库茨克) + fdTimezone->addItem("Asia/Jerusalem");//以色列时间 (耶路撒冷) + fdTimezone->addItem("Asia/Kabul");//阿富汗时间 (喀布尔) + fdTimezone->addItem("Asia/Karachi");//卡拉奇 + fdTimezone->addItem("Asia/Katmandu");//尼泊尔时间 (加德满都) + fdTimezone->addItem("Asia/Krasnoyarsk");//克拉斯诺亚尔斯克 + fdTimezone->addItem("Asia/Kuala_Lumpur");//吉隆坡 + fdTimezone->addItem("Asia/Kuwait");//科威特 + fdTimezone->addItem("Asia/Magadan");//马加丹时间 (马加丹) + fdTimezone->addItem("Asia/Oral");//乌拉尔 + fdTimezone->addItem("Asia/Rangoon");//缅甸时间 (仰光) + fdTimezone->addItem("Asia/Seoul");//首尔 + fdTimezone->addItem("Asia/Shanghai");//中国标准时间 (北京) + fdTimezone->addItem("Asia/Taipei");//台北时间 (台北) + fdTimezone->addItem("Asia/Tbilisi");//第比利斯 + fdTimezone->addItem("Asia/Tehran");//伊朗标准时间 (德黑兰) + fdTimezone->addItem("Asia/Tokyo");//日本时间 (东京) + fdTimezone->addItem("Asia/Vladivostok");//海参崴时间 (符拉迪沃斯托克) + fdTimezone->addItem("Asia/Yakutsk");//雅库茨克时间 (雅库茨克) + fdTimezone->addItem("Asia/Yekaterinburg");//叶卡捷林堡 + fdTimezone->addItem("Asia/Yerevan");//埃里温 + fdTimezone->addItem("Atlantic/Azores");//亚述尔群岛 + fdTimezone->addItem("Atlantic/Cape_Verde");//佛得角 + fdTimezone->addItem("Atlantic/South_Georgia");//南乔治亚 + fdTimezone->addItem("Australia/Adelaide");//阿德莱德 + fdTimezone->addItem("Australia/Brisbane");//布里斯班 + fdTimezone->addItem("Australia/Darwin");//达尔文 + fdTimezone->addItem("Australia/Hobart");//霍巴特 + fdTimezone->addItem("Australia/Perth");//佩思 + fdTimezone->addItem("Australia/Sydney");//悉尼 + fdTimezone->addItem("Europe/Amsterdam");//中欧标准时间 (阿姆斯特丹) + fdTimezone->addItem("Europe/Athens");//东欧标准时间 (雅典) + fdTimezone->addItem("Europe/Belgrade");//中欧标准时间 (贝尔格莱德) + fdTimezone->addItem("Europe/Brussels");//中欧标准时间 (布鲁塞尔) + fdTimezone->addItem("Europe/Helsinki");//东欧标准时间 (赫尔辛基) + fdTimezone->addItem("Europe/London");//格林尼治标准时间 (伦敦) + fdTimezone->addItem("Europe/Minsk");//明斯克 + fdTimezone->addItem("Europe/Moscow");//莫斯科 + fdTimezone->addItem("Europe/Sarajevo");//中欧标准时间 (萨拉热窝) + fdTimezone->addItem("Pacific/Auckland");//奥克兰 + fdTimezone->addItem("Pacific/Fiji");//斐济 + fdTimezone->addItem("Pacific/Guam");//关岛 + fdTimezone->addItem("Pacific/Honolulu"); + fdTimezone->addItem("Pacific/Majuro"); + fdTimezone->addItem("Pacific/Midway"); + fdTimezone->addItem("Pacific/Tongatapu");//东加塔布 + hBox->addWidget(fdTimezone); + + fdTimeZoneSet = new QPushButton; + connect(fdTimeZoneSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetTimezone"); + json.insert("_type", "SetTimezone"); + json.insert("timezone", fdTimezone->currentText()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetTimezone")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetTimezone")) + } + } + }); + hBox->addWidget(fdTimeZoneSet); + hBox->addSpacing(20); + + lbLang = new QLabel; + hBox->addWidget(lbLang); + + fdIsEn = new QRadioButton("English"); + hBox->addWidget(fdIsEn); + + fdIsCn = new QRadioButton("中文"); + hBox->addWidget(fdIsCn); + + btnLangSet = new QPushButton; + connect(btnLangSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetLanguage"); + json.insert("_type", "SetLanguage"); + json.insert("language", fdIsCn->isChecked() ? 1 : 0); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, "设置语言"); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti("设置语言") + } + } + }); + hBox->addWidget(btnLangSet); + + btnLangGet = new QPushButton; + connect(btnLangGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetLanguage"); + json.insert("_type", "GetLanguage"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, "获取语言"); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + if(json["language"].toInt()==1) fdIsCn->setChecked(true); + else fdIsEn->setChecked(true); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["language"].toInt()==1 ? "中文" : "英文"; + gFdResInfo->append(cardId+" 获取语言 "+err); + }); + } + } + }); + hBox->addWidget(btnLangGet); + hBox->addStretch(); + + + labelVerifyClockConfiguration = new QLabel; + labelVerifyClockConfiguration->setAlignment(Qt::AlignCenter); + vBox->addWidget(labelVerifyClockConfiguration); + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + hBox = new HBox(vBox); + auto vvv = new VBox(hBox); + + btnSyncTime = new QPushButton(tr("Verify to Computer time")); + btnSyncTime->setMinimumSize(QSize(60, 30)); + connect(btnSyncTime, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SyncTime"); + json.insert("_type", "SyncTime"); + json.insert("time", QDateTime::currentDateTime().toMSecsSinceEpoch()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SyncTime")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SyncTime")) + } + } + }); + vvv->addWidget(btnSyncTime); + + groupBox_5 = new QGroupBox; + vvv->addWidget(groupBox_5); + + auto vvvv = new QVBoxLayout(groupBox_5); + vvvv->addStretch(); + + btnDateGet = new QPushButton; + btnDateGet->setMinimumSize(QSize(0, 30)); + connect(btnDateGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetControllerDate"); + json.insert("_type", "GetControllerDate"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetControllerDate")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + labelCurTime->setText(json["date"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["date"].toString(); + gFdResInfo->append(cardId+" "+tr("GetControllerDate")+" "+err); + }); + } + } + }); + vvvv->addWidget(btnDateGet); + + labelCurTime = new QLabel; + vvvv->addWidget(labelCurTime); + vvvv->addStretch(); + + + hBox->addSpacing(20); + + + groupBox = new QGroupBox; + groupBox->setCheckable(true); + vvv = new VBox(groupBox); + vvv->setSpacing(3); + + auto hhh = new HBox(vvv); + fdIsLora = new QRadioButton("Lora"); + hhh->addWidget(fdIsLora); + fdIsGPS = new QRadioButton("GPS"); + hhh->addWidget(fdIsGPS); + fdIsNTP = new QRadioButton("NTP"); + hhh->addWidget(fdIsNTP); + fdIsLan = new QRadioButton; + hhh->addWidget(fdIsLan); + + horizontalLayout_5 = new QHBoxLayout(); + horizontalLayout_5->setContentsMargins(0, 0, 0, 0); + + labelSyncTimeInterval = new QLabel(groupBox); + horizontalLayout_5->addWidget(labelSyncTimeInterval); + + lineEdit_3 = new QLineEdit(groupBox); + lineEdit_3->setMinimumSize(QSize(160, 30)); + lineEdit_3->setMaximumSize(QSize(160, 16777215)); + horizontalLayout_5->addWidget(lineEdit_3); + + labelmintime = new QLabel(groupBox); + + horizontalLayout_5->addWidget(labelmintime); + + + vvv->addLayout(horizontalLayout_5); + + horizontalLayout_9 = new QHBoxLayout(); + horizontalLayout_9->setContentsMargins(-1, 0, -1, -1); + labelIdCode = new QLabel(groupBox); + + horizontalLayout_9->addWidget(labelIdCode); + + lineEditIdCode = new QLineEdit(groupBox); + lineEditIdCode->setMinimumSize(QSize(0, 30)); + lineEditIdCode->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); + + horizontalLayout_9->addWidget(lineEditIdCode); + + vvv->addLayout(horizontalLayout_9); + + horizontalLayout_10 = new QHBoxLayout(); + horizontalLayout_10->setContentsMargins(-1, 0, -1, -1); + labelTimeOffset = new QLabel(groupBox); + + horizontalLayout_10->addWidget(labelTimeOffset); + + lineEditTimeOffset = new QLineEdit(groupBox); + lineEditTimeOffset->setMinimumSize(QSize(0, 30)); + lineEditTimeOffset->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); + + horizontalLayout_10->addWidget(lineEditTimeOffset); + + + vvv->addLayout(horizontalLayout_10); + + horizontalLayout_13 = new QHBoxLayout(); + horizontalLayout_13->setContentsMargins(-1, 0, -1, -1); + checkBoxBrightness = new QCheckBox(groupBox); + + horizontalLayout_13->addWidget(checkBoxBrightness); + + checkBoxVolume = new QCheckBox(groupBox); + + horizontalLayout_13->addWidget(checkBoxVolume); + + checkBoxScreenSwitch = new QCheckBox(groupBox); + + horizontalLayout_13->addWidget(checkBoxScreenSwitch); + + + vvv->addLayout(horizontalLayout_13); + + horizontalLayout_7 = new QHBoxLayout(); + horizontalLayout_7->setContentsMargins(-1, 0, -1, -1); + btnSyncSet = new QPushButton(groupBox); + btnSyncSet->setMinimumSize(QSize(60, 30)); + connect(btnSyncSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetingSyncMethod"); + json.insert("_type", "SetingSyncMethod"); + json.insert("ntpServer", labelNtpServerAddress->text()); + json.insert("delaySync", lineEditTimeOffset->text().toInt()); + json.insert("identificationCode",lineEditIdCode->text()); + json.insert("brightness", checkBoxBrightness->isChecked() ? "serial" : "none"); + json.insert("volume", checkBoxVolume->isChecked() ? "serial" : "none"); + json.insert("screenSwitch", checkBoxScreenSwitch->isChecked() ? "serial" : "none"); + if(fdIsLora->isChecked()) json.insert("time", "serial"); + else if(fdIsNTP->isChecked()) { + json.insert("time", "ntp"); + json.insert("checkNtpTime", lineEdit_3->text().toInt()); + } else if(fdIsGPS->isChecked()) json.insert("time", "gps"); + else if(fdIsLan->isChecked()) json.insert("time", "Lan"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetingSyncMethod")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetingSyncMethod")) + } + } + }); + horizontalLayout_7->addWidget(btnSyncSet); + + fdSyncGet = new QPushButton; + fdSyncGet->setMinimumSize(QSize(60, 30)); + connect(fdSyncGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetingSyncMethod"); + json.insert("_type", "GetingSyncMethod"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetingSyncMethod")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + dealGetSync(json); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QByteArray data; + QString err = checkReplyForJson(reply, &json, &data); + if(err.isEmpty()) { + QString strOtherSyncItem = tr("screenSwitch") + ":" + (json["screenSwitch"].toBool() ? tr("YES") : tr("NO")) + + " " + tr("volume") + ":" + (json["volume"].toBool() ? tr("YES") : tr("NO")) + + " " + tr("brightness") + ":" + (json["brightness"].toBool() ? tr("YES") : tr("NO")); + QString lastSynchronousTime = QDateTime::fromMSecsSinceEpoch(json["lastSynchronousTime"].toDouble()).toString("yyyy-MM-dd HH:mm:ss"); + QString time = json["time"].toString(); + QString lower = time.toLower(); + if(lower=="serial") { + err = "Lora\n "+tr("identificationCode")+": "+json["identificationCode"].toString()+"\n " + +tr("delaySync")+": "+QString::number(json["delaySync"].toInt())+tr("msec")+"\n " + +tr("OtherSyncItem")+": "+strOtherSyncItem+"\n " + +tr("lastSynchronousTime")+": "+lastSynchronousTime; + } else if(lower=="ntp") { + err = time+"\n "+tr("checkNtpTime")+": "+QString::number(json["checkNtpTime"].toInt())+"\n " + +tr("OtherSyncItem")+": "+strOtherSyncItem+"\n " + +tr("lastSynchronousTime")+": "+lastSynchronousTime; + } else if(lower=="gps") { + err = time+"\n "+tr("OtherSyncItem")+": "+strOtherSyncItem+"\n "+tr("lastSynchronousTime")+": "+lastSynchronousTime; + } else if(lower=="lan") { + err = tr("LAN")+"\n "+tr("identificationCode")+": "+json["identificationCode"].toString()+"\n " + +tr("delaySync")+": "+QString::number(json["delaySync"].toInt())+tr("msec")+"\n " + +tr("OtherSyncItem")+": "+strOtherSyncItem+"\n " + +tr("lastSynchronousTime")+": "+lastSynchronousTime; + } else { + err = time+"\n "+data; + } + } + gFdResInfo->append(cardId+" "+tr("GetingSyncMethod")+" "+err); + }); + } + } + }); + horizontalLayout_7->addWidget(fdSyncGet); + + vvv->addLayout(horizontalLayout_7); + vvv->addStretch(); + + groupBox_4 = new QGroupBox(groupBox); + groupBox_4->setMinimumSize(QSize(0, 20)); + horizontalLayout_11 = new QHBoxLayout(groupBox_4); + horizontalLayout_11->setSpacing(6); + horizontalLayout_11->setContentsMargins(0, 0, 0, 0); + fdMaster = new QRadioButton(groupBox_4); + + buttonGroup_2 = new QButtonGroup(this); + buttonGroup_2->addButton(fdMaster); + fdMaster->setChecked(true); + + horizontalLayout_11->addWidget(fdMaster, 0, Qt::AlignHCenter); + + fdSlave = new QRadioButton(groupBox_4); + buttonGroup_2->addButton(fdSlave); + + horizontalLayout_11->addWidget(fdSlave, 0, Qt::AlignHCenter); + + + vvv->addWidget(groupBox_4); + + horizontalLayout_12 = new QHBoxLayout(); + horizontalLayout_12->setContentsMargins(-1, 0, -1, -1); + btnLoraMasterSet = new QPushButton(groupBox); + btnLoraMasterSet->setMinimumSize(QSize(0, 30)); + connect(btnLoraMasterSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "MasterSlaveSwitch"); + json.insert("_type", "MasterSlaveSwitch"); + bool isMaster = buttonGroup_2->checkedId()==0; + json.insert("master", isMaster); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, isMaster ? tr("MasterSwitch ") : tr("SlaveSwitch ")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [reply, card, isMaster] { + QString err = checkReplyForJson(reply); + gFdResInfo->append(card->m_strCardId+" "+(isMaster ? tr("MasterSwitch ") : tr("SlaveSwitch "))+" "+(err.isEmpty()?QCoreApplication::translate("Def","Success"):err)); + }); + } + } + }); + horizontalLayout_12->addWidget(btnLoraMasterSet); + + btnLoraMasterGet = new QPushButton(groupBox); + btnLoraMasterGet->setMinimumSize(QSize(0, 30)); + connect(btnLoraMasterGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "IsMasterSlave"); + json.insert("_type", "IsMasterSlave"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("IsMasterSlave")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + bool isMaster = json["result"].toBool(); + fdMaster->setChecked(isMaster); + fdSlave->setChecked(! isMaster); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["result"].toBool() ? tr("Master") : tr("Slave"); + gFdResInfo->append(cardId+" "+tr("Lora identity")+" "+err); + }); + } + } + }); + horizontalLayout_12->addWidget(btnLoraMasterGet); + + vvv->addLayout(horizontalLayout_12); + + hBox->addWidget(groupBox); + + hBox->addSpacing(20); + + groupNTP = new QGroupBox; + vvv = new VBox(groupNTP); + + hhh = new HBox(vvv); + labelNtpServerAddress = new QLabel(groupNTP); + hhh->addWidget(labelNtpServerAddress); + + fdNtpServer = new QLineEdit(groupNTP); + fdNtpServer->setMinimumSize(QSize(160, 30)); + fdNtpServer->setMaximumSize(QSize(160, 16777215)); + fdNtpServer->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); + hhh->addWidget(fdNtpServer); + hhh->addStretch(); + + vvv->addSpacing(20); + + hhh = new HBox(vvv); + btnNtpSet = new QPushButton; + btnNtpSet->setMinimumSize(QSize(60, 30)); + connect(btnNtpSet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "SetNtpServer"); + json.insert("_type", "SetNtpServer"); + json.insert("ntpServer", fdNtpServer->text()); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("SetNtpServer")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { + Def_CtrlSetReqAfter + }); + } else { + foreach(auto card, *gSelCards) { + Def_CtrlSetMulti(tr("SetNtpServer")) + } + } + }); + hhh->addWidget(btnNtpSet); + + btnNtpGet = new QPushButton; + btnNtpGet->setMinimumSize(QSize(60, 30)); + connect(btnNtpGet, &QPushButton::clicked, this, [this] { + if(gSelCards->isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); + return; + } + QJsonObject json; + json.insert("_id", "GetNtpServer"); + json.insert("_type", "GetNtpServer"); + if(gSelCards->count() == 1) { + auto waitingDlg = new WaitingDlg(this, tr("GetNtpServer")); + Def_CtrlReqPre + connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { + Def_CtrlSingleGetReply + waitingDlg->success(); + fdNtpServer->setText(json["ntpServer"].toString()); + }); + } else { + foreach(auto card, *gSelCards) { + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + auto cardId = card->m_strCardId; + connect(reply, &QNetworkReply::finished, this, [reply, cardId] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(err.isEmpty()) err = json["ntpServer"].toString(); + gFdResInfo->append(cardId+" "+tr("GetNtpServer")+" "+err); + }); + } + } + }); + hhh->addWidget(btnNtpGet); + + vvv->addStretch(); + + hBox->addWidget(groupNTP); + hBox->addStretch(); + + vBox->addStretch(); + + btnNtpSet->setProperty("ssType", "progManageTool"); + btnSyncSet->setProperty("ssType", "progManageTool"); + btnSyncTime->setProperty("ssType", "progManageTool"); + fdSyncGet->setProperty("ssType", "progManageTool"); + btnNtpGet->setProperty("ssType", "progManageTool"); + + btnLoraMasterSet->setProperty("ssType", "progManageTool"); + btnLoraMasterGet->setProperty("ssType", "progManageTool"); + btnDateGet->setProperty("ssType", "progManageTool"); + fdTimeZoneSet->setProperty("ssType", "progManageTool"); + buttonGroup_2->setId(fdMaster, 0); + buttonGroup_2->setId(fdSlave, 1); + + fdIsLora->setChecked(true); + labelIdCode->setVisible(true); + lineEditIdCode->setVisible(true); + labelTimeOffset->setVisible(true); + lineEditTimeOffset->setVisible(true); + lineEdit_3->setVisible(false); + labelSyncTimeInterval->setVisible(false); + labelmintime->setVisible(false); + + //按钮事件绑定 + connect(fdIsGPS,SIGNAL(clicked()),this,SLOT(OnRadioButton())); + connect(fdIsLora,SIGNAL(clicked()),this,SLOT(OnRadioButton2())); + connect(fdIsNTP,SIGNAL(clicked()),this,SLOT(OnRadioButton3())); + connect(fdIsLan,SIGNAL(clicked()),this,SLOT(OnRadioButton6())); + + connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { + if(isVisible()) init(); + }); + transUi(); +} + +void CtrlVerifyClockPanel::showEvent(QShowEvent *event) { + QWidget::showEvent(event); + init(); +} +void CtrlVerifyClockPanel::init() { + bool isSingle = gSelCards->count()==1; + if(! isSingle) return; + auto card = gSelCards->at(0); + + QJsonObject json; + json.insert("_id", "GetingSyncMethod"); + json.insert("_type", "GetingSyncMethod"); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + dealGetSync(json); + }); + + json = QJsonObject(); + json.insert("_id", "GetTimezone"); + json.insert("_type", "GetTimezone"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + fdTimezone->setCurrentText(json["timezone"].toString()); + }); + + json = QJsonObject(); + json.insert("_id", "GetLanguage"); + json.insert("_type", "GetLanguage"); + reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [this, reply] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) return; + if(json["language"].toInt()==1) fdIsCn->setChecked(true); + else fdIsEn->setChecked(true); + }); +} +void CtrlVerifyClockPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void CtrlVerifyClockPanel::transUi() { + btnDateGet->setText(tr("Readback")); + btnLangGet->setText(tr("Readback")); + btnLangSet->setText(tr("Set")); + btnLoraMasterGet->setText(tr("Readback")); + btnLoraMasterSet->setText(tr("Set")); + btnNtpGet->setText(tr("Readback")); + btnNtpSet->setText(tr("Set")); + btnSyncTime->setText(tr("Verify to Computer time")); + checkBoxBrightness->setText(tr("Brightness")); + checkBoxScreenSwitch->setText(tr("Screen on/off")); + checkBoxVolume->setText(tr("Volume")); + fdIsLan->setText(tr("LAN")); + fdNtpServer->setPlaceholderText(tr("NTP Server address")); + fdSyncGet->setText(tr("Readback")); + fdTimeZoneSet->setText(tr("Set")); + groupBox->setTitle(tr("Enable Synchronous playing")); + groupBox_5->setTitle(tr("Cur time of controller")); + groupNTP->setTitle(tr("NTP Server")); + label->setText(tr("TimeZone")); + labelIdCode->setText(tr("Identification Code")); + labelNtpServerAddress->setText(tr("NTP Server address")); + labelSyncTimeInterval->setText(tr("Sync time interval")); + labelTimeOffset->setText(tr("Time offset(msec)")); + labelVerifyClockConfiguration->setText(tr("Verify Clock Configuration")); + labelmintime->setText(tr("(min/time)")); + lbLang->setText(tr("Language:")); + lineEditIdCode->setPlaceholderText(tr("identification code")); + lineEdit_3->setPlaceholderText(tr("Sync time interval")); + btnSyncSet->setText(tr("Set")); + fdMaster->setText(tr("Master")); + fdSlave->setText(tr("Slave")); +} +void CtrlVerifyClockPanel::dealGetSync(QJsonDocument &json) { + QString strType = json["time"].toString().toLower(); + if(strType=="serial" || strType=="lan") { + if(strType=="serial") fdIsLora->setChecked(true); + else fdIsLan->setChecked(true); + lineEditIdCode->setText(json["identificationCode"].toString()); + lineEditTimeOffset->setText(QString::number(json["delaySync"].toInt())); + labelIdCode->setVisible(true); + lineEditIdCode->setVisible(true); + labelTimeOffset->setVisible(true); + lineEditTimeOffset->setVisible(true); + lineEdit_3->setVisible(false); + labelSyncTimeInterval->setVisible(false); + labelmintime->setVisible(false); + checkBoxScreenSwitch->setChecked(json["screenSwitch"].toString()!="NONE"); + checkBoxVolume->setChecked(json["volume"].toString()!="NONE"); + checkBoxBrightness->setChecked(json["brightness"].toString()!="NONE"); + checkBoxScreenSwitch->setVisible(true); + checkBoxVolume->setVisible(true); + checkBoxBrightness->setVisible(true); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); + } else if(strType=="ntp") { + fdIsNTP->setChecked(true); + lineEdit_3->setText(QString::number(json["checkNtpTime"].toInt())); + labelIdCode->setVisible(false); + lineEditIdCode->setVisible(false); + labelTimeOffset->setVisible(false); + lineEditTimeOffset->setVisible(false); + lineEdit_3->setVisible(true); + labelSyncTimeInterval->setVisible(true); + labelmintime->setVisible(true); + groupBox_4->setVisible(false); + fdMaster->setVisible(false); + fdSlave->setVisible(false); + btnLoraMasterSet->setVisible(false); + btnLoraMasterGet->setVisible(false); + checkBoxScreenSwitch->setVisible(false); + checkBoxVolume->setVisible(false); + checkBoxBrightness->setVisible(false); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); + } else if(strType=="gps") { + fdIsGPS->setChecked(true); + labelIdCode->setVisible(false); + lineEditIdCode->setVisible(false); + labelTimeOffset->setVisible(false); + lineEditTimeOffset->setVisible(false); + labelSyncTimeInterval->setVisible(false); + lineEdit_3->setVisible(false); + labelmintime->setVisible(false); + groupBox_4->setVisible(false); + fdMaster->setVisible(false); + fdSlave->setVisible(false); + btnLoraMasterSet->setVisible(false); + btnLoraMasterGet->setVisible(false); + checkBoxScreenSwitch->setVisible(false); + checkBoxVolume->setVisible(false); + checkBoxBrightness->setVisible(false); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); + } +} +void CtrlVerifyClockPanel::OnRadioButton()//gps +{ + labelIdCode->setVisible(false); + lineEditIdCode->setVisible(false); + labelTimeOffset->setVisible(false); + lineEditTimeOffset->setVisible(false); + labelSyncTimeInterval->setVisible(false); + lineEdit_3->setVisible(false); + labelmintime->setVisible(false); + groupBox_4->setVisible(false); + fdMaster->setVisible(false); + fdSlave->setVisible(false); + btnLoraMasterSet->setVisible(false); + btnLoraMasterGet->setVisible(false); + checkBoxScreenSwitch->setVisible(false); + checkBoxVolume->setVisible(false); + checkBoxBrightness->setVisible(false); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); +} +void CtrlVerifyClockPanel::OnRadioButton2()//lora +{ + labelIdCode->setVisible(true); + lineEditIdCode->setVisible(true); + labelTimeOffset->setVisible(true); + lineEditTimeOffset->setVisible(true); + lineEdit_3->setVisible(false); + labelSyncTimeInterval->setVisible(false); + labelmintime->setVisible(false); + groupBox_4->setVisible(true); + fdMaster->setVisible(true); + fdSlave->setVisible(true); + btnLoraMasterSet->setVisible(true); + btnLoraMasterGet->setVisible(true); + checkBoxScreenSwitch->setVisible(true); + checkBoxVolume->setVisible(true); + checkBoxBrightness->setVisible(true); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); +} + +void CtrlVerifyClockPanel::OnRadioButton3()//ntp +{ + labelIdCode->setVisible(false); + lineEditIdCode->setVisible(false); + labelTimeOffset->setVisible(false); + lineEditTimeOffset->setVisible(false); + lineEdit_3->setVisible(true); + labelSyncTimeInterval->setVisible(true); + labelmintime->setVisible(true); + groupBox_4->setVisible(false); + fdMaster->setVisible(false); + fdSlave->setVisible(false); + btnLoraMasterSet->setVisible(false); + btnLoraMasterGet->setVisible(false); + checkBoxScreenSwitch->setVisible(false); + checkBoxVolume->setVisible(false); + checkBoxBrightness->setVisible(false); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); +} +void CtrlVerifyClockPanel::OnRadioButton6() { + labelIdCode->setVisible(true); + lineEditIdCode->setVisible(true); + labelTimeOffset->setVisible(true); + lineEditTimeOffset->setVisible(true); + lineEdit_3->setVisible(false); + labelSyncTimeInterval->setVisible(false); + labelmintime->setVisible(false); + groupBox_4->setVisible(true); + fdMaster->setVisible(true); + fdSlave->setVisible(true); + btnLoraMasterSet->setVisible(true); + btnLoraMasterGet->setVisible(true); + checkBoxScreenSwitch->setVisible(true); + checkBoxVolume->setVisible(true); + checkBoxBrightness->setVisible(true); + btnSyncSet->setVisible(true); + fdSyncGet->setVisible(true); +} diff --git a/LedOK/wDevicesManager/ctrlverifyclockpanel.h b/LedOK/device/ctrlverifyclockpanel.h similarity index 95% rename from LedOK/wDevicesManager/ctrlverifyclockpanel.h rename to LedOK/device/ctrlverifyclockpanel.h index 3d4f4c5..135b359 100644 --- a/LedOK/wDevicesManager/ctrlverifyclockpanel.h +++ b/LedOK/device/ctrlverifyclockpanel.h @@ -59,12 +59,12 @@ private: QCheckBox *checkBoxVolume; QCheckBox *checkBoxScreenSwitch; QHBoxLayout *horizontalLayout_7; - QPushButton *pushButtonSetSync; + QPushButton *btnSyncSet; QPushButton *fdSyncGet; QGroupBox *groupBox_4; QHBoxLayout *horizontalLayout_11; - QRadioButton *radioButton_4; - QRadioButton *radioButton_5; + QRadioButton *fdMaster; + QRadioButton *fdSlave; QHBoxLayout *horizontalLayout_12; QPushButton *btnLoraMasterSet; QPushButton *btnLoraMasterGet; diff --git a/LedOK/wDevicesManager/ledcard.cpp b/LedOK/device/ledcard.cpp similarity index 97% rename from LedOK/wDevicesManager/ledcard.cpp rename to LedOK/device/ledcard.cpp index 843dc44..f045a4b 100644 --- a/LedOK/wDevicesManager/ledcard.cpp +++ b/LedOK/device/ledcard.cpp @@ -1,48 +1,48 @@ -#include "ledcard.h" - -LedCard::LedCard(QObject *p) : QObject(p) { - -} - -void LedCard::copyLedCardHTTPGetParam(LedCard *p) -{ - m_strCardId = p->m_strCardId; - m_strCardIp = p->m_strCardIp; - if(p->m_strCardRemarkName!="") - m_strCardRemarkName=p->m_strCardRemarkName; - starterversionName = p->starterversionName ; - starterPort = p->starterPort ; - androidVersion = p->androidVersion ; - iHttpGetId = p->iHttpGetId ; - androidHeight = p->androidHeight ; - androidWidth = p->androidWidth ; - lastActive = p->lastActive ; -} -void LedCard::copyLedCardHTTPPostParam(LedCard *p) -{ - strIMEI =p->strIMEI ; - HardVersion =p->HardVersion ; - BrightnessLevel =p->BrightnessLevel ; - ScreenResolution =p->ScreenResolution ; - FirmwareVersion =p->FirmwareVersion ; -} -bool LedCard::CompareHTTPGetParam(LedCard *p) { - //这里只比较httpGet devicelist打算应答 - if(m_strCardIp!=p->m_strCardIp) return false; - if(m_strCardRemarkName!=p->m_strCardRemarkName) return false; - if(starterversionName!=p->starterversionName) return false; - if(androidVersion!=p->androidVersion) return false; - if(androidWidth!=p->androidWidth) return false; - if(androidHeight!=p->androidHeight) return false; - return true; -} -bool LedCard::CompareHTTPPostParam(LedCard *p) -{ - //这里只比较httpGet devicelist打算应答 - if(strIMEI!=p->strIMEI) return false; - if(HardVersion!=p->HardVersion) return false; - if(BrightnessLevel!=p->BrightnessLevel) return false; - if(ScreenResolution!=p->ScreenResolution) return false; - if(FirmwareVersion!=p->FirmwareVersion) return false; - return true; -} +#include "ledcard.h" + +LedCard::LedCard(QObject *p) : QObject(p) { + +} + +void LedCard::copyLedCardHTTPGetParam(LedCard *p) +{ + m_strCardId = p->m_strCardId; + m_strCardIp = p->m_strCardIp; + if(p->m_strCardRemarkName!="") + m_strCardRemarkName=p->m_strCardRemarkName; + starterversionName = p->starterversionName ; + starterPort = p->starterPort ; + androidVersion = p->androidVersion ; + iHttpGetId = p->iHttpGetId ; + androidHeight = p->androidHeight ; + androidWidth = p->androidWidth ; + lastActive = p->lastActive ; +} +void LedCard::copyLedCardHTTPPostParam(LedCard *p) +{ + strIMEI =p->strIMEI ; + HardVersion =p->HardVersion ; + BrightnessLevel =p->BrightnessLevel ; + ScreenResolution =p->ScreenResolution ; + FirmwareVersion =p->FirmwareVersion ; +} +bool LedCard::CompareHTTPGetParam(LedCard *p) { + //这里只比较httpGet devicelist打算应答 + if(m_strCardIp!=p->m_strCardIp) return false; + if(m_strCardRemarkName!=p->m_strCardRemarkName) return false; + if(starterversionName!=p->starterversionName) return false; + if(androidVersion!=p->androidVersion) return false; + if(androidWidth!=p->androidWidth) return false; + if(androidHeight!=p->androidHeight) return false; + return true; +} +bool LedCard::CompareHTTPPostParam(LedCard *p) +{ + //这里只比较httpGet devicelist打算应答 + if(strIMEI!=p->strIMEI) return false; + if(HardVersion!=p->HardVersion) return false; + if(BrightnessLevel!=p->BrightnessLevel) return false; + if(ScreenResolution!=p->ScreenResolution) return false; + if(FirmwareVersion!=p->FirmwareVersion) return false; + return true; +} diff --git a/LedOK/wDevicesManager/ledcard.h b/LedOK/device/ledcard.h similarity index 91% rename from LedOK/wDevicesManager/ledcard.h rename to LedOK/device/ledcard.h index 34074ae..faefbb4 100644 --- a/LedOK/wDevicesManager/ledcard.h +++ b/LedOK/device/ledcard.h @@ -1,58 +1,60 @@ -#ifndef LEDCARD_H -#define LEDCARD_H - -#include - -class LedCard : public QObject { - Q_OBJECT - Q_PROPERTY(QString strCardId MEMBER m_strCardId NOTIFY CardIdChanged) - Q_PROPERTY(QString strCardIp MEMBER m_strCardIp NOTIFY CardIpChanged) - Q_PROPERTY(qint32 iCardWidth MEMBER m_iWidth NOTIFY WidthChanged) - Q_PROPERTY(qint32 iCardHeight MEMBER m_iHeight NOTIFY HeightChanged) - Q_PROPERTY(QString strCardRemarkName MEMBER m_strCardRemarkName NOTIFY CardRemarkNameChanged) - -public: - LedCard(QObject *p = nullptr); -signals: - void CardIdChanged(const QString &); - void CardIpChanged(const QString &); - void WidthChanged(qint32 t); - void HeightChanged(qint32 t); - void CardRemarkNameChanged(const QString &); -public: - //属性 - QString m_strCardId; - QString m_strCardIp; - qint32 m_iWidth = 0; - qint32 m_iHeight = 0; - QString m_strCardRemarkName = ""; - QString starterversionName = ""; - int starterPort = 0; - QString androidVersion = ""; - int iHttpGetId = 0; - int androidHeight = 0; - //int iCardSystemVersion = 0; - int brightness = 255; - int androidWidth = 0; - int lastActive = 0; - QString strIMEI=""; - QString HardVersion="0000"; - int BrightnessLevel=255; - QString ScreenResolution=""; - QString FirmwareVersion=""; - QString strXixunplayerVersion=""; - int strXixunplayerVersionCode=0; - bool bPassword=false; - void copyLedCardHTTPGetParam(LedCard *p); - void copyLedCardHTTPPostParam(LedCard *p); - bool CompareHTTPGetParam(LedCard *p); - bool CompareHTTPPostParam(LedCard *p); - //状态 - bool m_bLockStatus=true; - bool m_bPowerStatus=true; - bool m_bOnLine=true; - - -}; - -#endif // LEDCARD_H +#ifndef LEDCARD_H +#define LEDCARD_H + +#include +#include +class LedCard : public QObject { + Q_OBJECT + Q_PROPERTY(QString strCardId MEMBER m_strCardId NOTIFY CardIdChanged) + Q_PROPERTY(QString strCardIp MEMBER m_strCardIp NOTIFY CardIpChanged) + Q_PROPERTY(qint32 iCardWidth MEMBER m_iWidth NOTIFY WidthChanged) + Q_PROPERTY(qint32 iCardHeight MEMBER m_iHeight NOTIFY HeightChanged) + Q_PROPERTY(QString strCardRemarkName MEMBER m_strCardRemarkName NOTIFY CardRemarkNameChanged) + +public: + LedCard(QObject *p = nullptr); + ~LedCard(){ + qDebug()<<"~~~~LedCard"; + } +signals: + void CardIdChanged(const QString &); + void CardIpChanged(const QString &); + void WidthChanged(qint32 t); + void HeightChanged(qint32 t); + void CardRemarkNameChanged(const QString &); +public: + //属性 + QString m_strCardId; + QString m_strCardIp; + qint32 m_iWidth = 0; + qint32 m_iHeight = 0; + QString m_strCardRemarkName = ""; + QString starterversionName = ""; + int starterPort = 0; + QString androidVersion = ""; + int iHttpGetId = 0; + int androidHeight = 0; + int bright{100}; + int androidWidth = 0; + int lastActive = 0; + QString strIMEI=""; + QString HardVersion="0000"; + int BrightnessLevel=255; + QString ScreenResolution=""; + QString FirmwareVersion=""; + QString strXixunplayerVersion=""; + int strXixunplayerVersionCode=0; + bool bPassword=false; + void copyLedCardHTTPGetParam(LedCard *p); + void copyLedCardHTTPPostParam(LedCard *p); + bool CompareHTTPGetParam(LedCard *p); + bool CompareHTTPPostParam(LedCard *p); + //状态 + bool m_bLockStatus=true; + bool m_bPowerStatus=true; + bool m_bOnLine=true; + + +}; + +#endif // LEDCARD_H diff --git a/LedOK/wDevicesManager/specialdlg - 副本.cpp b/LedOK/device/specialdlg - 副本.cpp similarity index 97% rename from LedOK/wDevicesManager/specialdlg - 副本.cpp rename to LedOK/device/specialdlg - 副本.cpp index 4e5a1e6..8a6fafd 100644 --- a/LedOK/wDevicesManager/specialdlg - 副本.cpp +++ b/LedOK/device/specialdlg - 副本.cpp @@ -1,75 +1,75 @@ -#include "specialdlg.h" -#include "tools.h" -#include "globaldefine.h" -#include "base/waitingdlg.h" -#include "LoUIClass/qiplineedit.h" -#include -#include - -SpecialDlg::SpecialDlg(QWidget *parent) : QDialog(parent) { - resize(300, 100); - setWindowTitle(tr("Specify IP")); - - auto vBox = new QVBoxLayout(this); - vBox->addStretch(); - - auto hBox = new QHBoxLayout(); - hBox->addStretch(); - - auto label = new QLabel(tr("Specify IP")); - label->setAlignment(Qt::AlignCenter); - hBox->addWidget(label); - - auto fdIP = new QIPLineEdit(); - fdIP->setMinimumWidth(160); - hBox->addWidget(fdIP); - - hBox->addStretch(); - - vBox->addLayout(hBox); - vBox->addStretch(); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - - auto bnSearch = new QPushButton(tr("Search")); - hBox->addWidget(bnSearch); - - auto btnCancel = new QPushButton(tr("Cancel")); - connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject); - hBox->addWidget(btnCancel); - - hBox->addStretch(); - - vBox->addLayout(hBox); - - //绑定信号和槽函数 - connect(bnSearch, &QPushButton::clicked, this, [this, fdIP] { - QString strTempIp = fdIP->text(); - if(strTempIp=="...") { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input IP address!")); - return; - } else if(! isTextValid(strTempIp)) { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Your IP Address is Invalid!")); - return; - } - auto waitingDlg = new WaitingDlg(gMainWin, tr("Search")+" ..."); - waitingDlg->show(); - auto reply = Tools::netManager().get(reqForJson("http://"+strTempIp+":3000/deviceList?fromDetector=true")); - //在该ip的3000端口get方法deviceList,可以一次性获取到局域网中设备列表的详细信息 - connect(reply, &QNetworkReply::finished, this, [reply, this, waitingDlg] { - QJsonDocument json; - QString err = parseReplyJson(reply); - if(! err.isEmpty()) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - waitingDlg->success(); - close(); - QStringList keys = json.object().keys(); - qDebug()<<"json size"<parseInfo(json[key].toObject(), ""); - }); - }); -} +#include "specialdlg.h" +#include "tools.h" +#include "globaldefine.h" +#include "base/waitingdlg.h" +#include "LoUIClass/qiplineedit.h" +#include +#include + +SpecialDlg::SpecialDlg(QWidget *parent) : QDialog(parent) { + resize(300, 100); + setWindowTitle(tr("Specify IP")); + + auto vBox = new QVBoxLayout(this); + vBox->addStretch(); + + auto hBox = new QHBoxLayout(); + hBox->addStretch(); + + auto label = new QLabel(tr("Specify IP")); + label->setAlignment(Qt::AlignCenter); + hBox->addWidget(label); + + auto fdIP = new QIPLineEdit(); + fdIP->setMinimumWidth(160); + hBox->addWidget(fdIP); + + hBox->addStretch(); + + vBox->addLayout(hBox); + vBox->addStretch(); + + hBox = new QHBoxLayout(); + hBox->addStretch(); + + auto bnSearch = new QPushButton(tr("Search")); + hBox->addWidget(bnSearch); + + auto btnCancel = new QPushButton(tr("Cancel")); + connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject); + hBox->addWidget(btnCancel); + + hBox->addStretch(); + + vBox->addLayout(hBox); + + //绑定信号和槽函数 + connect(bnSearch, &QPushButton::clicked, this, [this, fdIP] { + QString strTempIp = fdIP->text(); + if(strTempIp=="...") { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input IP address!")); + return; + } else if(! isTextValid(strTempIp)) { + QMessageBox::warning(gMainWin, tr("Attention"), tr("Your IP Address is Invalid!")); + return; + } + auto waitingDlg = new WaitingDlg(gMainWin, tr("Search")+" ..."); + waitingDlg->show(); + auto reply = Tools::netManager().get(reqForJson("http://"+strTempIp+":3000/deviceList?fromDetector=true")); + //在该ip的3000端口get方法deviceList,可以一次性获取到局域网中设备列表的详细信息 + connect(reply, &QNetworkReply::finished, this, [reply, this, waitingDlg] { + QJsonDocument json; + QString err = parseReplyJson(reply); + if(! err.isEmpty()) { + waitingDlg->close(); + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + waitingDlg->success(); + close(); + QStringList keys = json.object().keys(); + qDebug()<<"json size"<parseInfo(json[key].toObject(), ""); + }); + }); +} diff --git a/LedOK/wDevicesManager/specialdlg - 副本.h b/LedOK/device/specialdlg - 副本.h similarity index 93% rename from LedOK/wDevicesManager/specialdlg - 副本.h rename to LedOK/device/specialdlg - 副本.h index cdafa95..ed8804c 100644 --- a/LedOK/wDevicesManager/specialdlg - 副本.h +++ b/LedOK/device/specialdlg - 副本.h @@ -1,12 +1,12 @@ -#ifndef SPECIALDLG_H -#define SPECIALDLG_H - -#include - -class SpecialDlg : public QDialog { - Q_OBJECT -public: - explicit SpecialDlg(QWidget *); -}; - -#endif // SPECIALDLG_H +#ifndef SPECIALDLG_H +#define SPECIALDLG_H + +#include + +class SpecialDlg : public QDialog { + Q_OBJECT +public: + explicit SpecialDlg(QWidget *); +}; + +#endif // SPECIALDLG_H diff --git a/LedOK/device/upgradeapkdialog.cpp b/LedOK/device/upgradeapkdialog.cpp new file mode 100644 index 0000000..6b85be9 --- /dev/null +++ b/LedOK/device/upgradeapkdialog.cpp @@ -0,0 +1,647 @@ +#include "upgradeapkdialog.h" +#include "gutil/qcore.h" +#include "gutil/qgui.h" +#include "gutil/qnetwork.h" +#include "base/waitingdlg.h" +#include "tools.h" +#include +#include +#include +#include +#include +#include +#include +#include + +UpgradeApkDialog::UpgradeApkDialog(QWidget *parent) : QDialog(parent) { + resize(1280, 720); + setWindowFlag(Qt::WindowMaximizeButtonHint); + setWindowState(Qt::WindowMaximized); + + setWindowTitle(tr("Update APK")); + + auto vBox = new VBox(this); + auto hBox = new HBox(vBox); + + auto btnSelectOnlineApk = new QPushButton(tr("Select Online APK")); + btnSelectOnlineApk->setMinimumSize(QSize(100, 30)); + btnSelectOnlineApk->setProperty("ssType", "progManageTool"); + hBox->addWidget(btnSelectOnlineApk); + + auto btnSelectApk = new QPushButton(tr("Select apk")); + btnSelectApk->setMinimumSize(QSize(100, 30)); + btnSelectApk->setProperty("ssType", "progManageTool"); + hBox->addWidget(btnSelectApk); + + auto btnSelectFpga = new QPushButton(tr("Select Fpga")); + btnSelectFpga->setMinimumSize(QSize(100, 30)); + btnSelectFpga->setProperty("ssType", "progManageTool"); + hBox->addWidget(btnSelectFpga); + + auto fdFileName = new QLabel; + fdFileName->setMinimumSize(200, 30); + fdFileName->setStyleSheet("background-color: #fff;"); + hBox->addWidget(fdFileName); + + connect(btnSelectApk, &QPushButton::clicked, this, [=] { + filePath = QFileDialog::getOpenFileName(this, "Open file", QString(), "apk package (*.apk *.zip)"); + if(filePath.isEmpty()) return; + fileId = ""; + fdFileName->setText(QFileInfo(filePath).fileName()); + }); + connect(btnSelectFpga, &QPushButton::clicked, this, [=] { + filePath = QFileDialog::getOpenFileName(this, "Open File", QString(), "rpd package (*.rpd)"); + if(filePath.isEmpty()) return; + fileId = ""; + fdFileName->setText(QFileInfo(filePath).fileName()); + }); + connect(btnSelectOnlineApk, &QPushButton::clicked, this, [=] { + NetReq req("https://www.ledokcloud.com/aips4/screen/upgrade/getGeneric?type=0&page=1&limit=10"); + req.setRawHeader("token","e183653f716cb150ebf3b4f8a83c95e7"); + auto reply = req.timeout(60000).post(""); + connect(reply, &QNetworkReply::finished, this, [=] { + QJsonDocument json; + auto err = errStrWithData(reply, &json); + if(! err.isEmpty()) { + QMessageBox::critical(this, "Error", err); + return; + } + if(json["code"].toInt()) { + QMessageBox::critical(this, "Error", json["msg"].toString()); + return; + } + auto files = json["page"]["list"].toArray(); + if(files.isEmpty()) { + QMessageBox::critical(this, "Error", tr("No Files")); + return; + } + QDialog dlg(this); + dlg.setWindowFlag(Qt::WindowContextHelpButtonHint, false); + dlg.setWindowTitle(tr("Select Online APK")); + dlg.resize(800, 500); + + auto vBox = new VBox(&dlg); + vBox->setContentsMargins(0,0,0,0); + + auto table = new Table{ + {"name", tr("Name"), 200, QHeaderView::Stretch}, + {"size", tr("Size"), 80}, + {"createTime", tr("Create Time"), 150} + }; + table->setDefs(); + table->setSelectionMode(QAbstractItemView::SingleSelection); + foreach(auto file, files) { + auto rr = table->appendRow(); + table->setText(rr, "name", file["fileName"].toString()+"."+file["suffix"].toString()); + table->setText(rr, "size", byteSizeStr(file["fileSize"].toInt()))->setTextAlignment(AlignRight); + table->setText(rr, "createTime", file["createTime"].toString()); + table->setData(rr, 0, file["fileId"].toString()); + } + connect(table, &Table::cellDoubleClicked, &dlg, [=, &dlg](int row) { + fdFileName->setText(table->text(row, "name")); + fileId = table->data(row, 0).toString(); + filePath = ""; + dlg.accept(); + }); + vBox->addWidget(table); + + auto hBox = new HBox(vBox); + hBox->addStretch(); + + auto btnOk = new QPushButton("确定"); + btnOk->setMinimumWidth(80); + connect(btnOk, &QPushButton::clicked, &dlg, [=, &dlg] { + auto sels = table->selectedRanges(); + if(sels.isEmpty()) { + QMessageBox::warning(&dlg, "Warning", "请选择文件"); + return; + } + auto row = sels[0].topRow(); + fdFileName->setText(table->text(row, "name")); + fileId = table->data(row, 0).toString(); + filePath = ""; + dlg.accept(); + }); + hBox->addWidget(btnOk); + hBox->addStretch(); + + auto btnClose = new QPushButton("关闭"); + btnClose->setMinimumWidth(80); + connect(btnClose, &QPushButton::clicked, &dlg, &QDialog::reject); + hBox->addWidget(btnClose); + hBox->addStretch(); + + dlg.exec(); + }); + }); + + auto btnUpgread = new QPushButton(tr("Upgrade")); + btnUpgread->setMinimumSize(QSize(80, 30)); + btnUpgread->setProperty("ssType", "progManageTool"); + connect(btnUpgread, &QPushButton::clicked, this, [=] { + auto fileName = fdFileName->text(); + if(fileName.length() < 3) return; + int cnt = table->topLevelItemCount(); + QList items; + for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) { + auto item = static_cast(table->topLevelItem(i)); + if(item->isUpdating) { + QMessageBox::information(this, tr("Tip"), tr("Is upgrading now. Please wait")); + return; + } + if(item->mCard->bPassword && item->mCard->m_bLockStatus && item->m_lockFlag) { + item->setResult(tr("This screen is encrypted"), Qt::red); + return; + } + items.append(item); + } + if(items.isEmpty()) { + QMessageBox::information(this, tr("Tip"), tr("NoSelectedController")); + return; + } + QByteArray fileData; + if(! filePath.isEmpty()) { + QFile file(filePath); + if(! file.exists()) return; + if(! file.open(QIODevice::ReadOnly)) return; + fileData = file.readAll(); + file.close(); + } else if(! fileId.isEmpty()) { + auto waitingDlg = new WaitingDlg(this, tr("Downloading Online File")+" ..."); + waitingDlg->show(); + auto reply = NetReq("https://www.ledokcloud.com/aips4/sys/file/download/"+fileId).timeout(120000).get(); + QEventLoop loop; + connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); + connect(reply, &QNetworkReply::downloadProgress, waitingDlg, [=](qint64 bytesReceived, qint64 bytesTotal) { + waitingDlg->fdText->setText(tr("Downloading Online File")+" "+QString::number(bytesReceived*100/bytesTotal)+" %"); + }); + loop.exec(QEventLoop::ExcludeUserInputEvents); + waitingDlg->close(); + auto err = errStr(reply); + fileData = reply->readAll(); + if(! err.isEmpty()) { + if(! fileData.isEmpty()) err += "\n"+fileData; + QMessageBox::critical(this, tr("Error"), err); + return; + } + if(fileData.isEmpty()) { + QMessageBox::critical(this, tr("Error"), tr("Online file is empty")); + return; + } + } + auto nameBytes = fileName.toUtf8(); + auto Boundary = "----QtLedOK_.oOo._"+QUuid::createUuid().toByteArray(QUuid::WithoutBraces); + QByteArray data; + data.append("--").append(Boundary).append("\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\n10005\r\n"); + data.append("--").append(Boundary).append("\r\nContent-Disposition: form-data; name=\"").append(nameBytes).append("\"; filename=\"").append(nameBytes).append("\"\r\n\r\n").append(fileData).append("\r\n"); + data.append("--").append(Boundary).append("--\r\n"); + bool isApk = ! fileName.endsWith(".rpd", Qt::CaseInsensitive); + foreach(auto item, items) { + item->setResult(tr("Uploading")+" ..."); + item->mProgress->setValue(0); + item->isUpdating = true; + NetReq req("http://"+item->mCard->m_strCardIp+":2016/upload?type="+(isApk ? "software":"hardware")); + auto reply = req.timeout(120000).type("multipart/form-data; boundary="+Boundary).post(data); + connect(reply, &QNetworkReply::uploadProgress, item, [item](qint64 bytesSent, qint64 bytesTotal) { + if(bytesTotal<=0) return; + item->mProgress->setValue(bytesSent*100/bytesTotal); + }); + connect(reply, &QNetworkReply::finished, item, [=] { + QString err = errStrWithData(reply); + if(! err.isEmpty()) { + item->setResult(tr("Upload error")+": "+err, Qt::red); + item->isUpdating = false; + return; + } + item->mProgress->setValue(100); + item->setResult(tr("Installing")+" ..."); + QJsonObject json; + if(isApk) { + json.insert("_id", "UpgradeSoftware"); + json.insert("_type", "UpgradeSoftware"); + json.insert("fileName", fileName); + json.insert("isCustom", true); + } else { + json.insert("_id", "SynchronousHardwareVersion"); + json.insert("_type", "SynchronousHardwareVersion"); + } + auto reply = NetReq("http://"+item->mCard->m_strCardIp+":2016/settings").timeout(120000).post(json); + connect(reply, &QNetworkReply::finished, item, [=] { + item->isUpdating = false; + QString err = errStrWithData(reply); + if(! err.isEmpty()) { + item->setResult(tr("Install error")+": "+err, Qt::red); + return; + } + item->setResult(tr("Install success"), Qt::darkGreen); + if(isApk) item->OnCheckSoftVersions(); + else item->OnCheckFpgaVersions(); + }); + }); + } + }); + hBox->addWidget(btnUpgread); + hBox->addStretch(); + + hBox->addWidget(new QLabel("APK:")); + + auto fdApk = new QComboBox; + fdApk->setMinimumWidth(200); + fdApk->setEditable(true); + fdApk->addItem("com.xixun.xixunplayer"); + fdApk->addItem("com.xixun.joey.cardsystem"); + fdApk->addItem("com.xixun.joey.systemcore"); + fdApk->addItem("net.sysolution.taxiapp"); + fdApk->addItem("net.sysolution.starter"); + fdApk->addItem("com.xixun.display"); + fdApk->addItem("com.xixun.xy.conn"); + fdApk->addItem("com.xixun.xy.update"); + fdApk->addItem("net.sysolution.basicapp"); + hBox->addWidget(fdApk); + + auto btnUninstall = new QPushButton(tr("Uninstall")); + btnUninstall->setMinimumSize(80, 30); + btnUninstall->setProperty("ssType", "progManageTool"); + connect(btnUninstall, &QPushButton::clicked, this, [this, fdApk] { + auto strApkName = fdApk->currentText(); + if(strApkName.isEmpty()) { + QMessageBox::information(gMainWin, tr("Tip"), "APK is Empty"); + return; + } + if(! strApkName.endsWith(".xixunplayer") && ! strApkName.endsWith(".taxiapp") && QMessageBox::warning(gMainWin, tr("Reminder"), tr("Reminder: Uninstalling this program may cause the device to offline, cannot be found, lost configs and have a black screen. Please uninstall with caution!")+"\n"+tr("Do you want to continue?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return; + int cnt = table->topLevelItemCount(); + for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) { + auto item = static_cast(table->topLevelItem(i)); + item->setResult(tr("Uninstalling")+" ..."); + QJsonObject json; + json.insert("_id", "UninstallSoftware"); + json.insert("_type", "UninstallSoftware"); + json.insert("packageName", strApkName); + auto reply = NetReq("http://"+item->mCard->m_strCardIp+":2016/settings").timeout(120000).post(json); + connect(reply, &QNetworkReply::finished, this, [reply, item, strApkName] { + QString err = errStrWithData(reply); + if(! err.isEmpty()) { + item->setResult(tr("Uninstall error")+": "+err, Qt::red); + return; + } + item->setResult(tr("Uninstall success"), Qt::darkGreen); + }); + } + }); + hBox->addWidget(btnUninstall); + + auto btnCheck = new QPushButton(tr("check running state")); + btnCheck->setMinimumSize(QSize(140, 30)); + btnCheck->setProperty("ssType", "progManageTool"); + connect(btnCheck, &QPushButton::clicked, this, [this, fdApk] { + QString strApkName = fdApk->currentText(); + int cnt = table->topLevelItemCount(); + for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) { + auto item = static_cast(table->topLevelItem(i)); + item->setResult(tr("Check apk running status")); + QJsonObject json; + json.insert("_id", "IsSoftwareRunning"); + json.insert("_type", "IsSoftwareRunning"); + json.insert("packageName", strApkName); + auto reply = NetReq("http://"+item->mCard->m_strCardIp+":2016/settings").timeout(120000).post(json); + connect(reply, &QNetworkReply::finished, this, [reply, item, strApkName] { + QJsonDocument json; + QString err = errStrWithData(reply, &json); + if(! err.isEmpty()) { + item->setResult(tr("Check error")+": "+err, Qt::red); + return; + } + if(json["running"].toBool()) item->setResult(tr("Running"), Qt::darkGreen); + else item->setResult(tr("Not running"), Qt::red); + }); + } + }); + hBox->addWidget(btnCheck); + + + hBox = new HBox(vBox); + auto label = new QLabel; + hBox->addWidget(label); + + hBox->addStretch(); + + auto btnRefresh = new QPushButton(tr("Refresh")); + btnRefresh->setMinimumSize(QSize(0, 30)); + btnRefresh->setProperty("ssType", "progManageTool"); + connect(btnRefresh, &QPushButton::clicked, this, [this, label] { + table->clear(); + table->onCheckAll(false); + int iCount = gDevicePanel->mLedCards.count(); + for(int i=0;imLedCards.at(i)); + label->setText(tr("All")+":"+QString::number(iCount)); + }); + hBox->addWidget(btnRefresh); + + auto txtSearch = new QLineEdit(); + txtSearch->setClearButtonEnabled(true); + txtSearch->setMaximumWidth(200); + txtSearch->addAction(new QAction(QIcon(":/res/program/bnSearch.png"), ""), QLineEdit::LeadingPosition); + connect(txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &))); + hBox->addWidget(txtSearch); + + + table = new LoQTreeWidget(); + table->setProperty("ssType", "topList"); + vBox->addWidget(table); + + hBox = new HBox(vBox); + hBox->addStretch(); + + auto pushButtonCancel = new QPushButton(tr("Cancel")); + pushButtonCancel->setMinimumSize(QSize(0, 30)); + pushButtonCancel->setProperty("ssType", "progManageTool"); + connect(pushButtonCancel, &QPushButton::clicked, this, &UpgradeApkDialog::reject); + hBox->addWidget(pushButtonCancel); + + + m_headerItem = new QTreeWidgetItem(); + for(int i=1; isetTextAlignment(i, Qt::AlignCenter); + m_headerItem->setText(Upgrade_Check, ""); + m_headerItem->setText(Upgrade_SCREEN_ID, tr("Screen ID")); + m_headerItem->setText(Upgrade_ONLINE, tr("Online")); + m_headerItem->setText(Upgrade_SCREEN_IP, tr("Screen IP")); + m_headerItem->setText(Upgrade_ENCRYPT, tr("Security")); + m_headerItem->setText(Upgrade_REMARK_NAME, tr("Remark Name")); + m_headerItem->setText(Upgrade_PROGRESS, tr("Progress")); + m_headerItem->setText(Upgrade_Remark, tr("State")); + m_headerItem->setText(Upgrade_XIXUNPLAYER_VERSION, tr("xixunplayer")); + m_headerItem->setText(Upgrade_CARDSYSTEM_VERSION, tr("cardsystem")); + m_headerItem->setText(Upgrade_STARTER_VERSION, tr("starter")); + m_headerItem->setText(Upgrade_TAXIAPP_VERSION, tr("taxiapp")); + m_headerItem->setText(Upgrade_DISPLAYER_VERSION, tr("displayer")); + m_headerItem->setText(Upgrade_FPAG_VERSION, tr("FPGA")); + m_headerItem->setText(Upgrade_CONNECTION_VERSION, tr("connection")); + m_headerItem->setText(Upgrade_UPDATE_VERSION, tr("update")); + + table->setHeaderItem(m_headerItem); + table->header()->setSectionResizeMode(Upgrade_Check, QHeaderView::Fixed); + table->setColumnWidth(Upgrade_Check, 40); + table->header()->setSectionResizeMode(Upgrade_SCREEN_ID, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_ONLINE, QHeaderView::Fixed); + table->setColumnWidth(Upgrade_ONLINE, 40); + table->header()->setSectionResizeMode(Upgrade_SCREEN_IP, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_ENCRYPT, QHeaderView::Fixed); + table->setColumnWidth(Upgrade_ENCRYPT, 40); + table->header()->setSectionResizeMode(Upgrade_PROGRESS, QHeaderView::Fixed); + table->setColumnWidth(Upgrade_PROGRESS, 100); + table->header()->setSectionResizeMode(Upgrade_XIXUNPLAYER_VERSION, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_CARDSYSTEM_VERSION, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_STARTER_VERSION, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_TAXIAPP_VERSION, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_DISPLAYER_VERSION, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_FPAG_VERSION, QHeaderView::Fixed); + table->setColumnWidth(Upgrade_FPAG_VERSION, 100); + table->header()->setSectionResizeMode(Upgrade_Remark, QHeaderView::Stretch); + table->header()->setSectionResizeMode(Upgrade_REMARK_NAME, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_CONNECTION_VERSION, QHeaderView::ResizeToContents); + table->header()->setSectionResizeMode(Upgrade_UPDATE_VERSION, QHeaderView::ResizeToContents); + + int iCount = gDevicePanel->mLedCards.count(); + for(int i=0; imLedCards.at(i)); + label->setText(tr("All")+":"+QString::number(iCount)); +} + +void UpgradeApkDialog::onAddLedCard(LedCard *card) { + int iExistFlg=0; + int cnt = table->topLevelItemCount(); + for(int i=0; i(table->topLevelItem(i))->mCard->m_strCardId; + if(strTempCardId == card->m_strCardId) { + iExistFlg=1; + static_cast(table->topLevelItem(i))->SetItemParam(card); + break; + } + } + if(iExistFlg==0) new wUpgradeApkItem(card, table, this); +} + +void UpgradeApkDialog::keyPressEvent(QKeyEvent *ev) { + if(ev->key() == Qt::Key_F3) { + QMessageBox::warning(this, "Tip", tr("The encrypted control card can be upgraded directly")); + int cnt = table->topLevelItemCount(); + for(int i=0; i(table->topLevelItem(i))->m_lockFlag = false; + } +} +void UpgradeApkDialog::FilterProgram(const QString &strtemp) +{ + if (strtemp.isEmpty()) //显示全部 + { + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); + } + } + else + { + QList resultList = table->findItems(strtemp, Qt::MatchContains,Upgrade_SCREEN_ID); //搜索结果 + if (resultList.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + + QList resultList6 = table->findItems(strtemp, Qt::MatchContains,Upgrade_REMARK_NAME); //搜索结果 + if (resultList6.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList6.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + + + //QMessageBox::warning(this, "Export", "FilterProgram"); + QList resultList1 = table->findItems(strtemp, Qt::MatchContains,Upgrade_XIXUNPLAYER_VERSION); //搜索结果 + if (resultList1.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList1.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_SCREEN_IP); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_XIXUNPLAYER_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_CARDSYSTEM_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_TAXIAPP_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_DISPLAYER_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_STARTER_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_CONNECTION_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_UPDATE_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_FPAG_VERSION); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_Remark); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + if (resultList2.contains(topItem)) + table->setRowHidden(i,table->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + for (int i = 0; i< table->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = table->topLevelItem(i); + table->setRowHidden(i,table->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } +} diff --git a/LedOK/wDevicesManager/upgradeapkdialog.h b/LedOK/device/upgradeapkdialog.h similarity index 85% rename from LedOK/wDevicesManager/upgradeapkdialog.h rename to LedOK/device/upgradeapkdialog.h index 0ac855b..d5363c3 100644 --- a/LedOK/wDevicesManager/upgradeapkdialog.h +++ b/LedOK/device/upgradeapkdialog.h @@ -1,25 +1,25 @@ -#ifndef UPGRADEAPKDIALOG_H -#define UPGRADEAPKDIALOG_H - -#include -#include -#include "wupgradeapkitem.h" - -class UpgradeApkDialog : public QDialog { - Q_OBJECT -public: - explicit UpgradeApkDialog(QWidget *parent = nullptr); -protected: - virtual void keyPressEvent(QKeyEvent *ev); -protected slots: - void FilterProgram(const QString &strtemp); - -private: - void onAddLedCard(LedCard *p); - - LoQTreeWidget *wDevicePublishList; - QTreeWidgetItem *m_headerItem=nullptr; - QString m_strUrl=""; -}; - -#endif // UpgradeApkDialog_H +#ifndef UPGRADEAPKDIALOG_H +#define UPGRADEAPKDIALOG_H + +#include +#include +#include "wupgradeapkitem.h" + +class UpgradeApkDialog : public QDialog { + Q_OBJECT +public: + explicit UpgradeApkDialog(QWidget *parent = nullptr); + QString filePath, fileId; +protected: + virtual void keyPressEvent(QKeyEvent *ev); +protected slots: + void FilterProgram(const QString &strtemp); + +private: + void onAddLedCard(LedCard *p); + + LoQTreeWidget *table; + QTreeWidgetItem *m_headerItem=nullptr; +}; + +#endif // UpgradeApkDialog_H diff --git a/LedOK/device/wupgradeapkitem.cpp b/LedOK/device/wupgradeapkitem.cpp new file mode 100644 index 0000000..4291ab0 --- /dev/null +++ b/LedOK/device/wupgradeapkitem.cpp @@ -0,0 +1,138 @@ +#include "wupgradeapkitem.h" +#include "tools.h" +#include "base/x_uimsgboxok.h" +#include "passwordindlg.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +wUpgradeApkItem::wUpgradeApkItem(LedCard *pLedCard, LoQTreeWidget *parent, QWidget *pWnd) : QObject(parent), QTreeWidgetItem(UserType), m_parent(parent) { + m_pWnd=pWnd; + mCard=pLedCard; + setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); + setCheckState(0, Qt::Unchecked); + m_parent->addTopLevelItem(this); + m_ImageOnline = new QLabel(); + m_parent->setItemWidget(this, Upgrade_ONLINE, m_ImageOnline); + m_ImageOnline->setAlignment(Qt::AlignCenter); + for(int i=1; isetAlignment(Qt::AlignCenter); + mProgress->setStyleSheet("margin-top:8px; margin-bottom:8px; "); + m_parent->setItemWidget(this, Upgrade_PROGRESS, mProgress); + OnCheckSoftVersions(); + OnCheckFpgaVersions(); +} + +void wUpgradeApkItem::OnCheckFpgaVersions() { + QJsonObject json; + json.insert("_id", "CheckHardwareVersions"); + json.insert("_type", "CheckHardwareVersions"); + auto reply = Tools::netManager().post(reqForJson("http://"+mCard->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [reply, this] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) { + return; + } + QString strBuf; + auto vers = json["versions"].toArray(); + for(int i=0; im_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [reply, this] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) { + return; + } + auto apps = json["apps"].toArray(); + foreach(QJsonValue app, apps) { + QString packageName = app["packageName"].toString(); + QString verName = app["versionName"].toString(); + if(packageName=="com.xixun.xixunplayer") setData(Upgrade_XIXUNPLAYER_VERSION, 0, verName); + else if(packageName=="com.xixun.joey.cardsystem") setData(Upgrade_CARDSYSTEM_VERSION, 0, verName); + else if(packageName=="net.sysolution.starter") setData(Upgrade_STARTER_VERSION, 0, verName); + else if(packageName=="net.sysolution.taxiapp") setData(Upgrade_TAXIAPP_VERSION, 0, verName); + else if(packageName=="com.xixun.display") setData(Upgrade_DISPLAYER_VERSION, 0, verName); + else if(packageName=="com.xixun.xy.conn") setData(Upgrade_CONNECTION_VERSION, 0, verName); + else if(packageName=="com.xixun.xy.update") setData(Upgrade_UPDATE_VERSION, 0, verName); + } + }); +} +void wUpgradeApkItem::onVerifyLockPassword() { + bool ok; + auto pwd = QInputDialog::getText(gMainWin, tr("Input password"), tr("Input password"), QLineEdit::Password, QString(), &ok); + if(! ok) return; + QJsonObject json; + json.insert("_id", "VerifyPassword"); + json.insert("_type", "VerifyPassword"); + json.insert("pwd", pwd); + auto reply = Tools::netManager().post(reqForJson("http://"+mCard->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, this, [reply, this] { + QJsonDocument json; + QString err = checkReplyForJson(reply, &json); + if(! err.isEmpty()) { + QMessageBox::critical(gMainWin, tr("Error"), err); + return; + } + if(json["result"].toBool()) mCard->m_bLockStatus = false; + else { + mCard->m_bLockStatus = true; + QMessageBox::critical(gMainWin, tr("Tip Info"), tr("password is wrong")); + } + SetPasswordItem(mCard); + }); +} +void wUpgradeApkItem::SetPasswordItem(LedCard *p){ + if(p->bPassword) {//加过密 + if(m_bnLock==nullptr){ + m_bnLock = new QPushButton(m_pWnd); + m_bnLock->setStyleSheet("background-color:transparent;"); + m_bnLock->setStyleSheet("margin-left:12px; margin-right:12px;margin-top:12px; margin-bottom:12px;"); + m_parent->setItemWidget(this, Upgrade_ENCRYPT, m_bnLock); + connect(m_bnLock, SIGNAL(clicked()), this, SLOT(onVerifyLockPassword())); + } + if(p->m_bLockStatus) m_bnLock->setIcon(QIcon(":/res/device/Lock.png")); //如果已经验证通过密码显示绿色图标 + else m_bnLock->setIcon(QIcon(":/res/device/UnLock.png")); //如果没有验证显示蓝色锁图标 + m_parent->setItemWidget(this, Upgrade_ENCRYPT, m_bnLock); + } +} +void wUpgradeApkItem::setResult(QString tip, QColor color) { + setText(Upgrade_Remark, tip); + setToolTip(Upgrade_Remark, tip); + setForeground(Upgrade_Remark, color); +} +void wUpgradeApkItem::SetItemParam(LedCard *p) { + setData(Upgrade_SCREEN_ID, 0, p->m_strCardId); + setData(Upgrade_SCREEN_IP, 0, p->m_strCardIp); + mCard->m_strCardId = p->m_strCardId; + mCard->m_strCardIp = p->m_strCardIp; + mCard->m_bOnLine = p->m_bOnLine; + if(mCard->m_bOnLine) m_ImageOnline->setPixmap(QPixmap(mCard->m_bOnLine ? ":/res/device/O_Online.png" : ":/res/device/O_Offline.png")); + SetPasswordItem(mCard); + setData(Upgrade_REMARK_NAME, 0, p->m_strCardRemarkName); + OnCheckSoftVersions(); + OnCheckFpgaVersions(); +} diff --git a/LedOK/device/wupgradeapkitem.h b/LedOK/device/wupgradeapkitem.h new file mode 100644 index 0000000..9e8d71f --- /dev/null +++ b/LedOK/device/wupgradeapkitem.h @@ -0,0 +1,68 @@ +#ifndef WUPGRADEAPKITEM_H +#define WUPGRADEAPKITEM_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class wUpgradeApkItem : public QObject, public QTreeWidgetItem { + Q_OBJECT +public: + explicit wUpgradeApkItem(LedCard *pLedCard, LoQTreeWidget *parent = nullptr,QWidget *pWnd=nullptr); + void SetItemParam(LedCard *p); + void setResult(QString, QColor cr = Qt::blue); + + LedCard *mCard = nullptr; + bool isUpdating{false}; + bool m_lockFlag=true; + QLabel *m_ImageOnline=nullptr; + LoQTreeWidget *m_parent = nullptr; + QWidget *m_pWnd=nullptr; + QProgressBar *mProgress=nullptr; + QPushButton *m_bnLock = nullptr; +signals: + void sigUpgradeSuccess(); + void sigUpgradeFail(); + +public slots: + void onVerifyLockPassword(); + void OnCheckSoftVersions(); + void OnCheckFpgaVersions(); + +private: + void SetPasswordItem(LedCard *p); + void postFileTask(const QString& strUrl, const QString& strFilePath);//需要的数据 +}; +enum ENUM_DEVICE_PUBLISH_HEADERITEM +{ + Upgrade_Check=0, + Upgrade_SCREEN_ID, + Upgrade_ONLINE, + Upgrade_SCREEN_IP, + Upgrade_ENCRYPT, + Upgrade_REMARK_NAME, + Upgrade_PROGRESS, + Upgrade_Remark, + Upgrade_XIXUNPLAYER_VERSION, + Upgrade_CARDSYSTEM_VERSION, + Upgrade_STARTER_VERSION, + Upgrade_TAXIAPP_VERSION, + Upgrade_DISPLAYER_VERSION, + Upgrade_FPAG_VERSION, + Upgrade_CONNECTION_VERSION, + Upgrade_UPDATE_VERSION, + Upgrade_END, +}; + + +#endif // WPROGRAMPUBLISHITEM_H diff --git a/LedOK/devicectrlpanel.cpp b/LedOK/devicectrlpanel.cpp index f166eeb..413e4b4 100644 --- a/LedOK/devicectrlpanel.cpp +++ b/LedOK/devicectrlpanel.cpp @@ -1,146 +1,143 @@ -#include "devicectrlpanel.h" -#include "devicepanel.h" -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -QTextEdit *gFdResInfo; - -DeviceCtrlPanel::DeviceCtrlPanel(DevicePanel *parent) : QWidget(parent), mDevWgt(parent) { - auto vBox = new QVBoxLayout(this); - vBox->setContentsMargins(0,0,0,0); - vBox->setSpacing(0); - - auto hBox = new QHBoxLayout; - hBox->setSpacing(2); - - mBtnGrp = new QButtonGroup(this); - for(int i=0; isizePolicy(); - policy.setHorizontalPolicy(QSizePolicy::Preferred); - btn->setSizePolicy(policy); - btn->setIconSize(QSize(48, 48)); - btn->setCheckable(true); - btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); - btn->setProperty("ss", "CtrlTab"); - hBox->addWidget(btn); - mBtnGrp->addButton(btn, i); - } - mBtnGrp->button(Setting_Bright)->setIcon(QIcon(":/res/bnBrightnessAdjustMent_s.png")); - mBtnGrp->button(Setting_PowerControl)->setIcon(QIcon(":/res/bnPowerControl_s.png")); - mBtnGrp->button(Setting_NetCfg)->setIcon(QIcon(":/res/bnNetConfig_s.png")); - mBtnGrp->button(Setting_VerifyClock)->setIcon(QIcon(":/res/bnVerifyClock_s.png")); - mBtnGrp->button(Setting_Encrypt)->setIcon(QIcon(":/res/encrypt.png")); - mBtnGrp->button(Setting_HDMI)->setIcon(QIcon(":/res/Hdmi.png")); - mBtnGrp->button(Setting_Volume)->setIcon(QIcon(":/res/volume.png")); - mBtnGrp->button(Setting_Advanced)->setIcon(QIcon(":/res/AdvParam.png")); - mBtnGrp->button(Setting_Test)->setIcon(QIcon(":/res/test.png")); - - connect(mBtnGrp, &QButtonGroup::idToggled, this, [this](int index, bool checked) { - if(!checked || index==curIndex) return; - curIndex = index; - if(wgts[index]==0) { - if(index==Setting_Bright) wgts[index] = new CtrlBrightPanel(this); - else if(index==Setting_PowerControl) wgts[index] = new ControlPowerWidget(this,m_pLedlist); - else if(index==Setting_NetCfg) wgts[index] = new ControlNetConfigWidget(this,m_pLedlist); - else if(index==Setting_VerifyClock) wgts[index] = new CtrlVerifyClockPanel(this); - else if(index==Setting_Encrypt) wgts[index] = new ControlEncryptWidget(this,m_pLedlist); - else if(index==Setting_HDMI) wgts[index] = new ControlHdmiWidget(this,m_pLedlist); - else if(index==Setting_Volume) wgts[index] = new ControlVolumeWidget(this,m_pLedlist); - else if(index==Setting_Advanced) wgts[index] = new CtrlAdvancedPanel(this,m_pLedlist); - else if(index==Setting_Test) wgts[index] = new ControlTestWidget(this,m_pLedlist); - } - scrollArea->takeWidget(); - scrollArea->setWidget(wgts[index]); - emit sigSwitchIndexChanged(curIndex); - }); - vBox->addLayout(hBox); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - hBox = new QHBoxLayout(); - - scrollArea = new QScrollArea(); - scrollArea->setWidgetResizable(true); - hBox->addWidget(scrollArea); - - auto vBox2 = new QVBoxLayout(); - - fdInfo = new QTextEdit(); - gFdResInfo = fdInfo; - fdInfo->setReadOnly(true); - fdInfo->setMaximumWidth(360); - vBox2->addWidget(fdInfo); - - btnClear = new QPushButton(tr("Clear")); - btnClear->setMinimumHeight(30); - btnClear->setProperty("ssType", "progManageTool"); - connect(btnClear, &QPushButton::clicked, fdInfo, &QTextEdit::clear); - vBox2->addWidget(btnClear); - - hBox->addLayout(vBox2); - - vBox->addLayout(hBox); - - connect(mDevWgt, &DevicePanel::sigSelectedDeviceList, this, [this](QList *list) { - m_pLedlist = list; - if(m_pLedlist==nullptr) return; - if(m_pLedlist->count()<=1) { - if(m_pLedlist->count()==1) { - m_pLedCard=list->at(0); - mDevWgt->fdCardNumInfo->setText(tr("single screen operation")+"->"+tr("Current Screen")+":"+m_pLedCard->m_strCardId); - } else mDevWgt->fdCardNumInfo->setText(tr("Current Screen")+": "+tr("none")); - fdInfo->hide(); - btnClear->hide(); - } else { - QString strSelectNum = QString::number(m_pLedlist->count()); - mDevWgt->fdCardNumInfo->setText(tr("Multi screen operation")+"->"+tr("selected num")+":"+strSelectNum); - fdInfo->clear(); - fdInfo->show(); - btnClear->show(); - } - }); - - transUi(); - - mBtnGrp->button(0)->setChecked(true); -} - -void DeviceCtrlPanel::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void DeviceCtrlPanel::transUi() { - mBtnGrp->button(Setting_Bright)->setText(tr("Brightness Adjustment")); - mBtnGrp->button(Setting_PowerControl)->setText(tr("Power Control")); - mBtnGrp->button(Setting_NetCfg)->setText(tr("Net Config")); - mBtnGrp->button(Setting_VerifyClock)->setText(tr("Time Synchronization")); - mBtnGrp->button(Setting_HDMI)->setText(tr("Video source")); - mBtnGrp->button(Setting_Encrypt)->setText(tr("Encrypt")); - mBtnGrp->button(Setting_Advanced)->setText(tr("Advanced parameters")); - mBtnGrp->button(Setting_Volume)->setText(tr("Volume Adjustment")); - mBtnGrp->button(Setting_Test)->setText(tr("Test")); - - if(m_pLedCard!=nullptr) mDevWgt->fdCardNumInfo->setText(tr("single screen operation")+" -> "+tr("Current Screen:")+m_pLedCard->m_strCardId); - else mDevWgt->fdCardNumInfo->setText(tr("Current Screen")+": "+tr("none")); - btnClear->setText(tr("Clear")); -} - -void DeviceCtrlPanel::OnOutputInfo(QString strInfo) { - if(isVisible() && fdInfo->isVisible()) fdInfo->append(strInfo); -} +#include "devicectrlpanel.h" +#include "devicepanel.h" +#include "tools.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QTextEdit *gFdResInfo; + +DeviceCtrlPanel::DeviceCtrlPanel(DevicePanel *parent) : QWidget(parent), mDevWgt(parent) { + auto vBox = new QVBoxLayout(this); + vBox->setContentsMargins(0,0,0,0); + vBox->setSpacing(0); + + auto hBox = new QHBoxLayout; + hBox->setSpacing(2); + + mBtnGrp = new QButtonGroup(this); + for(int i=0; isizePolicy(); + policy.setHorizontalPolicy(QSizePolicy::Preferred); + btn->setSizePolicy(policy); + btn->setIconSize(QSize(48, 48)); + btn->setCheckable(true); + btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); + btn->setProperty("ss", "CtrlTab"); + hBox->addWidget(btn); + mBtnGrp->addButton(btn, i); + } + mBtnGrp->button(Setting_Bright)->setIcon(QIcon(":/res/bnBrightnessAdjustMent_s.png")); + mBtnGrp->button(Setting_PowerControl)->setIcon(QIcon(":/res/bnPowerControl_s.png")); + mBtnGrp->button(Setting_NetCfg)->setIcon(QIcon(":/res/bnNetConfig_s.png")); + mBtnGrp->button(Setting_VerifyClock)->setIcon(QIcon(":/res/bnVerifyClock_s.png")); + mBtnGrp->button(Setting_Encrypt)->setIcon(QIcon(":/res/encrypt.png")); + mBtnGrp->button(Setting_HDMI)->setIcon(QIcon(":/res/Hdmi.png")); + mBtnGrp->button(Setting_Volume)->setIcon(QIcon(":/res/volume.png")); + mBtnGrp->button(Setting_Advanced)->setIcon(QIcon(":/res/AdvParam.png")); + mBtnGrp->button(Setting_Test)->setIcon(QIcon(":/res/test.png")); + + connect(mBtnGrp, &QButtonGroup::idToggled, this, [this](int index, bool checked) { + if(!checked || index==curIndex) return; + curIndex = index; + if(wgts[index]==0) { + if(index==Setting_Bright) wgts[index] = new CtrlBrightPanel(this); + else if(index==Setting_PowerControl) wgts[index] = new ControlPowerWidget(this, gSelCards); + else if(index==Setting_NetCfg) wgts[index] = new CtrlNetworkPanel(this); + else if(index==Setting_VerifyClock) wgts[index] = new CtrlVerifyClockPanel(this); + else if(index==Setting_Encrypt) wgts[index] = new CtrlPwdPanel(this); + else if(index==Setting_HDMI) wgts[index] = new CtrlHdmiPanel(this); + else if(index==Setting_Volume) wgts[index] = new ControlVolumeWidget(this, gSelCards); + else if(index==Setting_Advanced) wgts[index] = new CtrlAdvancedPanel(this); + else if(index==Setting_Test) wgts[index] = new ControlTestWidget(this, gSelCards); + } + scrollArea->takeWidget(); + scrollArea->setWidget(wgts[index]); + emit sigSwitchIndexChanged(curIndex); + }); + vBox->addLayout(hBox); + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + hBox = new QHBoxLayout(); + + scrollArea = new QScrollArea(); + scrollArea->setWidgetResizable(true); + hBox->addWidget(scrollArea); + + auto vBox2 = new QVBoxLayout(); + + fdInfo = new QTextEdit(); + gFdResInfo = fdInfo; + fdInfo->setReadOnly(true); + fdInfo->setMaximumWidth(360); + vBox2->addWidget(fdInfo); + + btnClear = new QPushButton(tr("Clear")); + btnClear->setMinimumHeight(30); + btnClear->setProperty("ssType", "progManageTool"); + connect(btnClear, &QPushButton::clicked, fdInfo, &QTextEdit::clear); + vBox2->addWidget(btnClear); + + hBox->addLayout(vBox2); + + vBox->addLayout(hBox); + + connect(mDevWgt, &DevicePanel::sigSelectedDeviceList, this, [this]() { + if(gSelCards->count() < 2) { + if(gSelCards->count()==1) mDevWgt->fdCardNumInfo->setText(tr("Current Screen")+": "+gSelCards->at(0)->m_strCardId); + else mDevWgt->fdCardNumInfo->setText(tr("Current Screen")+": "+tr("none")); + fdInfo->hide(); + btnClear->hide(); + } else { + mDevWgt->fdCardNumInfo->setText(tr("Multi screen operation")+". "+tr("selected num")+": "+QString::number(gSelCards->count())); + fdInfo->clear(); + fdInfo->show(); + btnClear->show(); + } + }); + + transUi(); + + mBtnGrp->button(0)->setChecked(true); +} + +void DeviceCtrlPanel::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void DeviceCtrlPanel::transUi() { + mBtnGrp->button(Setting_Bright)->setText(tr("Brightness Adjustment")); + mBtnGrp->button(Setting_PowerControl)->setText(tr("Power Control")); + mBtnGrp->button(Setting_NetCfg)->setText(tr("Net Config")); + mBtnGrp->button(Setting_VerifyClock)->setText(tr("Time Sync")); + mBtnGrp->button(Setting_HDMI)->setText(tr("Video source")); + mBtnGrp->button(Setting_Encrypt)->setText(tr("Password")); + mBtnGrp->button(Setting_Advanced)->setText(tr("Advanced")); + mBtnGrp->button(Setting_Volume)->setText(tr("Volume Adj.")); + mBtnGrp->button(Setting_Test)->setText(tr("Test")); + + if(gSelCards->count() < 1) mDevWgt->fdCardNumInfo->setText(tr("Current Screen")+": "+tr("none")); + else if(gSelCards->count()==1) mDevWgt->fdCardNumInfo->setText(tr("Current Screen")+": "+gSelCards->at(0)->m_strCardId); + else mDevWgt->fdCardNumInfo->setText(tr("Multi screen operation")+". "+tr("selected num")+": "+QString::number(gSelCards->count())); + btnClear->setText(tr("Clear")); +} + +void DeviceCtrlPanel::OnOutputInfo(QString strInfo) { + if(isVisible() && fdInfo->isVisible()) fdInfo->append(strInfo); +} diff --git a/LedOK/devicectrlpanel.h b/LedOK/devicectrlpanel.h index a283fbb..60b7a57 100644 --- a/LedOK/devicectrlpanel.h +++ b/LedOK/devicectrlpanel.h @@ -2,7 +2,7 @@ #define DEVICECTRLPANEL_H #include "globaldefine.h" -#include "wDevicesManager/ledcard.h" +#include "device/ledcard.h" #include #include #include @@ -32,8 +32,6 @@ private: QPushButton *btnClear; QWidget *wgts[Setting_End]{}; int curIndex{-1}; - QList *m_pLedlist{0}; - LedCard *m_pLedCard{0}; }; diff --git a/LedOK/deviceitem.cpp b/LedOK/deviceitem.cpp index fef651a..57bcc95 100644 --- a/LedOK/deviceitem.cpp +++ b/LedOK/deviceitem.cpp @@ -11,7 +11,6 @@ #include #include #include -#include "base/updaterdialog.h" #include #include "base/pixbmpshowdialog.h" #include @@ -21,7 +20,7 @@ DeviceItem::DeviceItem(LedCard *pLedCard, LoQTreeWidget *parent,QWidget *pWnd) : QObject(parent), QTreeWidgetItem(UserType), m_parent(parent){ m_pWnd=pWnd; - m_pLedCard=pLedCard; + mCard=pLedCard; pHpptClient = new HpptClient(this); setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); setCheckState(0, Qt::Unchecked); @@ -33,24 +32,24 @@ DeviceItem::DeviceItem(LedCard *pLedCard, LoQTreeWidget *parent,QWidget *pWnd) : m_bnCardDetailInfo->setStyleSheet(R"rrr( QPushButton { border-radius: 4px; - image: url(:/res/DeviceManager/bnDetail.png); + image: url(:/res/device/bnDetail.png); } -QPushButton:hover{background-color: #cccccc;} +QPushButton:hover{background-color: #ccc;} )rrr"); connect(m_bnCardDetailInfo, &QPushButton::clicked, this, [this]{ QString strTip=""; - strTip.append(tr("cur brightness:")).append(QString::number(m_pLedCard->brightness)).append("\r\n"); + strTip.append(tr("cur brightness:")).append(QString::number(mCard->bright)).append("\r\n"); //strTip.append("cardsystem apk version:"+QString::number(m_LedCard.iCardSystemVersion)+"\r\n"); //strTip.append("device apk:"+m_LedCard.starterversionName+"\r\n"); - strTip.append(tr("android version:")).append(m_pLedCard->androidVersion).append("\r\n"); + strTip.append(tr("android version:")).append(mCard->androidVersion).append("\r\n"); //strTip.append(tr("android width:")+QString::number(m_LedCard.androidWidth)+"\r\n"); //strTip.append(tr("android height:")+QString::number(m_LedCard.androidHeight)+"\r\n"); - strTip.append(tr("IMEI:")).append(m_pLedCard->strIMEI).append("\r\n"); - strTip.append(tr("HardWard Version:")).append(m_pLedCard->HardVersion).append("\r\n"); - strTip.append(tr("MAX Brightness level:")).append(QString::number(m_pLedCard->BrightnessLevel)).append("\r\n"); - strTip.append(tr("Android OS Resolution:")).append(m_pLedCard->ScreenResolution).append("\r\n"); - strTip.append(tr("Firmware Version:")).append(m_pLedCard->FirmwareVersion).append("\r\n"); - strTip.append(tr("Player Version:")).append(m_pLedCard->strXixunplayerVersion).append("\r\n"); + strTip.append(tr("IMEI:")).append(mCard->strIMEI).append("\r\n"); + strTip.append(tr("HardWard Version:")).append(mCard->HardVersion).append("\r\n"); + strTip.append(tr("MAX Brightness level:")).append(QString::number(mCard->BrightnessLevel)).append("\r\n"); + strTip.append(tr("Android OS Resolution:")).append(mCard->ScreenResolution).append("\r\n"); + strTip.append(tr("Firmware Version:")).append(mCard->FirmwareVersion).append("\r\n"); + strTip.append(tr("Player Version:")).append(mCard->strXixunplayerVersion).append("\r\n"); QMessageBox::information(gMainWin, tr("Detail Info"), strTip); }); @@ -60,24 +59,24 @@ QPushButton:hover{background-color: #cccccc;} m_bnReadbackPic->setStyleSheet(R"rrr( QPushButton { border-radius: 4px; - image: url(:/res/DeviceManager/deviceReadbackPic.png); + image: url(:/res/device/deviceReadbackPic.png); } -QPushButton:hover{background-color: #cccccc;} +QPushButton:hover{background-color: #ccc;} )rrr"); connect(m_bnReadbackPic, SIGNAL(clicked()), this, SLOT(onReadbackPic())); m_ImageOnline = new QLabel(); - m_pLedCard->m_bOnLine=true; - m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Online.png")); - setData(DeviceTable_ID, 0, m_pLedCard->m_strCardId); - setData(DeviceTable_IP, 0, m_pLedCard->m_strCardIp); - setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(m_pLedCard->m_iWidth).arg(m_pLedCard->m_iHeight)); + mCard->m_bOnLine=true; + m_ImageOnline->setPixmap(QPixmap(":/res/device/O_Online.png")); + setData(DeviceTable_ID, 0, mCard->m_strCardId); + setData(DeviceTable_IP, 0, mCard->m_strCardIp); + setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(mCard->m_iWidth).arg(mCard->m_iHeight)); m_parent->setItemWidget(this, DeviceTable_Info, m_bnCardDetailInfo); m_parent->setItemWidget(this, DeviceTable_Screenshot, m_bnReadbackPic); m_parent->setItemWidget(this, DeviceTable_Online, m_ImageOnline); m_ImageOnline->setAlignment(Qt::AlignCenter); - SetPasswordItem(m_pLedCard); + SetPasswordItem(mCard); for(int i=1; i10) { //下线 - m_pLedCard->m_bOnLine=false; - m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Offline.png")); + mCard->m_bOnLine=false; + m_ImageOnline->setPixmap(QPixmap(":/res/device/O_Offline.png")); } else { //在线 - m_pLedCard->m_bOnLine=true; - m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Online.png")); + mCard->m_bOnLine=true; + m_ImageOnline->setPixmap(QPixmap(":/res/device/O_Online.png")); } }); mHeartbeatTimer.start(60000); @@ -157,7 +156,7 @@ void DeviceItem::OnControlTcpSend(int iProgramIndex) { QTcpSocket *send = new QTcpSocket(); connect(send, SIGNAL(connected()), this, SLOT(connect_sucessful())); connect(send, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(show_error(QAbstractSocket::SocketError))); - send->connectToHost(QHostAddress(m_pLedCard->m_strCardIp),31299); + send->connectToHost(QHostAddress(mCard->m_strCardIp),31299); ST_ANSY_PROGRAM_PACKET tempStreadPakcet; tempStreadPakcet.SyncHead[0]=0x7e; @@ -175,8 +174,8 @@ void DeviceItem::OnControlTcpSend(int iProgramIndex) { QByteArray databuf = QByteArray(reinterpret_cast(&tempStreadPakcet), iLenPacket); if(!send->waitForConnected(10000)) //等待连接返回 { - qDebug()<m_strCardIp<<"Connect timeout "; - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("Connect")+":"+tr("timeout")); + qDebug()<m_strCardIp<<"Connect timeout "; + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("Connect")+":"+tr("timeout")); send->close(); delete send; return ; @@ -186,7 +185,7 @@ void DeviceItem::OnControlTcpSend(int iProgramIndex) { { send->read(send->bytesAvailable()); qDebug()<<"recv anycast success ack"; - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("Anycast")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("Anycast")+":"+tr("success")); } send->close(); delete send; @@ -197,23 +196,12 @@ void DeviceItem::HttpPostByTypeJsonObject(QJsonObject json) QJsonDocument doc; doc.setObject(json); QByteArray post_loginArray = doc.toJson(QJsonDocument::Compact); - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings"; - if(m_pLedCard->m_strCardId.left(2)!="M8"&&m_pLedCard->m_strCardId.left(2)!="m8") + m_strUrl="http://"+mCard->m_strCardIp+":2016/settings"; + if(mCard->m_strCardId.left(2)!="M8" && mCard->m_strCardId.left(2)!="m8") { - if(json["_type"]=="GetAllScreenSizeM80"||json["_type"]=="SetSpecialResolution"||json["_type"]=="GetSpecialResolution"||json["_type"]=="CleanDisplayScreenSize") - { - // pHpptClient->httpPost(m_strUrl,post_loginArray); - - } - else { - pHpptClient->httpPost(m_strUrl,post_loginArray); - } - } - else - { - - pHpptClient->httpPost(m_strUrl,post_loginArray); + if(json["_type"]!="GetAllScreenSizeM80") pHpptClient->httpPost(m_strUrl,post_loginArray); } + else pHpptClient->httpPost(m_strUrl,post_loginArray); } void DeviceItem::HttpGetLedCardWidthHeight() { @@ -230,7 +218,7 @@ void DeviceItem::HttpGetLedCardRemarkName(){ } void DeviceItem::refreshLable(){ - if(m_pLedCard->m_bPowerStatus){ + if(mCard->m_bPowerStatus){ this->setForeground(DeviceTable_Power, Qt::green); setData(DeviceTable_Power, 0, tr("on")); } else { @@ -267,10 +255,10 @@ void DeviceItem::onReadbackPic() { } void DeviceItem::SetPasswordItem(LedCard *p){ if(p->bPassword) {//加过密 - if(p->m_bLockStatus) m_bnLock->setIcon(QIcon(":/res/DeviceManager/Lock.png")); //如果已经验证通过密码显示绿色图标 - else m_bnLock->setIcon(QIcon(":/res/DeviceManager/UnLock.png")); //如果没有验证显示蓝色锁图标 + if(p->m_bLockStatus) m_bnLock->setIcon(QIcon(":/res/device/Lock.png")); //如果已经验证通过密码显示绿色图标 + else m_bnLock->setIcon(QIcon(":/res/device/UnLock.png")); //如果没有验证显示蓝色锁图标 m_parent->setItemWidget(this, DeviceTable_Password, m_bnLock); - } else m_bnLock->setIcon(QIcon(":/res/DeviceManager/Transparent.png")); //显示空白 + } else m_bnLock->setIcon(QIcon()); //显示空白 } //获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 void DeviceItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data) { @@ -295,38 +283,35 @@ void DeviceItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data QString strType=jsonObject["_type"].toString(); if(jsonObject["success"].toBool()==true) { - //alahover 20200521 qDebug()<m_strCardId +"---------"+ strType; if(strType=="GetScreenSize" ) { - if(m_pLedCard->m_iWidth!=jsonObject["width"].toInt()||m_pLedCard->m_iHeight!=jsonObject["height"].toInt()) + if(mCard->m_iWidth!=jsonObject["width"].toInt()||mCard->m_iHeight!=jsonObject["height"].toInt()) { - m_pLedCard->m_iWidth=jsonObject["width"].toInt(); - m_pLedCard->m_iHeight=jsonObject["height"].toInt(); + mCard->m_iWidth=jsonObject["width"].toInt(); + mCard->m_iHeight=jsonObject["height"].toInt(); } - setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(m_pLedCard->m_iWidth).arg(m_pLedCard->m_iHeight)); + setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(mCard->m_iWidth).arg(mCard->m_iHeight)); } else if(strType=="GetCardAlias" ) { - m_pLedCard->m_strCardRemarkName = QString::fromUtf8(QByteArray::fromBase64(jsonObject["alias"].toString().toLatin1())); - setData(DeviceTable_Remark,0,m_pLedCard->m_strCardRemarkName); + mCard->m_strCardRemarkName = QString::fromUtf8(QByteArray::fromBase64(jsonObject["alias"].toString().toLatin1())); + setData(DeviceTable_Remark,0,mCard->m_strCardRemarkName); } else if(strType=="GetCardName") { m_HeartbeatCount=0; - m_pLedCard->m_bOnLine=true; - m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Online.png")); + mCard->m_bOnLine=true; + m_ImageOnline->setPixmap(QPixmap(":/res/device/O_Online.png")); } else if(strType=="GetBuildInformation" ) { - m_pLedCard->strIMEI=jsonObject["IMEI"].toString(); - m_pLedCard->HardVersion=jsonObject["HardVersion"].toString(); - m_pLedCard->BrightnessLevel=jsonObject["BrightnessLevel"].toInt(); - m_pLedCard->ScreenResolution=jsonObject["ScreenResolution"].toString(); - m_pLedCard->FirmwareVersion=jsonObject["FirmwareVersion"].toString(); - //if(m_pLedCard->CompareHTTPPostParam()==false) - + mCard->strIMEI=jsonObject["IMEI"].toString(); + mCard->HardVersion=jsonObject["HardVersion"].toString(); + mCard->BrightnessLevel=jsonObject["BrightnessLevel"].toInt(); + mCard->ScreenResolution=jsonObject["ScreenResolution"].toString(); + mCard->FirmwareVersion=jsonObject["FirmwareVersion"].toString(); } else if(strType=="CheckSoftVersions" ) { @@ -335,42 +320,36 @@ void DeviceItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data QJsonObject oApp = value.toObject(); if(oApp["packageName"].toString().contains("xixunplayer")) { - m_pLedCard->strXixunplayerVersion=oApp["versionName"].toString(); - m_pLedCard->strXixunplayerVersionCode=oApp["versionCode"].toInt(); + mCard->strXixunplayerVersion=oApp["versionName"].toString(); + mCard->strXixunplayerVersionCode=oApp["versionCode"].toInt(); } } } else if(strType == "HasControllerPassword") { - //if(m_pLedCard->bPassword!=jsonObject["result"].toBool()) { - m_pLedCard->bPassword=jsonObject["result"].toBool(); - SetPasswordItem(m_pLedCard); + mCard->bPassword=jsonObject["result"].toBool(); + SetPasswordItem(mCard); } } - else if(strType == "SetScreenOn") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetScreenOn")+":"+tr("success")); - } else if(strType == "AliIotSetting") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("AliIotSetting")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("AliIotSetting")+":"+tr("success")); } else if(strType == "IsScreenOn") { - //if(m_pLedCard->m_bPowerStatus!=jsonObject["on"].toBool()) { - m_pLedCard->m_bPowerStatus=jsonObject["on"].toBool(); - if(m_pLedCard->m_bPowerStatus) { + mCard->m_bPowerStatus=jsonObject["on"].toBool(); + if(mCard->m_bPowerStatus) { this->setForeground(DeviceTable_Power, Qt::green); setData(DeviceTable_Power, 0, tr("on")); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetScreenStatus")+tr("success")+","+tr("Status")+":"+tr("on")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetScreenStatus")+tr("success")+","+tr("Status")+":"+tr("on")); } else { this->setForeground(DeviceTable_Power, Qt::red); setData(DeviceTable_Power, 0, tr("off")); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetScreenStatus")+tr("success")+","+tr("Status")+":"+tr("off")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetScreenStatus")+tr("success")+","+tr("Status")+":"+tr("off")); } } } @@ -380,140 +359,56 @@ void DeviceItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data if(bStatus)//解密成功 { qDebug()<<"解密成功"; - m_pLedCard->m_bLockStatus=false; + mCard->m_bLockStatus=false; } else { qDebug()<<"解密失败"; X_UIMsgBoxOk *mb = new X_UIMsgBoxOk(tr("Tip Info"),tr("password is wrong"), m_pWnd,0); mb->exec(); - m_pLedCard->m_bLockStatus=true; + mCard->m_bLockStatus=true; } - SetPasswordItem(m_pLedCard); + SetPasswordItem(mCard); } else if(strType == "GetBrightness") { - m_pLedCard->brightness = jsonObject["brightness"].toInt(); - QString bright = QString::number(m_pLedCard->brightness); - setData(DeviceTable_Brightness, 0, QString::number(m_pLedCard->brightness*100/m_pLedCard->BrightnessLevel)+"% ("+bright+")"); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetBrightness")+tr("success")+","+tr("brightness")+"="+bright); - } - else if(strType == "SetBrightness") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetBrightness")+":"+tr("success")); - } - else if(strType == "SetBrightnessSensitivity") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetBrightnessSensitivity")+tr("success")); - } - else if(strType == "SetMinBrightness") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetMinBrightness")+":"+tr("success")); - } - else if(strType == "GetBrightnessSensitivity") - { - int iTemp=jsonObject["sensitivity"].toInt(); - QString strSensitivity=QString::number(iTemp); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetBrightnessSensitivity")+tr("success")+","+tr("sensitivity")+"="+strSensitivity); - } - else if(strType == "GetMinBrightness") - { - int iTemp=jsonObject["brightness"].toInt(); - QString strMinBrightness=QString::number(iTemp); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetMinBrightness")+tr("success")+","+tr("brightness")+"="+strMinBrightness); - } - else if(strType == "SensorBrightnessTable") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetSensorBrightnessTable")+":"+tr("success")); - } - else if(strType == "SetSwitchWiFi") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetSwitchWiFi")+":"+tr("success")); - } - else if(strType == "ConfigurationWiFi") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("ConfigurationWiFi")+":"+tr("success")); - } - else if(strType == "ConfigurationHotSpot") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("ConfigurationHotSpot")+":"+tr("success")); - } - else if(strType == "GetSwitchWiFi") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetSwitchWiFi")+":"+tr("success")); + mCard->bright = jsonObject["brightnessPercentage"].toInt(-1); + if(mCard->bright==-1) mCard->bright = qRound(jsonObject["brightness"].toInt() * 100.0 / mCard->BrightnessLevel); + QString bright = QString::number(mCard->bright); + setData(DeviceTable_Brightness, 0, QString::number(mCard->bright)+"%"); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetBrightness")+tr("success")+","+tr("brightness")+"="+bright+"%"); } else if(strType == "SetAutoBrightnessTask") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetAutoBrightnessTask")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetAutoBrightnessTask")+":"+tr("success")); } else if(strType == "SetAutoVolumeTask") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetAutoVolumeTask")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetAutoVolumeTask")+":"+tr("success")); } else if(strType == "SetVolume") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetVolume")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetVolume")+":"+tr("success")); } else if(strType == "GetVolume") { int itempVolume=jsonObject["volume"].toInt(); QString strCurVolume=QString::number(itempVolume); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetVolume")+":"+tr("success")+","+tr("volume")+"="+strCurVolume); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetVolume")+":"+tr("success")+","+tr("volume")+"="+strCurVolume); } else if(strType == "SetTimingScreenTask") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetTimingScreenTask")+":"+tr("success")); - } - else if(strType == "SetHighForBusy") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetHighForBusy")+":"+tr("success")); - } - else if(strType == "GetStateForBusy") - { - if(jsonObject["result"].toInt()==0) - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetStateForBusy")+":"+tr("Service:Low Out of service:High")); - else - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetStateForBusy")+":"+tr("Service:High Out of service:Low")); - } - else if(strType =="UpgradeSoftware") - { - qDebug()<<"slotUploadFinished success ack"; - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - else if(strType == "IsPortableHotSpot") - { - QString strWifi=jsonObject["wifi"].toString(); - if(!strWifi.isEmpty()) - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("IsPortableHotSpot")+":"+tr("success")+","+tr("WifiName")+":"+strWifi); - QString strAp=jsonObject["hotSpots"].toString(); - if(!strAp.isEmpty()) - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("IsPortableHotSpot")+":"+tr("success")+","+tr("ApName")+":"+strAp); - if(strWifi.isEmpty()&&strAp.isEmpty()) - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("IsPortableHotSpot")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetTimingScreenTask")+":"+tr("success")); } else if(strType == "TestScreen") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("TestScreen")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("TestScreen")+":"+tr("success")); } else if(strType == "SetOnlineAddr") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetOnlineAddr")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetOnlineAddr")+":"+tr("success")); } else if(strType == "SetRealtimeServer") { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetRealtimeServer")+":"+tr("success")); - } - else if(strType == "GetOnlineAddr") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetOnlineAddr")+":"+jsonObject["server"].toString()+" ID:"+jsonObject["companuID"].toString()); - } - else if(strType == "GetRealtimeServer") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetRealtimeServer")+":"+jsonObject["server"].toString()); - } - else if(strType == "DelPrograms") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("DelPrograms")+":"+tr("success")); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetRealtimeServer")+":"+tr("success")); } else if(strType == "GetCurrentSensorBrightness") { @@ -529,33 +424,7 @@ void DeviceItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data int iTempValue=jsonObject["value"].toInt(); QString strSensorValue=QString::number(iTempValue); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetCurrentSensorBrightness")+":"+strSensorType+","+tr("Cur brightness")+":"+strSensorValue); - } - else if(strType == "SetSpecialResolution") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetSpecialResolution")+":"+tr("success")); - } - else if(strType == "GetSpecialResolution") - { - QString strTotalResolution = jsonObject["totalResolution"].toString(); - QString strCurDisplayResolution = jsonObject["displayResolution"].toString(); - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetSpecialResolution")+":"+tr("totalResolution")+"["+strTotalResolution+"],"+tr("strCurDisplayResolution")+"["+strCurDisplayResolution+"]"); - } - else if(strType == "CleanDisplayScreenSize") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("CleanDisplayScreenSize")+":"+tr("success")); - } - else if(strType == "SetMinBrightness") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetMinBrightness")+":"+tr("success")); - } - else if(strType == "SetMaxBrightness") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetMaxBrightness")+":"+tr("success")); - } - else if(strType == "GetMaxBrightness") - { - emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetMaxBrightness")+":"+QString::number(jsonObject["brightness"].toInt())); + emit sigOutputInfo(mCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetCurrentSensorBrightness")+":"+strSensorType+","+tr("Cur brightness")+":"+strSensorValue); } else if(strType == "GetScreenshotFull") { MACRO_ASKTIME_STOP MACRO_POSTING_DLG_UNLOCK @@ -570,18 +439,10 @@ void DeviceItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data //imageresult.loadFromData(Ret_bytearray); PixbmpShowDialog *dlg=new PixbmpShowDialog(m_pWnd); dlg->m_PixMap.loadFromData(Ret_bytearray); - dlg->ResizeByPixmap(m_pLedCard->m_iWidth,m_pLedCard->m_iHeight); + dlg->ResizeByPixmap(mCard->m_iWidth,mCard->m_iHeight); dlg->exec(); } - } else {//失败应答,打印失败和错误信息 - if(strType == "UpgradeSoftware") { - qDebug()<<"slotUploadFinished failed ack"; - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - emit sigOutputInfo(m_pLedCard->m_strCardId+"<-"+strType+":failed,error:"+jsonObject["error"].toString()); } - } } QPixmap DeviceItem::Base64_To_Image(QByteArray bytearray,QString SavePath) @@ -600,17 +461,6 @@ QPixmap DeviceItem::Base64_To_Image(QByteArray bytearray,QString SavePath) return imageresult; } -void DeviceItem::slotUploadProgress(qint64 A,qint64 B) -{ - if(B!=0) - { - QString strbaifenbi=tr("Uploadding")+":"+QString("%1%").arg(A*100/B); - emit sigSetTipTextContent(strbaifenbi); - m_pGetAskTimer->stop(); - m_pGetAskTimer->start(50000); - } -} - void DeviceItem::DeletePostingDlg() { if(m_PostingDlg!=nullptr) diff --git a/LedOK/deviceitem.h b/LedOK/deviceitem.h index 714aa01..9a66b43 100644 --- a/LedOK/deviceitem.h +++ b/LedOK/deviceitem.h @@ -7,7 +7,7 @@ #include #include #include -#include +#include #include #include #include @@ -44,11 +44,10 @@ public: void HttpGetLedCardRemarkName(); QPixmap Base64_To_Image(QByteArray bytearray,QString SavePath); - LedCard *m_pLedCard{0}; + LedCard *mCard{0}; QTimer mHeartbeatTimer; signals: void sigOutputInfo(QString); - void sigSetTipTextContent(QString); public slots: void DeletePostingDlg(); @@ -57,7 +56,6 @@ public slots: protected slots: void onReadbackPic(); void onVerifyLockPassword(); - void slotUploadProgress(qint64 A,qint64 B); private: int m_intIndexFlagOfInfoOrControl=0; void SetPasswordItem(LedCard *p); diff --git a/LedOK/devicepanel.cpp b/LedOK/devicepanel.cpp index 800bd77..b52934c 100644 --- a/LedOK/devicepanel.cpp +++ b/LedOK/devicepanel.cpp @@ -1,7 +1,7 @@ #include "devicepanel.h" #include "devicectrlpanel.h" #include "tools.h" -#include "gqt.h" +#include "gutil/qgui.h" #include #include #include @@ -31,7 +31,7 @@ DevicePanel::DevicePanel(QSettings &settings, QWidget *parent) : QWidget(parent) hBox->setSpacing(2); auto label = new QLabel(); - label->setPixmap({":/res/DeviceManager/DeviceNum_All.png"}); + label->setPixmap({":/res/device/DeviceNum_All.png"}); label->setScaledContents(true); label->setFixedSize(33, 24); hBox->addWidget(label); @@ -46,9 +46,16 @@ DevicePanel::DevicePanel(QSettings &settings, QWidget *parent) : QWidget(parent) auto fdSearch = new QLineEdit(); fdSearch->setClearButtonEnabled(true); fdSearch->setFixedSize(220, 30); - fdSearch->addAction(new QAction(QIcon(":/res/ProgramManager/bnSearch.png"), QString()), QLineEdit::LeadingPosition); + fdSearch->addAction(new QAction(QIcon(":/res/program/bnSearch.png"), QString()), QLineEdit::LeadingPosition); fdSearch->setStyleSheet("border: 1px solid #aaaaaa;"); - connect(fdSearch, &QLineEdit::textChanged, this, &DevicePanel::FilterProgram); + connect(fdSearch, &QLineEdit::textChanged, this, [this](const QString &search) { + auto cnt = mDeviceTable->topLevelItemCount(); + if(search.isEmpty()) for(int i=0; itopLevelItem(i)->setHidden(false); + else for(int i=0; itopLevelItem(i); + item->setHidden(! (item->text(DeviceTable_ID).contains(search) || item->text(DeviceTable_Remark).contains(search) || item->text(DeviceTable_IP).contains(search))); + } + }); hBox->addWidget(fdSearch); hBox->addSpacing(10); @@ -80,7 +87,7 @@ QComboBox { } QComboBox:hover {background-color: #08b;} QComboBox::drop-down {width: 25px;} -QComboBox::down-arrow {image: url(:/res/DeviceManager/FlashArrow.png);} +QComboBox::down-arrow {image: url(:/res/device/FlashArrow.png);} QComboBox QAbstractItemView::item { height: 28px; color: #fff; @@ -91,7 +98,7 @@ QComboBox QAbstractItemView::item:selected {background-color: #09c;} btnRefresh = new QPushButton(tr("Refresh"), areaFlash); btnRefresh->setGeometry(0, 0, 75, areaFlash->height()); connect(btnRefresh, &QPushButton::clicked, this, [this] { - LedCardList.clear(); + mLedCards.clear(); mDeviceTable->onCheckAll(false); mDeviceTable->clear(); nDeviceNum->setText("0"); @@ -137,12 +144,12 @@ QPushButton:hover {background-color: #08b;} parseInfo(document.object(), addr); } else { auto bytes = gram.data(); - STREAM_PACKET *pStreamPacket = (STREAM_PACKET *)bytes.data(); + auto packet = (Packet *)bytes.data(); LedCard *pLedCard = new LedCard(this);//alahover 没有释放 - pLedCard->m_strCardId = pStreamPacket->ucSerialCode; + pLedCard->m_strCardId = packet->serialCode; pLedCard->m_strCardIp = addr; - for(int i=0;im_strCardId==pLedCard->m_strCardId ) {//如果已经存在在列表中 - auto pOldLedCard = LedCardList.at(i);//获取到旧的对象指针 + for(int i=0;im_strCardId==pLedCard->m_strCardId ) {//如果已经存在在列表中 + auto pOldLedCard = mLedCards.at(i);//获取到旧的对象指针 pOldLedCard->m_bOnLine = true; if(pOldLedCard->CompareHTTPGetParam(pLedCard)==false) {//如果ip地址变化了 pOldLedCard->copyLedCardHTTPGetParam(pLedCard); @@ -154,7 +161,7 @@ QPushButton:hover {background-color: #08b;} delete pLedCard; return; } - LedCardList.append(pLedCard); + mLedCards.append(pLedCard); addLedCard(pLedCard);//发送信号到界面 } } @@ -164,7 +171,7 @@ QPushButton:hover {background-color: #08b;} for(int i=1; isetTextAlignment(i, Qt::AlignCenter); mDeviceTable->setHeaderItem(m_headerItem); mDeviceTable->header()->setSectionResizeMode(DeviceTable_Check, QHeaderView::Fixed); - mDeviceTable->setColumnWidth(DeviceTable_Check, 48); + mDeviceTable->setColumnWidth(DeviceTable_Check, 36); mDeviceTable->header()->setSectionResizeMode(DeviceTable_Online, QHeaderView::Fixed); mDeviceTable->setColumnWidth(DeviceTable_Online, 48); mDeviceTable->header()->setSectionResizeMode(DeviceTable_ID, QHeaderView::Stretch); @@ -188,7 +195,6 @@ QPushButton:hover {background-color: #08b;} mDeviceTable->hideColumn(0); mDeviceTable->fdIsSelAll->hide(); - specifyIPDlg = new QDialog(this); specifyIPDlg->setWindowTitle(tr("Specify IP")); @@ -246,30 +252,28 @@ DevicePanel::~DevicePanel() { } void DevicePanel::sendGetInfo() { - QByteArray data = QJsonDocument({{"action", "getInfo"}}).toJson(QJsonDocument::Compact); -// if(mUdpSocket.writeDatagram(data, QHostAddress("255.255.255.255"), 22222) != data.length()) { -// qDebug() << "getInfo writeDatagram to 255.255.255.255 Failed"; -// } + const QByteArray data = QJsonDocument({{"action", "getInfo"}}).toJson(QJsonDocument::Compact); + uchar ccc[]{0x7E, 0x7E, 0x7E, 0x90, 0x42, 0x72, 0x6F, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x21, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1C, 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, 0x9F}; + if(mUdpSocket.writeDatagram(data, QHostAddress("255.255.255.255"), 22222) != data.length()) qDebug() << "getInfo write to 255.255.255.255 failed"; + if(mUdpSocket.writeDatagram((char *)ccc, sizeof(ccc), QHostAddress("255.255.255.255"), 31296) != sizeof(ccc)) qDebug() << "getInfo write to 255.255.255.255 failed"; QList networkinterfaces = QNetworkInterface::allInterfaces(); foreach(QNetworkInterface face, networkinterfaces) { auto flags = face.flags(); bool can = (flags & QNetworkInterface::IsRunning) && (flags & QNetworkInterface::CanBroadcast) && ! (flags & QNetworkInterface::IsLoopBack); if(! can) continue; - qDebug() << face; auto addrEntries = face.addressEntries(); foreach(QNetworkAddressEntry addrEntry, addrEntries) { auto ip = addrEntry.ip(); if(ip.protocol()!=QAbstractSocket::IPv4Protocol) continue; auto broadcast = addrEntry.broadcast(); - if(mUdpSocket.writeDatagram(data, broadcast, 22222) != data.length()) qDebug() << "getInfo writeDatagram Failed." << ip.toString() << "->" << broadcast.toString(); + if(mUdpSocket.writeDatagram(data, broadcast, 22222) != data.length()) qDebug() << "getInfo write failed." << ip.toString() << "->" << broadcast.toString(); } } auto ipstr = fdIP->toPlainText(); if(! ipstr.isEmpty()) { auto ips = ipstr.split("\n", Qt::SkipEmptyParts); - foreach(auto ip, ips) { - if(gDevicePanel->mUdpSocket.writeDatagram(data, QHostAddress(ip), 22222) != data.length()) qDebug() << "Specify IP write Failed." << ip; - } + foreach(auto ip, ips) if(mUdpSocket.writeDatagram(data, QHostAddress(ip), 22222) != data.length()) qDebug() << "getInfo specify IP write failed." << ip; } } @@ -308,82 +312,21 @@ void DevicePanel::transUi() { bnSpecifyIP->setItemText(0,tr("Specify IP")); label_3->setText(tr("All")); - m_headerItem->setData(DeviceTable_Check, 0, ""); - m_headerItem->setData(DeviceTable_Online, 0, tr("Online")); - m_headerItem->setData(DeviceTable_ID, 0, tr("Screen ID")); - m_headerItem->setData(DeviceTable_IP, 0, tr("Screen IP")); - m_headerItem->setData(DeviceTable_ScreenSize, 0, tr("Screen Size")); - m_headerItem->setData(DeviceTable_Remark, 0, tr("Remark Name")); - m_headerItem->setData(DeviceTable_Screenshot, 0, tr("readback pic")); - m_headerItem->setData(DeviceTable_Brightness, 0, tr("Cur Brightness")); - m_headerItem->setData(DeviceTable_Power, 0, tr("Power Status")); - m_headerItem->setData(DeviceTable_Password, 0, tr("Security")); - m_headerItem->setData(DeviceTable_Info, 0, tr("More Info")); + m_headerItem->setText(DeviceTable_Online, tr("Online")); + m_headerItem->setText(DeviceTable_ID, tr("Screen ID")); + m_headerItem->setText(DeviceTable_IP, tr("Screen IP")); + m_headerItem->setText(DeviceTable_ScreenSize, tr("Screen Size")); + m_headerItem->setText(DeviceTable_Remark, tr("Remark Name")); + m_headerItem->setText(DeviceTable_Screenshot, tr("readback pic")); + m_headerItem->setText(DeviceTable_Brightness, tr("Cur Brightness")); + m_headerItem->setText(DeviceTable_Power, tr("Power Status")); + m_headerItem->setText(DeviceTable_Password, tr("Security")); + m_headerItem->setText(DeviceTable_Info, tr("More Info")); auto cnt = mDeviceTable->topLevelItemCount(); for(int i=0; i(mDeviceTable->topLevelItem(i))->refreshLable(); } -void DevicePanel::FilterProgram(const QString &strtemp){ - if (strtemp.isEmpty()) //显示全部 - { - for (int i = 0; i< mDeviceTable->topLevelItemCount(); ++i){ - QTreeWidgetItem* topItem = mDeviceTable->topLevelItem(i); - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),false); - } - } - else - { - QList resultList = mDeviceTable->findItems(strtemp, Qt::MatchContains,DeviceTable_ID); //搜索结果 - if (resultList.size() > 0) - { - for (int i = 0; i< mDeviceTable->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = mDeviceTable->topLevelItem(i); - if (resultList.contains(topItem)) - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList1 = mDeviceTable->findItems(strtemp, Qt::MatchContains,DeviceTable_Remark); //搜索结果 - if (resultList1.size() > 0) - { - for (int i = 0; i< mDeviceTable->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = mDeviceTable->topLevelItem(i); - if (resultList1.contains(topItem)) - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = mDeviceTable->findItems(strtemp, Qt::MatchContains,DeviceTable_IP); //搜索结果 - if (resultList2.size() > 0) - { - for (int i = 0; i< mDeviceTable->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = mDeviceTable->topLevelItem(i); - if (resultList2.contains(topItem)) - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - for (int i = 0; i< mDeviceTable->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = mDeviceTable->topLevelItem(i); - mDeviceTable->setRowHidden(i,mDeviceTable->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - } - } - } -} - void DevicePanel::OnControlTcpSend(int iProgramIndex){ int cnt = mDeviceTable->topLevelItemCount(); for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) static_cast(mDeviceTable->topLevelItem(i))->OnControlTcpSend(iProgramIndex); @@ -394,7 +337,7 @@ void DevicePanel::OnControlSendJson(QJsonObject &json,QString strFanYi){ for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) { DeviceItem *item = static_cast(mDeviceTable->topLevelItem(i)); item->HttpPostByTypeJsonObject(json); - QString strCardId=item->m_pLedCard->m_strCardId; + QString strCardId=item->mCard->m_strCardId; mDeviceCtrlPanel->OnOutputInfo(strCardId+":"+tr("send")+"->"+strFanYi); } } @@ -405,7 +348,7 @@ int DevicePanel::GetSelectDeviceNum() { mSelCards.clear(); for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) { iSelectCount++; - mSelCards.append(static_cast(mDeviceTable->topLevelItem(i))->m_pLedCard); + mSelCards.append(static_cast(mDeviceTable->topLevelItem(i))->mCard); } return iSelectCount; } @@ -420,28 +363,35 @@ void DevicePanel::onCheckStateChanged(int f){ emit sigSelectedDeviceList(&mSelCards); } } -void DevicePanel::addLedCard(LedCard *p){ +void DevicePanel::addLedCard(LedCard *card) { int cnt = mDeviceTable->topLevelItemCount(); for(int i=0; i(mDeviceTable->topLevelItem(i)); - if(item->m_pLedCard->m_strCardId != p->m_strCardId) continue; - item->setData(DeviceTable_ID, 0, p->m_strCardId); - item->setData(DeviceTable_IP, 0, p->m_strCardIp); - item->setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(p->m_iWidth).arg(p->m_iHeight)); + if(item->mCard->m_strCardId != card->m_strCardId) continue; + item->setData(DeviceTable_ID, 0, card->m_strCardId); + item->setData(DeviceTable_IP, 0, card->m_strCardIp); + item->setData(DeviceTable_ScreenSize, 0, QString("%1 x %2").arg(card->m_iWidth).arg(card->m_iHeight)); return; } - new DeviceItem(p, mDeviceTable, this); + new DeviceItem(card, mDeviceTable, this); nDeviceNum->setText(QString::number(mDeviceTable->topLevelItemCount())); + + QJsonObject json; + json.insert("_id", "SyncTime"); + json.insert("_type", "SyncTime"); + json.insert("time", QDateTime::currentDateTime().toMSecsSinceEpoch()); + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); + connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater); } void DevicePanel::clearUdpHeartbeat(LedCard *p) { int cnt = mDeviceTable->topLevelItemCount(); for(int i=0; i(mDeviceTable->topLevelItem(i)); - if(item->m_pLedCard->m_strCardId != p->m_strCardId) continue; + if(item->mCard->m_strCardId != p->m_strCardId) continue; item->m_HeartbeatCount = 0; if(item->m_ImageOnline) { - item->m_pLedCard->m_bOnLine = true; - item->m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Online.png")); + item->mCard->m_bOnLine = true; + item->m_ImageOnline->setPixmap(QPixmap(":/res/device/O_Online.png")); } return; } @@ -465,8 +415,8 @@ void DevicePanel::parseInfo(const QJsonObject &subObj, const QString &strIp) { pLedCard->androidWidth=subObj["androidWidth"].toInt(); pLedCard->lastActive=subObj["lastActive"].toInt(); - for(int i=0;im_strCardId==pLedCard->m_strCardId ) { //如果已经存在在列表中 - auto pOldLedCard = LedCardList.at(i);//获取到旧的对象指针 + for(int i=0;im_strCardId==pLedCard->m_strCardId ) { //如果已经存在在列表中 + auto pOldLedCard = mLedCards.at(i);//获取到旧的对象指针 pOldLedCard->m_bOnLine = true; if(! pOldLedCard->CompareHTTPGetParam(pLedCard)) {//如果ip地址变化了 pOldLedCard->copyLedCardHTTPGetParam(pLedCard); @@ -478,7 +428,7 @@ void DevicePanel::parseInfo(const QJsonObject &subObj, const QString &strIp) { delete pLedCard; return; } - LedCardList.append(pLedCard); + mLedCards.append(pLedCard); addLedCard(pLedCard);//发送信号到界面 } @@ -486,7 +436,7 @@ STREAM_PACKET LedOkMakeStreamPacket(int iComType,int iLen,unsigned char *ucBuf,Q STREAM_PACKET Temp; memset(&Temp, 0, sizeof(STREAM_PACKET)); if(iLen>2048) return Temp; - memset(Temp.SyncHead,STREAM_SYNC_HEAD,STREAM_SYNC_HEAD_NUM); + memset(Temp.SyncHead, 0x7e, 3); memset(Temp.ucSerialCode,0x00,20); char* ch; QByteArray ba = str.toLatin1(); // must @@ -521,11 +471,10 @@ void DevicePanel::RestoreLedCardIpByUdpCmd() { if(strGateway.length()<=20) memcpy(stTempIp.cDns,strGateway.toLatin1().data(),strGateway.length()); STREAM_PACKET tempStreadPacket = LedOkMakeStreamPacket(COMMAND_ONLY_RESET_CARD_IP, 80, (unsigned char *)&stTempIp,"Broadcast!"); - int iLenPacket=tempStreadPacket.iLength+sizeof(int)+STREAM_SYNC_HEAD_NUM*sizeof(unsigned char)+sizeof(char)+20*sizeof(char)+sizeof(char);/////除正文外的协议结构大小; + int iLenPacket=tempStreadPacket.iLength+sizeof(int)+3*sizeof(unsigned char)+sizeof(char)+20*sizeof(char)+sizeof(char);/////除正文外的协议结构大小; QUdpSocket *tempUdpSocket = new QUdpSocket(this); if(!tempUdpSocket->bind(entry.ip())) break; tempUdpSocket->writeDatagram((char *)&tempStreadPacket,iLenPacket,broadcastAddress, 31296); - } } } diff --git a/LedOK/devicepanel.h b/LedOK/devicepanel.h index 85417ec..b7faf99 100644 --- a/LedOK/devicepanel.h +++ b/LedOK/devicepanel.h @@ -32,7 +32,7 @@ public: void clearUdpHeartbeat(LedCard *); void parseInfo(const QJsonObject &subObj,const QString &strIp); void RestoreLedCardIpByUdpCmd(); - QList LedCardList; + QList mLedCards; protected: void changeEvent(QEvent *) override; void transUi(); @@ -40,7 +40,6 @@ public slots: void ShowDevicesInfoOrControlWidget(int index); protected slots: void onCheckStateChanged(int f); - void FilterProgram(const QString &strtemp); void OnControlSendJson(QJsonObject &json,QString strFanYi); void OnControlTcpSend(int iProgramIndex); diff --git a/LedOK/ffplayer.cpp b/LedOK/ffplayer.cpp index 37b2abc..51df954 100644 --- a/LedOK/ffplayer.cpp +++ b/LedOK/ffplayer.cpp @@ -1,642 +1,648 @@ -#include "ffplayer.h" -#include -#include -#if(QT_VERSION_MAJOR > 5) - #include -#endif -#include -#include - -using namespace std; - -AVFmt::AVFmt(QByteArray url) { - fmt_ctx = avformat_alloc_context(); - int res = avformat_open_input(&fmt_ctx, url.constData(), nullptr, nullptr); - if(res < 0) { - err = "Open input fail: "+errStr(res); - return; - } - res = avformat_find_stream_info(fmt_ctx, nullptr); - if(res < 0) { - err = "Find stream info fail: "+errStr(res); - return; - } - start = fmt_ctx->start_time; - qInfo() << "Fmt Start" << start << "Dur" << fmt_ctx->duration; - for(uint ss=0; ssnb_streams; ss++) if(fmt_ctx->streams[ss]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {vi.idx = ss; break;} - for(uint ss=0; ssnb_streams; ss++) if(fmt_ctx->streams[ss]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {au.idx = ss; break;} - if(vi.idx == -1) qWarning()<<"Didn't find a Video Stream"; - else { - auto viStream = fmt_ctx->streams[vi.idx]; - auto decoder = avcodec_find_decoder(viStream->codecpar->codec_id); - if(decoder==0) { - vi.idx = -1; - qInfo()<<"Couldn't found Video Decoder"; - } else { - vi.ctx = avcodec_alloc_context3(decoder); - avcodec_parameters_to_context(vi.ctx, viStream->codecpar); - vi.ctx->thread_count = 0; - if(avcodec_open2(vi.ctx, decoder, nullptr) < 0) { - vi.idx = -1; - qInfo()<<"Couldn't open Video Codec Ctx"; - } else { - sws_ctx = sws_getContext(vi.ctx->width, vi.ctx->height, vi.ctx->pix_fmt, vi.ctx->width, vi.ctx->height, AV_PIX_FMT_RGB32, SWS_FAST_BILINEAR, 0, 0, 0); - if(vi.ctx->color_primaries==AVCOL_PRI_BT2020) { - res = sws_setColorspaceDetails(sws_ctx, sws_getCoefficients(SWS_CS_BT2020), 0, sws_getCoefficients(SWS_CS_DEFAULT), 0, -0x2200, 0x1c000, 0x18000); //0x12800, 0x40000 - qInfo()<<"sws_setColorspaceDetails"<time_base.num * 1000000; - vi.time_den = viStream->time_base.den; - vi.start = viStream->start_time * vi.time_num / vi.time_den; - qInfo()<<"Video Idx" << vi.idx << "Start" << vi.start << "Dur" << viStream->duration * vi.time_num / vi.time_den; - } - } - } - if(au.idx == -1) qInfo()<<"Couldn't find a Audio Stream"; - else { - auto auStream = fmt_ctx->streams[au.idx]; -#if(QT_VERSION_MAJOR > 5) - QAudioDevice audioDevice = QMediaDevices::defaultAudioOutput(); -#else - QAudioDeviceInfo audioDevice = QAudioDeviceInfo::defaultOutputDevice(); -#endif - if(audioDevice.isNull()) { - au.idx = -1; - qInfo()<<"Couldn't find a Audio Device"; - } else { - AVCodecParameters *codecpar = auStream->codecpar; - AVSampleFormat packed_sample_fmt = av_get_packed_sample_fmt((AVSampleFormat)codecpar->format); - qInfo()<<"audio codecpar:"; - qInfo()<<" sample_rate"<sample_rate; - qInfo()<<" frame_size"<frame_size; - qInfo()<<" sample_fmt"<format); - qInfo()<<" bits per coded/raw sample"<bits_per_coded_sample<bits_per_raw_sample; - - sample_rate = codecpar->sample_rate; - QAudioFormat audioFmt; - audioFmt.setSampleRate(sample_rate); - audioFmt.setChannelCount(2); -#if(QT_VERSION_MAJOR > 5) - if(packed_sample_fmt==AV_SAMPLE_FMT_FLT) audioFmt.setSampleFormat(QAudioFormat::Float); - else if(packed_sample_fmt==AV_SAMPLE_FMT_S16) audioFmt.setSampleFormat(QAudioFormat::Int16); - else if(packed_sample_fmt==AV_SAMPLE_FMT_S32) audioFmt.setSampleFormat(QAudioFormat::Int32); - else if(packed_sample_fmt==AV_SAMPLE_FMT_S64) { - packed_sample_fmt = AV_SAMPLE_FMT_S32; - audioFmt.setSampleFormat(QAudioFormat::Int32); - } else if(packed_sample_fmt==AV_SAMPLE_FMT_DBL) { - packed_sample_fmt = AV_SAMPLE_FMT_FLT; - audioFmt.setSampleFormat(QAudioFormat::Float); - } else { - packed_sample_fmt = AV_SAMPLE_FMT_S16; - audioFmt.setSampleFormat(QAudioFormat::Int16); - } -#else - audioFmt.setCodec("audio/pcm"); - audioFmt.setByteOrder(QAudioFormat::LittleEndian); - if(packed_sample_fmt==AV_SAMPLE_FMT_FLT) { - audioFmt.setSampleType(QAudioFormat::Float); - audioFmt.setSampleSize(32); - } else if(packed_sample_fmt==AV_SAMPLE_FMT_S16) { - audioFmt.setSampleType(QAudioFormat::SignedInt); - audioFmt.setSampleSize(16); - } else if(packed_sample_fmt==AV_SAMPLE_FMT_S32) { - audioFmt.setSampleType(QAudioFormat::SignedInt); - audioFmt.setSampleSize(32); - } else if(packed_sample_fmt==AV_SAMPLE_FMT_S64) { - packed_sample_fmt = AV_SAMPLE_FMT_S32; - audioFmt.setSampleType(QAudioFormat::SignedInt); - audioFmt.setSampleSize(32); - } else if(packed_sample_fmt==AV_SAMPLE_FMT_DBL) { - packed_sample_fmt = AV_SAMPLE_FMT_FLT; - audioFmt.setSampleType(QAudioFormat::Float); - audioFmt.setSampleSize(32); - } else { - packed_sample_fmt = AV_SAMPLE_FMT_S16; - audioFmt.setSampleType(QAudioFormat::SignedInt); - audioFmt.setSampleSize(16); - } -#endif - sink = new QAudioSink(audioDevice, audioFmt); - sinkWriter = sink->start(); - if(sinkWriter==nullptr) { - au.idx = -1; - qCritical()<<"Couldn't Start Audio Output"<error(); - } else { - const AVCodec *decoder = avcodec_find_decoder(codecpar->codec_id); - if(decoder==nullptr) { - au.idx = -1; - qWarning()<<"Couldn't found Audio Decoder"; - } else { - au.ctx = avcodec_alloc_context3(decoder); - avcodec_parameters_to_context(au.ctx, codecpar); - if(avcodec_open2(au.ctx, decoder, nullptr) < 0) { - au.idx = -1; - qWarning()<<"Couldn't open aCodecCtx"; - } else { - out_ch_layout.order = AV_CHANNEL_ORDER_NATIVE; - out_ch_layout.nb_channels = 2; - out_ch_layout.u.mask = AV_CH_LAYOUT_STEREO; - swr_alloc_set_opts2(&swr_ctx, - &out_ch_layout, packed_sample_fmt, audioFmt.sampleRate(), - &au.ctx->ch_layout, au.ctx->sample_fmt, au.ctx->sample_rate, 0, nullptr); - if(swr_init(swr_ctx) < 0) { - au.idx = -1; - qCritical()<<"Couldn't init swrCtx"; - } else { - pcm_sample_size = audioFmt.bytesPerFrame(); - au.time_num = auStream->time_base.num * 1000000; - au.time_den = auStream->time_base.den; - au.start = auStream->start_time * au.time_num / au.time_den; - qInfo()<<"Audio Idx" << au.idx << "Start" << au.start<< "Dur" << auStream->duration * au.time_num / au.time_den; - buf_size = sink->bytesFree(); - qInfo()<<"Audio buffer size"< -1) au.thd = new thread(&AVFmt::mainAuDecode, this); - if(vi.idx > -1) vi.thd = new thread(&AVFmt::mainViDecode, this); -} -AVFmt::~AVFmt() { - if(read_thd!=nullptr) { - acts.lockAddNtf(new Act{0, nullptr, 'Q'}); - read_thd->join(); - delete read_thd; - qInfo() << "~ read thread"; - } - if(au.thd!=nullptr) { - au.thd->join(); - delete au.thd; - qInfo() << "~ au thread"; - } - if(vi.thd!=nullptr) { - vi.thd->join(); - delete vi.thd; - qInfo() << "~ vi thread"; - } - av_packet_free(&packet); - avformat_close_input(&fmt_ctx); - sws_freeContext(sws_ctx); - swr_free(&swr_ctx); - qInfo() << "~ AVContext"; -} - -void AVFmt::mainRead() { - int wait = 0; - int res = 0; - while(true) { - auto act = wait==0 ? acts.lockPoll() : acts.take(wait); - while(act!=nullptr) { - if(act->act=='S') { - if(au.idx!=-1) { - unique_lock lock(au.pkts.mtx); - au.pkts.delAll(); - au.pkts.add(new Packet{0, 0, 'R'}); - lock.unlock(); - au.pkts.cv.notify_all(); - } - if(vi.idx!=-1) { - unique_lock lock(vi.pkts.mtx); - vi.pkts.delAll(); - vi.pkts.add(new Packet{0, 0, 'R'}); - lock.unlock(); - vi.pkts.cv.notify_all(); - } - av_seek_frame(fmt_ctx, -1, act->arg, AVSEEK_FLAG_BACKWARD); - } else if(act->act=='Q') { - if(au.idx!=-1) { - unique_lock lock(au.pkts.mtx); - au.pkts.delAll(); - au.pkts.add(new Packet{0, 0, 'Q'}); - lock.unlock(); - au.pkts.cv.notify_all(); - } - if(vi.idx!=-1) { - unique_lock lock(vi.pkts.mtx); - vi.pkts.delAll(); - vi.pkts.add(new Packet{0, 0, 'Q'}); - lock.unlock(); - vi.pkts.cv.notify_all(); - } - delete act; - return; - } - delete act; - act = acts.lockPoll(); - } - if(res < 0) {wait = 500; continue;} - if(vi.pkts.size > 120 || au.pkts.size > 200) {wait = 100; continue;} - res = av_read_frame(fmt_ctx, packet); - if(res < 0) { - if(au.idx > -1) au.pkts.lockAddNtf(new Packet{0, 0, 0}); - if(vi.idx > -1) vi.pkts.lockAddNtf(new Packet{0, 0, 0}); - if(res!=AVERROR_EOF) { - qCritical()<<"Read Packet fail:"<stream_index == vi.idx) { - vi.pkts.lockAddNtf(new Packet{packet, 0, 0}); - packet = av_packet_alloc(); - } else if(packet->stream_index == au.idx) { - au.pkts.lockAddNtf(new Packet{packet, 0, 0}); - packet = av_packet_alloc(); - } - wait = 0; - } -} -void AVFmt::mainViDecode() { - while(true) { - if(vi_frms.size >= 7) { - unique_lock lock(vi.pkts.mtx); - if(vi.pkts.first && vi.pkts.first->act=='Q') return; - vi.pkts.cv.wait_for(lock, chrono::milliseconds(20)); - continue; - } - auto pkt = vi.pkts.take(); - if(pkt->act=='R') { - avcodec_flush_buffers(vi.ctx); - vi.deLoop = 0; - vi.stop = false; - } else if(pkt->act=='Q') { - delete pkt; - return; - } else if(!vi.stop) { - int res = avcodec_send_packet(vi.ctx, pkt->pkt); - if(res == AVERROR_EOF) goto end; - if(res < 0) qCritical()<<"Video send packet fail:"<width, vi.ctx->height, QImage::Format_ARGB32); - uint8_t *dst[4]{img.bits()}; - int dstStride[4]{(int)img.bytesPerLine()}; - sws_scale(sws_ctx, vi.frm->data, vi.frm->linesize, 0, vi.ctx->height, dst, dstStride); - { - lock_guard lock(vi_frms.mtx); - if(vi.stop) goto end; - viLmt = (vi.frm->best_effort_timestamp + vi.frm->pkt_duration) * vi.time_num / vi.time_den; - vi_frms.add(new Img{img, vi.frm->best_effort_timestamp * vi.time_num / vi.time_den, viLmt, vi.deLoop, 0}); - } - } - if(pkt->pkt==0) { - avcodec_flush_buffers(vi.ctx); - vi.deLoop++; - } - } - end: - delete pkt; - } -} -void AVFmt::mainAuDecode() { - while(true) { - if(au_frms.size >= 9) { - unique_lock lock(au.pkts.mtx); - if(au.pkts.first && au.pkts.first->act=='Q') return; - au.pkts.cv.wait_for(lock, chrono::milliseconds(20)); - continue; - } - auto pkt = au.pkts.take(); - if(pkt->act=='R') { - avcodec_flush_buffers(au.ctx); - au.deLoop = 0; - au.stop = false; - } else if(pkt->act=='Q') { - delete pkt; - return; - } else if(!au.stop) { - int res = avcodec_send_packet(au.ctx, pkt->pkt); - if(res == AVERROR_EOF) goto end; - if(res < 0) qCritical()<<"Audio send packet fail:"<nb_samples<=0) continue; - auto pcm = new uint8_t[au.frm->nb_samples * pcm_sample_size]; - int samp_cnt = swr_convert(swr_ctx, &pcm, au.frm->nb_samples, (const uint8_t **)&au.frm->data, au.frm->nb_samples); - if(samp_cnt<=0) { - delete [] pcm; - qWarning()<<"swr convert fail:"< lock(au_frms.mtx); - if(au.stop) { - delete [] pcm; - goto end; - } - au_frms.add(new Pcm{pcm, samp_cnt * pcm_sample_size, au.frm->best_effort_timestamp * au.time_num / au.time_den, (au.frm->best_effort_timestamp + au.frm->pkt_duration) * au.time_num / au.time_den, au.deLoop, 0}); - } - } - if(pkt->pkt==0) { - avcodec_flush_buffers(au.ctx); - au.deLoop++; - } - } - end: - delete pkt; - } -} - -void AVFmt::checkAndUpd(FFPlayer *player, qint64 now_epoch) { - if(vi.isNull()) { - playAudio(au_frms.lockGet(), player, now_epoch); - return; - } - if(au.isNull()) { - player->hasImg = false; - auto viFrm = vi_frms.lockGet(); - if(viFrm==0) return; - if(start_epoch==0) { - if(vi.start > viFrm->st) { - vi.start = viFrm->st; - if(start > viFrm->st) start = viFrm->st; - } - start_epoch = now_epoch - start + 12500; - return; - } - qint64 cur = now_epoch - start_epoch; - checkFrm: - if(viFrm->loop!=playLoop) { - playLoop = viFrm->loop; - start_epoch = now_epoch - start + 12500; - qInfo()<<"Restart"; - return; - } - if(viFrm->et < cur - 8334) { - if(viFrm->next) { - qWarning() << "Drop video frame. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000 << "Video Only"; - viFrm = vi_frms.lockDelGetNext(); - goto checkFrm; - } - qInfo() << "Video Adjust Start. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000 << "Video Only"; - cur = viFrm->st; - start_epoch = now_epoch - cur; - } - if(viFrm->st > cur) return; - player->img = viFrm->img; - player->hasImg = true; - player->viCurTime = viFrm->st; - delete vi_frms.lockPoll(); - return; - } - player->hasImg = false; - auto auFrm = au_frms.lockGet(); - auto viFrm = vi_frms.lockGet(); - if(start_epoch==0) { - if(viFrm==0) { - if(vi.start < start+500000) return; - } else if(vi.start > viFrm->st) { - vi.start = viFrm->st; - if(start > viFrm->st) start = viFrm->st; - } - if(auFrm==0) { - if(au.start < start+500000) return; - } else if(au.start > auFrm->st) { - au.start = auFrm->st; - if(start > auFrm->st) start = auFrm->st; - } - start_epoch = now_epoch - (start - 12500); - playAudio(auFrm, player, now_epoch, vi.pkts.lockGet()==0 ? INT64_MAX : viLmt); - return; - } - if(viFrm==0) { - if(vi.pkts.lockGet()==0) playAudio(auFrm, player, now_epoch); - return; - } - if(viFrm->loop!=playLoop) { - playAudio(auFrm, player, now_epoch); - return; - } - qint64 cur = now_epoch - start_epoch; - if(auFrm && auFrm->st < cur && auFrm->loop==playLoop) { - qInfo() << "Audio Adjust Start. st-cur" << (auFrm->st - cur)/1000 << "st" << auFrm->st/1000 << "cur" << cur/1000; - cur = auFrm->st; - start_epoch = now_epoch - cur; - } - qint64 curPre = cur - 8334; - while(viFrm->et < curPre && viFrm->next && viFrm->next->loop==playLoop) { - qWarning() << "Drop video frame. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000; - viFrm = vi_frms.lockDelGetNext(); - } - auto bytesFree = sink->bytesFree(); - bool isIdle = bytesFree==buf_size || sink->state()==QAudio::IdleState; - if(viFrm->et < curPre) { - if(isIdle) { - qInfo() << "Video Adjust Start. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000; - cur = viFrm->st; - start_epoch = now_epoch - cur; - } else qInfo() << "Video et < cur. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000; - } - if(auFrm && bytesFree >= auFrm->size && auFrm->loop==playLoop) whiteAudio(auFrm, player, isIdle, cur, vi.deLoop!=playLoop || vi.pkts.lockGet()==0 ? INT64_MAX : viLmt); - if(viFrm->st > cur) return; - player->img = viFrm->img; - player->hasImg = true; - player->viCurTime = viFrm->st; - delete vi_frms.lockPoll(); -} -void AVFmt::playAudio(Pcm *auFrm, FFPlayer *player, qint64 now_epoch, qint64 lmt) { - if(auFrm==0) return; - auto bytesFree = sink->bytesFree(); - if(bytesFree < auFrm->size) return; - bool isIdle = bytesFree==buf_size || sink->state()==QAudio::IdleState; - qint64 cur = now_epoch - start_epoch; - if(start_epoch==0) { - if(au.start > auFrm->st) { - au.start = auFrm->st; - if(start > auFrm->st) start = auFrm->st; - } - cur = start - 12500; - start_epoch = now_epoch - cur; - } else if(auFrm->loop!=playLoop) { - if(! isIdle) return; - playLoop = auFrm->loop; - cur = start - 12500; - start_epoch = now_epoch - cur; - qInfo()<<"Restart"; - } - if(auFrm->st < cur) { - qInfo() << "Audio Adjust Start. st-cur" << (auFrm->st - cur)/1000 << "st" << auFrm->st/1000 << "cur" << cur/1000 << "isIdle" << isIdle; - cur = auFrm->st; - start_epoch = now_epoch - cur; - } - whiteAudio(auFrm, player, isIdle, cur, lmt); - return; -} -void AVFmt::whiteAudio(Pcm *auFrm, FFPlayer *player, bool isIdle, qint64 cur, qint64 lmt) { - if(auFrm->st >= lmt) return; - if(isIdle) { - auto delay = auFrm->st - cur; - if(delay > 50000) return; - else if(delay > 999) { - auto size = (delay * sample_rate / 1000000) * pcm_sample_size; - char *data = new char[size](); - sinkWriter->write(data, size); - delete [] data; - } - } - do { - sinkWriter->write((char*)auFrm->data, auFrm->size); - player->auCurTime = auFrm->st; - auFrm = au_frms.lockDelGetNext(); - } while(auFrm && auFrm->data && sink->bytesFree() >= auFrm->size && auFrm->st < lmt); -} - -FFPlayer::FFPlayer() { - thread = new QThread(); - moveToThread(thread); - connect(thread, &QThread::finished, thread, &QThread::deleteLater); - connect(thread, &QThread::finished, this, &FFPlayer::deleteLater); - connect(this, &FFPlayer::emQuit, this, &FFPlayer::onQuit); - connect(this, &FFPlayer::emOpen, this, &FFPlayer::onOpen); - connect(this, &FFPlayer::emClose, this, &FFPlayer::onClose); - connect(this, &FFPlayer::emPlay, this, &FFPlayer::onPlay); - connect(this, &FFPlayer::emPause, this, &FFPlayer::onPause); - connect(this, &FFPlayer::emStop, this, &FFPlayer::onStop); - connect(this, &FFPlayer::emVol, this, &FFPlayer::onVol); - thread->start(); -} -FFPlayer::~FFPlayer() { - qInfo()<<"~ FFPlayer"; -} - -void FFPlayer::onQuit() { - onClose(); - thread->quit(); -} -void FFPlayer::onOpen(QByteArray url) { - onClose(); - ctx = new AVFmt(url); - if(mVol!=1.0 && ctx->sink) ctx->sink->setVolume(mVol); - if(ctx->err.isEmpty()) status = Paused; - else { - qCritical()<err; - emit emError(ctx->err); - delete ctx; - ctx = 0; - } -} -void FFPlayer::onClose() { - status = Closed; - if(audioDaemonTimerId!=0) { - killTimer(audioDaemonTimerId); - audioDaemonTimerId = 0; - } - if(ctx==0) return; - if(ctx->sink) { - ctx->sink->stop(); - delete ctx->sink; - } - delete ctx; - ctx = 0; - emit emUpd(QImage()); -} - -void FFPlayer::onPlay() { - if(ctx==0) return; - status = Playing; - ctx->sink->resume(); - startAudioDaemon(); -} -void FFPlayer::onPause() { - if(ctx==0) return; - status = Paused; - ctx->sink->suspend(); -} -void FFPlayer::onStop() { - if(audioDaemonTimerId!=0) { - killTimer(audioDaemonTimerId); - audioDaemonTimerId = 0; - } - if(ctx==0) return; - if(ctx->sink) { - ctx->sink->stop(); - ctx->sinkWriter = ctx->sink->start(); - } - lock_guard lock(ctx->acts.mtx); - ctx->vi.stop = true; - ctx->au.stop = true; - status = Paused; - ctx->start_epoch = 0; - ctx->playLoop = 0; - ctx->au_frms.lockDelAll(); - ctx->vi_frms.lockDelAll(); - img = QImage(); - ctx->acts.add(new Act{0, 0, 'S'}); - ctx->acts.cv.notify_all(); -} -void FFPlayer::onVol(qreal vol) { - mVol = vol; - if(ctx && ctx->sink) ctx->sink->setVolume(vol); -} - -void FFPlayer::updFrame() { - if(ctx==0) return; - if(status!=Playing) { - if(img.isNull()) { - lock_guard lock(ctx->vi_frms.mtx); - viSize = ctx->vi_frms.size; - auSize = ctx->au_frms.size; - if(ctx->vi_frms.first==0) return; - img = ctx->vi_frms.first->img; - emit emUpd(img); - } - return; - } - auto now_epoch = chrono::duration_cast(chrono::steady_clock::now().time_since_epoch()).count(); - dur = now_epoch - last_epoch; - last_epoch = now_epoch; - if(dur>100000) return; - if(dur<4000) { - qWarning()<<"FFPlayer UpdFrame Fail: dur"<checkAndUpd(this, now_epoch); - viSize = ctx->vi_frms.size; - auSize = ctx->au_frms.size; - if(hasImg) emit emUpd(img); - startAudioDaemon(); - -} -void FFPlayer::timerEvent(QTimerEvent *event) { - if(event->timerId()!=audioDaemonTimerId) return; - if(ctx==0 || status!=Playing) { - if(audioDaemonTimerId!=0) { - killTimer(audioDaemonTimerId); - audioDaemonTimerId = 0; - } - return; - } - auto now_epoch = chrono::duration_cast(chrono::steady_clock::now().time_since_epoch()).count(); - auto dur = now_epoch - last_epoch; - if(dur<=40000 && ! ctx->vi.isNull()) return; - ctx->checkAndUpd(this, now_epoch); - viSize = ctx->vi_frms.size; - auSize = ctx->au_frms.size; - if(hasImg) emit emUpd(img); -} +#include "ffplayer.h" +#include +#include +#if(QT_VERSION_MAJOR > 5) + #include +#endif +#include +#include + +using namespace std; + +AVFmt::AVFmt(QByteArray url) { + fmt_ctx = avformat_alloc_context(); + int res = avformat_open_input(&fmt_ctx, url.constData(), 0, 0); + if(res < 0) { + err = "Open input fail: "+errStr(res); + return; + } + res = avformat_find_stream_info(fmt_ctx, 0); + if(res < 0) { + err = "Find stream info fail: "+errStr(res); + return; + } + start = fmt_ctx->start_time; + qInfo() << "Fmt Start" << start << "Dur" << fmt_ctx->duration; + for(uint ss=0; ssnb_streams; ss++) if(fmt_ctx->streams[ss]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {vi.idx = ss; break;} + for(uint ss=0; ssnb_streams; ss++) if(fmt_ctx->streams[ss]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {au.idx = ss; break;} + if(vi.idx == -1) qWarning()<<"Didn't find a Video Stream"; + else { + auto viStream = fmt_ctx->streams[vi.idx]; + auto decoder = avcodec_find_decoder(viStream->codecpar->codec_id); + if(decoder==0) { + vi.idx = -1; + qCritical()<<"avcodec_find_decoder fail"; + } else { + vi.ctx = avcodec_alloc_context3(decoder); + avcodec_parameters_to_context(vi.ctx, viStream->codecpar); + vi.ctx->thread_count = 0; + if((res = avcodec_open2(vi.ctx, decoder, 0)) < 0) { + vi.idx = -1; + qCritical()<<"avcodec_open2 fail:"<width*4+63)/64*64; + dstStride[3] = dstStride[0] * vi.ctx->height; + sws_ctx = sws_getContext(vi.ctx->width, vi.ctx->height, vi.ctx->pix_fmt, vi.ctx->width, vi.ctx->height, AV_PIX_FMT_RGB32, SWS_FAST_BILINEAR, 0, 0, 0); + if(vi.ctx->color_primaries==AVCOL_PRI_BT2020) { + res = sws_setColorspaceDetails(sws_ctx, sws_getCoefficients(SWS_CS_BT2020), 0, sws_getCoefficients(SWS_CS_DEFAULT), 0, -0x2200, 0x1c000, 0x18000); //0x12800, 0x40000 + if(res < 0) qInfo()<<"sws_setColorspaceDetails fail:"<time_base.num * 1000000; + vi.time_den = viStream->time_base.den; + vi.start = viStream->start_time * vi.time_num / vi.time_den; + frmDur = viStream->r_frame_rate.den * 1000000 / viStream->r_frame_rate.num; + qInfo()<<"Video idx" << vi.idx << "Start" << vi.start << "dur" << viStream->duration * vi.time_num / vi.time_den << "frame dur" << frmDur; + if(frmDur <= 0) frmDur = 16666; + } + } + } + if(au.idx == -1) qInfo()<<"Couldn't find a Audio Stream"; + else { + auto auStream = fmt_ctx->streams[au.idx]; +#if(QT_VERSION_MAJOR > 5) + QAudioDevice audioDevice = QMediaDevices::defaultAudioOutput(); +#else + QAudioDeviceInfo audioDevice = QAudioDeviceInfo::defaultOutputDevice(); +#endif + if(audioDevice.isNull()) { + au.idx = -1; + qInfo()<<"Couldn't find a Audio Device"; + } else { + AVCodecParameters *codecpar = auStream->codecpar; + AVSampleFormat packed_sample_fmt = av_get_packed_sample_fmt((AVSampleFormat)codecpar->format); + qInfo()<<"audio codecpar:"; + qInfo()<<" sample_rate"<sample_rate; + qInfo()<<" frame_size"<frame_size; + qInfo()<<" sample_fmt"<format); + qInfo()<<" bits per coded/raw sample"<bits_per_coded_sample<bits_per_raw_sample; + + sample_rate = codecpar->sample_rate; + QAudioFormat audioFmt; + audioFmt.setSampleRate(sample_rate); + audioFmt.setChannelCount(2); +#if(QT_VERSION_MAJOR > 5) + if(packed_sample_fmt==AV_SAMPLE_FMT_FLT) audioFmt.setSampleFormat(QAudioFormat::Float); + else if(packed_sample_fmt==AV_SAMPLE_FMT_S16) audioFmt.setSampleFormat(QAudioFormat::Int16); + else if(packed_sample_fmt==AV_SAMPLE_FMT_S32) audioFmt.setSampleFormat(QAudioFormat::Int32); + else if(packed_sample_fmt==AV_SAMPLE_FMT_S64) { + packed_sample_fmt = AV_SAMPLE_FMT_S32; + audioFmt.setSampleFormat(QAudioFormat::Int32); + } else if(packed_sample_fmt==AV_SAMPLE_FMT_DBL) { + packed_sample_fmt = AV_SAMPLE_FMT_FLT; + audioFmt.setSampleFormat(QAudioFormat::Float); + } else { + packed_sample_fmt = AV_SAMPLE_FMT_S16; + audioFmt.setSampleFormat(QAudioFormat::Int16); + } +#else + audioFmt.setCodec("audio/pcm"); + audioFmt.setByteOrder(QAudioFormat::LittleEndian); + if(packed_sample_fmt==AV_SAMPLE_FMT_FLT) { + audioFmt.setSampleType(QAudioFormat::Float); + audioFmt.setSampleSize(32); + } else if(packed_sample_fmt==AV_SAMPLE_FMT_S16) { + audioFmt.setSampleType(QAudioFormat::SignedInt); + audioFmt.setSampleSize(16); + } else if(packed_sample_fmt==AV_SAMPLE_FMT_S32) { + audioFmt.setSampleType(QAudioFormat::SignedInt); + audioFmt.setSampleSize(32); + } else if(packed_sample_fmt==AV_SAMPLE_FMT_S64) { + packed_sample_fmt = AV_SAMPLE_FMT_S32; + audioFmt.setSampleType(QAudioFormat::SignedInt); + audioFmt.setSampleSize(32); + } else if(packed_sample_fmt==AV_SAMPLE_FMT_DBL) { + packed_sample_fmt = AV_SAMPLE_FMT_FLT; + audioFmt.setSampleType(QAudioFormat::Float); + audioFmt.setSampleSize(32); + } else { + packed_sample_fmt = AV_SAMPLE_FMT_S16; + audioFmt.setSampleType(QAudioFormat::SignedInt); + audioFmt.setSampleSize(16); + } +#endif + sink = new QAudioSink(audioDevice, audioFmt); + sinkWriter = sink->start(); + if(sinkWriter==nullptr) { + au.idx = -1; + qCritical()<<"Couldn't Start Audio Output"<error(); + } else { + const AVCodec *decoder = avcodec_find_decoder(codecpar->codec_id); + if(decoder==nullptr) { + au.idx = -1; + qWarning()<<"Couldn't found Audio Decoder"; + } else { + au.ctx = avcodec_alloc_context3(decoder); + avcodec_parameters_to_context(au.ctx, codecpar); + if(avcodec_open2(au.ctx, decoder, nullptr) < 0) { + au.idx = -1; + qWarning()<<"Couldn't open aCodecCtx"; + } else { + #if(QT_VERSION_MAJOR < 6) + out_ch_layout.order = AV_CHANNEL_ORDER_NATIVE; + out_ch_layout.nb_channels = 2; + out_ch_layout.u.mask = AV_CH_LAYOUT_STEREO; + #endif + swr_alloc_set_opts2(&swr_ctx, + &out_ch_layout, packed_sample_fmt, audioFmt.sampleRate(), + &au.ctx->ch_layout, au.ctx->sample_fmt, au.ctx->sample_rate, 0, nullptr); + if(swr_init(swr_ctx) < 0) { + au.idx = -1; + qCritical()<<"Couldn't init swrCtx"; + } else { + pcm_sample_size = audioFmt.bytesPerFrame(); + au.time_num = auStream->time_base.num * 1000000; + au.time_den = auStream->time_base.den; + au.start = auStream->start_time * au.time_num / au.time_den; + qInfo()<<"Audio Idx" << au.idx << "Start" << au.start<< "Dur" << auStream->duration * au.time_num / au.time_den; + buf_size = sink->bytesFree(); + qInfo()<<"Audio buffer size"< -1) au.thd = new thread(&AVFmt::mainAuDecode, this); + if(vi.idx > -1) vi.thd = new thread(&AVFmt::mainViDecode, this); +} +AVFmt::~AVFmt() { + if(read_thd!=nullptr) { + acts.lockAddNtf(new Act{0, nullptr, 'Q'}); + read_thd->join(); + delete read_thd; + qInfo() << "~ read thread"; + } + if(au.thd!=nullptr) { + au.thd->join(); + delete au.thd; + qInfo() << "~ au thread"; + } + if(vi.thd!=nullptr) { + vi.thd->join(); + delete vi.thd; + qInfo() << "~ vi thread"; + } + av_packet_free(&packet); + avformat_close_input(&fmt_ctx); + sws_freeContext(sws_ctx); + swr_free(&swr_ctx); + qInfo() << "~ AVContext"; +} + +void AVFmt::mainRead() { + int wait = 0; + int res = 0; + while(true) { + auto act = wait==0 ? acts.lockPoll() : acts.take(wait); + while(act!=nullptr) { + if(act->act=='S') { + if(au.idx!=-1) { + unique_lock lock(au.pkts.mtx); + au.pkts.delAll(); + au.pkts.add(new Packet{0, 0, 'R'}); + lock.unlock(); + au.pkts.cv.notify_all(); + } + if(vi.idx!=-1) { + unique_lock lock(vi.pkts.mtx); + vi.pkts.delAll(); + vi.pkts.add(new Packet{0, 0, 'R'}); + lock.unlock(); + vi.pkts.cv.notify_all(); + } + av_seek_frame(fmt_ctx, -1, act->arg, act->arg==0 ? AVSEEK_FLAG_FRAME : AVSEEK_FLAG_BACKWARD); + } else if(act->act=='Q') { + if(au.idx!=-1) { + unique_lock lock(au.pkts.mtx); + au.pkts.delAll(); + au.pkts.add(new Packet{0, 0, 'Q'}); + lock.unlock(); + au.pkts.cv.notify_all(); + } + if(vi.idx!=-1) { + unique_lock lock(vi.pkts.mtx); + vi.pkts.delAll(); + vi.pkts.add(new Packet{0, 0, 'Q'}); + lock.unlock(); + vi.pkts.cv.notify_all(); + } + delete act; + return; + } + delete act; + act = acts.lockPoll(); + } + if(res < 0) {wait = 500; continue;} + if(vi.pkts.size > 120 || au.pkts.size > 200) {wait = 100; continue;} + res = av_read_frame(fmt_ctx, packet); + if(res < 0) { + if(au.idx > -1) au.pkts.lockAddNtf(new Packet{0, 0, 0}); + if(vi.idx > -1) vi.pkts.lockAddNtf(new Packet{0, 0, 0}); + if(res!=AVERROR_EOF) { + qCritical()<<"Read Packet fail:"<stream_index == vi.idx) { + vi.pkts.lockAddNtf(new Packet{packet, 0, 0}); + packet = av_packet_alloc(); + } else if(packet->stream_index == au.idx) { + au.pkts.lockAddNtf(new Packet{packet, 0, 0}); + packet = av_packet_alloc(); + } + wait = 0; + } +} +static void imgCleanupHandler(void *info) { + delete [] (uchar*)info; +} +void AVFmt::mainViDecode() { + uint8_t *dst[4]{0}; + while(true) { + if(vi_frms.size >= 7) { + unique_lock lock(vi.pkts.mtx); + if(vi.pkts.first && vi.pkts.first->act=='Q') return; + vi.pkts.cv.wait_for(lock, chrono::milliseconds(20)); + continue; + } + auto pkt = vi.pkts.take(); + if(pkt->act=='R') { + avcodec_flush_buffers(vi.ctx); + vi.deLoop = 0; + vi.stop = false; + } else if(pkt->act=='Q') { + delete pkt; + return; + } else if(!vi.stop) { + int res = avcodec_send_packet(vi.ctx, pkt->pkt); + if(res == AVERROR_EOF) goto end; + if(res < 0) qCritical()<<"Video send packet fail:"<data, vi.frm->linesize, 0, vi.ctx->height, dst, dstStride); + QImage img(dst[0], vi.ctx->width, vi.ctx->height, dstStride[0], QImage::Format_ARGB32, imgCleanupHandler, dst[0]); + { + lock_guard lock(vi_frms.mtx); + if(vi.stop) goto end; + if(vi.frm->pkt_duration) viLmt = (vi.frm->best_effort_timestamp + vi.frm->pkt_duration) * vi.time_num / vi.time_den; + else viLmt = vi.frm->best_effort_timestamp * vi.time_num / vi.time_den + frmDur; + vi_frms.add(new Img{img, vi.frm->best_effort_timestamp * vi.time_num / vi.time_den, viLmt, vi.deLoop, 0}); + } + } + if(pkt->pkt==0) { + avcodec_flush_buffers(vi.ctx); + vi.deLoop++; + } + } + end: + delete pkt; + } +} +void AVFmt::mainAuDecode() { + while(true) { + if(au_frms.size >= 9) { + unique_lock lock(au.pkts.mtx); + if(au.pkts.first && au.pkts.first->act=='Q') return; + au.pkts.cv.wait_for(lock, chrono::milliseconds(20)); + continue; + } + auto pkt = au.pkts.take(); + if(pkt->act=='R') { + avcodec_flush_buffers(au.ctx); + au.deLoop = 0; + au.stop = false; + } else if(pkt->act=='Q') { + delete pkt; + return; + } else if(!au.stop) { + int res = avcodec_send_packet(au.ctx, pkt->pkt); + if(res == AVERROR_EOF) goto end; + if(res < 0) qCritical()<<"Audio send packet fail:"<nb_samples<=0) continue; + auto pcm = new uint8_t[au.frm->nb_samples * pcm_sample_size]; + int samp_cnt = swr_convert(swr_ctx, &pcm, au.frm->nb_samples, (const uint8_t **)&au.frm->data, au.frm->nb_samples); + if(samp_cnt<=0) { + delete [] pcm; + qWarning()<<"swr convert fail:"< lock(au_frms.mtx); + if(au.stop) { + delete [] pcm; + goto end; + } + au_frms.add(new Pcm{pcm, samp_cnt * pcm_sample_size, au.frm->best_effort_timestamp * au.time_num / au.time_den, (au.frm->best_effort_timestamp + au.frm->pkt_duration) * au.time_num / au.time_den, au.deLoop, 0}); + } + } + if(pkt->pkt==0) { + avcodec_flush_buffers(au.ctx); + au.deLoop++; + } + } + end: + delete pkt; + } +} + +void AVFmt::checkAndUpd(FFPlayer *player, qint64 now_epoch) { + if(vi.isNull()) { + playAudio(au_frms.lockGet(), player, now_epoch); + return; + } + if(au.isNull()) { + player->hasImg = false; + auto viFrm = vi_frms.lockGet(); + if(viFrm==0) return; + if(start_epoch==0) { + if(vi.start > viFrm->st) { + vi.start = viFrm->st; + if(start > viFrm->st) start = viFrm->st; + } + start_epoch = now_epoch - start + 12500; + return; + } + qint64 cur = now_epoch - start_epoch; + checkFrm: + if(viFrm->loop!=playLoop) { + playLoop = viFrm->loop; + start_epoch = now_epoch - start + 12500; + qInfo()<<"Restart"; + return; + } + if(viFrm->et < cur - 8334) { + if(viFrm->next) { + qWarning() << "Drop video frame. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000 << "Video Only"; + viFrm = vi_frms.lockDelGetNext(); + goto checkFrm; + } + qInfo() << "Video Adjust Start. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000 << "Video Only"; + cur = viFrm->st; + start_epoch = now_epoch - cur; + } + if(viFrm->st > cur) return; + player->img = viFrm->img; + player->hasImg = true; + player->viCurTime = viFrm->st; + delete vi_frms.lockPoll(); + return; + } + player->hasImg = false; + auto auFrm = au_frms.lockGet(); + auto viFrm = vi_frms.lockGet(); + if(start_epoch==0) { + if(viFrm==0) { + if(vi.start < start+500000) return; + } else if(vi.start > viFrm->st) { + vi.start = viFrm->st; + if(start > viFrm->st) start = viFrm->st; + } + if(auFrm==0) { + if(au.start < start+500000) return; + } else if(au.start > auFrm->st) { + au.start = auFrm->st; + if(start > auFrm->st) start = auFrm->st; + } + start_epoch = now_epoch - (start - 12500); + playAudio(auFrm, player, now_epoch, vi.pkts.lockGet()==0 ? INT64_MAX : viLmt); + return; + } + if(viFrm==0) { + if(vi.pkts.lockGet()==0) playAudio(auFrm, player, now_epoch); + return; + } + if(viFrm->loop!=playLoop) { + playAudio(auFrm, player, now_epoch); + return; + } + qint64 cur = now_epoch - start_epoch; + if(auFrm && auFrm->st < cur && auFrm->loop==playLoop) { + qInfo() << "Audio Adjust Start. st-cur" << (auFrm->st - cur)/1000 << "st" << auFrm->st/1000 << "cur" << cur/1000; + cur = auFrm->st; + start_epoch = now_epoch - cur; + } + qint64 curPre = cur - 8334; + while(viFrm->et < curPre && viFrm->next && viFrm->next->loop==playLoop) { + qWarning() << "Drop video frame. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000; + viFrm = vi_frms.lockDelGetNext(); + } + auto bytesFree = sink->bytesFree(); + bool isIdle = bytesFree==buf_size || sink->state()==QAudio::IdleState; + if(viFrm->et < curPre) { + if(isIdle) { + qInfo() << "Video Adjust Start. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000; + cur = viFrm->st; + start_epoch = now_epoch - cur; + } else qInfo() << "Video et < cur. st-cur" << (viFrm->st - cur)/1000 << "st" << viFrm->st/1000 << "cur" << cur/1000; + } + if(auFrm && bytesFree >= auFrm->size && auFrm->loop==playLoop) whiteAudio(auFrm, player, isIdle, cur, vi.deLoop!=playLoop || vi.pkts.lockGet()==0 ? INT64_MAX : viLmt); + if(viFrm->st > cur) return; + player->img = viFrm->img; + player->hasImg = true; + player->viCurTime = viFrm->st; + delete vi_frms.lockPoll(); +} +void AVFmt::playAudio(Pcm *auFrm, FFPlayer *player, qint64 now_epoch, qint64 lmt) { + if(auFrm==0) return; + auto bytesFree = sink->bytesFree(); + if(bytesFree < auFrm->size) return; + bool isIdle = bytesFree==buf_size || sink->state()==QAudio::IdleState; + qint64 cur = now_epoch - start_epoch; + if(start_epoch==0) { + if(au.start > auFrm->st) { + au.start = auFrm->st; + if(start > auFrm->st) start = auFrm->st; + } + cur = start - 12500; + start_epoch = now_epoch - cur; + } else if(auFrm->loop!=playLoop) { + if(! isIdle) return; + playLoop = auFrm->loop; + cur = start - 12500; + start_epoch = now_epoch - cur; + qInfo()<<"Restart"; + } + if(auFrm->st < cur) { + qInfo() << "Audio Adjust Start. st-cur" << (auFrm->st - cur)/1000 << "st" << auFrm->st/1000 << "cur" << cur/1000 << "isIdle" << isIdle; + cur = auFrm->st; + start_epoch = now_epoch - cur; + } + whiteAudio(auFrm, player, isIdle, cur, lmt); + return; +} +void AVFmt::whiteAudio(Pcm *auFrm, FFPlayer *player, bool isIdle, qint64 cur, qint64 lmt) { + if(auFrm->st >= lmt) return; + if(isIdle) { + auto delay = auFrm->st - cur; + if(delay > 50000) return; + else if(delay > 999) { + auto size = (delay * sample_rate / 1000000) * pcm_sample_size; + char *data = new char[size](); + sinkWriter->write(data, size); + delete [] data; + } + } + do { + sinkWriter->write((char*)auFrm->data, auFrm->size); + player->auCurTime = auFrm->st; + auFrm = au_frms.lockDelGetNext(); + } while(auFrm && auFrm->data && sink->bytesFree() >= auFrm->size && auFrm->st < lmt); +} + +FFPlayer::FFPlayer() { + thread = new QThread(); + moveToThread(thread); + connect(thread, &QThread::finished, thread, &QThread::deleteLater); + connect(thread, &QThread::finished, this, &FFPlayer::deleteLater); + connect(this, &FFPlayer::emQuit, this, &FFPlayer::onQuit); + connect(this, &FFPlayer::emOpen, this, &FFPlayer::onOpen); + connect(this, &FFPlayer::emClose, this, &FFPlayer::onClose); + connect(this, &FFPlayer::emPlay, this, &FFPlayer::onPlay); + connect(this, &FFPlayer::emPause, this, &FFPlayer::onPause); + connect(this, &FFPlayer::emStop, this, &FFPlayer::onStop); + connect(this, &FFPlayer::emVol, this, &FFPlayer::onVol); + thread->start(); +} +FFPlayer::~FFPlayer() { + qInfo()<<"~ FFPlayer"; +} + +void FFPlayer::onQuit() { + onClose(); + thread->quit(); +} +void FFPlayer::onOpen(QByteArray url) { + onClose(); + ctx = new AVFmt(url); + if(mVol!=1.0 && ctx->sink) ctx->sink->setVolume(mVol); + if(ctx->err.isEmpty()) status = Paused; + else { + qCritical()<err; + emit emError(ctx->err); + delete ctx; + ctx = 0; + } +} +void FFPlayer::onClose() { + status = Closed; + if(audioDaemonTimerId!=0) { + killTimer(audioDaemonTimerId); + audioDaemonTimerId = 0; + } + if(ctx==0) return; + if(ctx->sink) { + ctx->sink->stop(); + delete ctx->sink; + } + delete ctx; + ctx = 0; + emit emUpd(QImage()); +} + +void FFPlayer::onPlay() { + if(ctx==0) return; + status = Playing; + if(ctx->sink) ctx->sink->resume(); + startAudioDaemon(); +} +void FFPlayer::onPause() { + if(ctx==0) return; + status = Paused; + if(ctx->sink) ctx->sink->suspend(); +} +void FFPlayer::onStop() { + if(audioDaemonTimerId!=0) { + killTimer(audioDaemonTimerId); + audioDaemonTimerId = 0; + } + if(ctx==0) return; + if(ctx->sink) { + ctx->sink->stop(); + ctx->sinkWriter = ctx->sink->start(); + } + lock_guard lock(ctx->acts.mtx); + ctx->vi.stop = true; + ctx->au.stop = true; + status = Paused; + ctx->start_epoch = 0; + ctx->playLoop = 0; + ctx->au_frms.lockDelAll(); + ctx->vi_frms.lockDelAll(); + img = QImage(); + ctx->acts.add(new Act{0, 0, 'S'}); + ctx->acts.cv.notify_all(); +} +void FFPlayer::onVol(qreal vol) { + mVol = vol; + if(ctx && ctx->sink) ctx->sink->setVolume(vol); +} + +void FFPlayer::updFrame() { + if(ctx==0) return; + if(status!=Playing) { + if(img.isNull()) { + lock_guard lock(ctx->vi_frms.mtx); + viSize = ctx->vi_frms.size; + auSize = ctx->au_frms.size; + if(ctx->vi_frms.first==0) return; + img = ctx->vi_frms.first->img; + emit emUpd(img); + } + return; + } + auto now_epoch = chrono::duration_cast(chrono::steady_clock::now().time_since_epoch()).count(); + dur = now_epoch - last_epoch; + last_epoch = now_epoch; + if(dur>100000) return; + if(dur<4000) { + qWarning()<<"FFPlayer UpdFrame Fail: dur"<checkAndUpd(this, now_epoch); + viSize = ctx->vi_frms.size; + auSize = ctx->au_frms.size; + if(hasImg) emit emUpd(img); + startAudioDaemon(); + +} +void FFPlayer::timerEvent(QTimerEvent *event) { + if(event->timerId()!=audioDaemonTimerId) return; + if(ctx==0 || status!=Playing) { + if(audioDaemonTimerId!=0) { + killTimer(audioDaemonTimerId); + audioDaemonTimerId = 0; + } + return; + } + auto now_epoch = chrono::duration_cast(chrono::steady_clock::now().time_since_epoch()).count(); + auto dur = now_epoch - last_epoch; + if(dur<=40000 && ! ctx->vi.isNull()) return; + ctx->checkAndUpd(this, now_epoch); + viSize = ctx->vi_frms.size; + auSize = ctx->au_frms.size; + if(hasImg) emit emUpd(img); +} diff --git a/LedOK/ffplayer.h b/LedOK/ffplayer.h index 668a276..b07e0ff 100644 --- a/LedOK/ffplayer.h +++ b/LedOK/ffplayer.h @@ -1,260 +1,265 @@ -#ifndef FFPLAYER_H -#define FFPLAYER_H - -#include -#include -#include -#if(QT_VERSION_MAJOR > 5) - #include -#else - #include - typedef QAudioOutput QAudioSink; - typedef QAudioDeviceInfo QAudioDevice; -#endif -extern "C"{ -#include -#include -#include -#include -} - -template -class Queue { -public: - virtual ~Queue() { - delAll(); - } - void add(T *node) { - if(node==nullptr) { - throw std::invalid_argument("node is null"); - return; - } - if(last!=nullptr) last->next = node; - else first = node; - last = node; - size++; - } - void remove() { - if(first==nullptr) return; - if(first==last) first = last = nullptr; - else first = first->next; - size--; - } - T *poll() { - auto node = first; - remove(); - return node; - } - T *delGetNext() { - delete poll(); - return first; - } - T *removeGetNext() { - remove(); - return first; - } - void delAll() { - while(first!=nullptr) delete poll(); - } - - T *volatile first{0}; - T *volatile last{0}; - volatile int size{0}; -}; - -template -class ConQueue : public Queue { -public: - virtual ~ConQueue() { - std::lock_guard lock(mtx); - this->delAll(); - } - void lockAddNtf(T *node) { - { - std::lock_guard lock(mtx); - this->add(node); - } - cv.notify_one(); - } - void lockRemove() { - std::lock_guard lock(mtx); - this->remove(); - } - T *lockPoll() { - std::lock_guard lock(mtx); - return this->poll(); - } - T *lockGet() { - std::lock_guard lock(mtx); - return this->first; - } - T *lockDelGetNext() { - std::lock_guard lock(mtx); - return this->delGetNext(); - } - T *lockRemoveGetNext() { - std::lock_guard lock(mtx); - return this->removeGetNext(); - } - void lockDelAll() { - std::lock_guard lock(mtx); - this->delAll(); - } - - T *take(int ms = 0) { - std::unique_lock lock(mtx); - if(ms==0) while(this->first==nullptr) cv.wait(lock); - else if(this->first==nullptr) cv.wait_for(lock, std::chrono::milliseconds(ms)); - return this->poll(); - } - std::mutex mtx; - std::condition_variable cv; -}; -struct Act { - qint64 arg; - Act *next; - char act; -}; -struct Packet { - AVPacket *pkt; - Packet *next; - uchar act; - ~Packet() {av_packet_free(&pkt);} -}; -struct Img { - QImage img; - qint64 st; - qint64 et; - uint loop; - Img *next; -}; -struct Pcm { - uint8_t *data; - int size; - qint64 st; - qint64 et; - uint loop; - Pcm *next; - ~Pcm() {if(data!=nullptr) delete [] data;} -}; -class Type { -public: - inline bool isNull(){return idx <= -1;} - int idx{-1}; - int time_num{0}, time_den{0}; - qint64 start{0}; - AVCodecContext *ctx{0}; - std::thread *thd{0}; - std::atomic stop{false}; - AVFrame *frm{av_frame_alloc()}; - ConQueue pkts; - uint deLoop{0}; - ~Type() { - av_frame_free(&frm); - avcodec_free_context(&ctx); - } -}; -class AVFmt { - friend class FFPlayer; -public: - static const char Run{0}, Pause{1}, Quit{2}; - AVFmt(QByteArray url); - ~AVFmt(); - void mainRead(); - void mainViDecode(); - void mainAuDecode(); - bool isLoop{true}; -protected: - void checkAndUpd(FFPlayer *, qint64); - void playAudio(Pcm *, FFPlayer *, qint64, qint64 lmt = INT64_MAX); - void whiteAudio(Pcm *, FFPlayer *, bool, qint64 cur, qint64 lmt = INT64_MAX); - QString errStr(int err) { - if(av_strerror(err, err_str, err_size)==0) return QString::fromUtf8(err_str); - return QString::number(err); - } - - QString err; - const static int err_size{255}; - char err_str[err_size]{}; - - AVFormatContext *fmt_ctx{0}; - std::thread *read_thd{0}; - qint64 start{0}; - Type vi, au; - qint64 viLmt{0}; - - SwsContext *sws_ctx{0}; - SwrContext *swr_ctx{0}; - AVChannelLayout out_ch_layout; - int sample_rate{0}, pcm_sample_size{0}; - QAudioSink *sink{0}; - QIODevice *sinkWriter{0}; - int buf_size{0}; - - ConQueue acts; - AVPacket *packet{av_packet_alloc()}; - ConQueue vi_frms; - ConQueue au_frms; - qint64 start_epoch{0}; - uint playLoop{0}; -}; - -class FFPlayer : public QObject { - friend class AVFmt; - Q_OBJECT -public: - static const char Playing{0}, Paused{1}, Closed{2}; - - explicit FFPlayer(); - ~FFPlayer(); - - inline void open(QByteArray url) { - status = Paused; - emit emOpen(url); - } - inline void close() {emit emClose();} - inline void play() {emit emPlay();} - inline void pause() {emit emPause();} - inline void stop() {emit emStop();} - inline void setVol(qreal vol) {emit emVol(vol);} - inline void quit() {emit emQuit();} - - std::atomic status{Closed}; - QImage img; - qint64 dur{0}; - int viSize{0}, auSize{0}; - qint64 viCurTime{0}, auCurTime{0}; -public slots: - void updFrame(); -signals: - void emOpen(QByteArray url); - void emClose(); - void emPlay(); - void emPause(); - void emStop(); - void emVol(qreal vol); - void emUpd(QImage); - void emError(QString err); - void emQuit(); -protected slots: - void onOpen(QByteArray url); - void onClose(); - void onPlay(); - void onPause(); - void onStop(); - void onVol(qreal vol); - void onQuit(); -protected: - void timerEvent(QTimerEvent *event) override; - void startAudioDaemon() { - if(audioDaemonTimerId==0 && ! ctx->au.isNull()) audioDaemonTimerId = startTimer(20); - } - QThread *thread; - AVFmt *ctx{0}; - qint64 last_epoch{0}; - int audioDaemonTimerId{0}; - bool hasImg{false}; - qreal mVol{1.0}; -}; - -#endif // FFPLAYER_H +#ifndef FFPLAYER_H +#define FFPLAYER_H + +#include +#include +#include +#if(QT_VERSION_MAJOR > 5) + #include +#else + #include + typedef QAudioOutput QAudioSink; + typedef QAudioDeviceInfo QAudioDevice; +#endif +extern "C"{ +#include +#include +#include +#include +} + +template +class Queue { +public: + virtual ~Queue() { + delAll(); + } + void add(T *node) { + if(node==nullptr) { + throw std::invalid_argument("node is null"); + return; + } + if(last!=nullptr) last->next = node; + else first = node; + last = node; + size++; + } + void remove() { + if(first==nullptr) return; + if(first==last) first = last = nullptr; + else first = first->next; + size--; + } + T *poll() { + auto node = first; + remove(); + return node; + } + T *delGetNext() { + delete poll(); + return first; + } + T *removeGetNext() { + remove(); + return first; + } + void delAll() { + while(first!=nullptr) delete poll(); + } + + T *volatile first{0}; + T *volatile last{0}; + volatile int size{0}; +}; + +template +class ConQueue : public Queue { +public: + virtual ~ConQueue() { + std::lock_guard lock(mtx); + this->delAll(); + } + void lockAddNtf(T *node) { + { + std::lock_guard lock(mtx); + this->add(node); + } + cv.notify_one(); + } + void lockRemove() { + std::lock_guard lock(mtx); + this->remove(); + } + T *lockPoll() { + std::lock_guard lock(mtx); + return this->poll(); + } + T *lockGet() { + std::lock_guard lock(mtx); + return this->first; + } + T *lockDelGetNext() { + std::lock_guard lock(mtx); + return this->delGetNext(); + } + T *lockRemoveGetNext() { + std::lock_guard lock(mtx); + return this->removeGetNext(); + } + void lockDelAll() { + std::lock_guard lock(mtx); + this->delAll(); + } + + T *take(int ms = 0) { + std::unique_lock lock(mtx); + if(ms==0) while(this->first==nullptr) cv.wait(lock); + else if(this->first==nullptr) cv.wait_for(lock, std::chrono::milliseconds(ms)); + return this->poll(); + } + std::mutex mtx; + std::condition_variable cv; +}; +struct Act { + qint64 arg; + Act *next; + char act; +}; +struct Packet { + AVPacket *pkt; + Packet *next; + uchar act; + ~Packet() {av_packet_free(&pkt);} +}; +struct Img { + QImage img; + qint64 st; + qint64 et; + uint loop; + Img *next; +}; +struct Pcm { + uint8_t *data; + int size; + qint64 st; + qint64 et; + uint loop; + Pcm *next; + ~Pcm() {if(data!=nullptr) delete [] data;} +}; +class Type { +public: + inline bool isNull(){return idx <= -1;} + int idx{-1}; + int time_num{0}, time_den{0}; + qint64 start{0}; + AVCodecContext *ctx{0}; + std::thread *thd{0}; + std::atomic stop{false}; + AVFrame *frm{av_frame_alloc()}; + ConQueue pkts; + uint deLoop{0}; + ~Type() { + av_frame_free(&frm); + avcodec_free_context(&ctx); + } +}; +class AVFmt { + friend class FFPlayer; +public: + static const char Run{0}, Pause{1}, Quit{2}; + AVFmt(QByteArray url); + ~AVFmt(); + void mainRead(); + void mainViDecode(); + void mainAuDecode(); + bool isLoop{true}; +protected: + void checkAndUpd(FFPlayer *, qint64); + void playAudio(Pcm *, FFPlayer *, qint64, qint64 lmt = INT64_MAX); + void whiteAudio(Pcm *, FFPlayer *, bool, qint64 cur, qint64 lmt = INT64_MAX); + QString errStr(int err) { + if(av_strerror(err, errbuf, AV_ERROR_MAX_STRING_SIZE)==0) return QString::fromUtf8(errbuf); + return QString::number(err); + } + + QString err; + char errbuf[AV_ERROR_MAX_STRING_SIZE]{}; + + AVFormatContext *fmt_ctx{0}; + std::thread *read_thd{0}; + qint64 start{0}; + Type vi, au; + qint64 frmDur{0}; + qint64 viLmt{0}; + + SwsContext *sws_ctx{0}; + int dstStride[4]{0}; + SwrContext *swr_ctx{0}; + AVChannelLayout out_ch_layout + #if(QT_VERSION_MAJOR > 5) + AV_CHANNEL_LAYOUT_STEREO + #endif + ; + int sample_rate{0}, pcm_sample_size{0}; + QAudioSink *sink{0}; + QIODevice *sinkWriter{0}; + int buf_size{0}; + + ConQueue acts; + AVPacket *packet{av_packet_alloc()}; + ConQueue vi_frms; + ConQueue au_frms; + qint64 start_epoch{0}; + uint playLoop{0}; +}; + +class FFPlayer : public QObject { + friend class AVFmt; + Q_OBJECT +public: + static const char Playing{0}, Paused{1}, Closed{2}; + + explicit FFPlayer(); + ~FFPlayer(); + + inline void open(QByteArray url) { + status = Paused; + emit emOpen(url); + } + inline void close() {emit emClose();} + inline void play() {emit emPlay();} + inline void pause() {emit emPause();} + inline void stop() {emit emStop();} + inline void setVol(qreal vol) {emit emVol(vol);} + inline void quit() {emit emQuit();} + + std::atomic status{Closed}; + QImage img; + qint64 dur{0}; + int viSize{0}, auSize{0}; + qint64 viCurTime{0}, auCurTime{0}; +public slots: + void updFrame(); +signals: + void emOpen(QByteArray url); + void emClose(); + void emPlay(); + void emPause(); + void emStop(); + void emVol(qreal vol); + void emUpd(QImage); + void emError(QString err); + void emQuit(); +protected slots: + void onOpen(QByteArray url); + void onClose(); + void onPlay(); + void onPause(); + void onStop(); + void onVol(qreal vol); + void onQuit(); +protected: + void timerEvent(QTimerEvent *event) override; + void startAudioDaemon() { + if(audioDaemonTimerId==0 && ! ctx->au.isNull()) audioDaemonTimerId = startTimer(20); + } + QThread *thread; + AVFmt *ctx{0}; + qint64 last_epoch{0}; + int audioDaemonTimerId{0}; + bool hasImg{false}; + qreal mVol{1.0}; +}; + +#endif // FFPLAYER_H diff --git a/LedOK/globaldefine.cpp b/LedOK/globaldefine.cpp index 8fe70b3..b919666 100644 --- a/LedOK/globaldefine.cpp +++ b/LedOK/globaldefine.cpp @@ -1,169 +1,160 @@ -#include -#include -#include -#include -#include -#include -#include - -bool gVideoCompress = true; -bool gVideoTranscoding = true; -bool gTextAntialiasing = false; -bool gShowLoraScreen = false; -bool gWidthSplit = false; - -QNetworkRequest netReq(const QString &url, int timeout, const QVariant &contentType) { - QNetworkRequest request{url}; - request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); - request.setTransferTimeout(timeout); - if(contentType.isValid()) request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); - return request; -} -QString parseReplyJson(QNetworkReply *reply, QJsonDocument *outJson) { - reply->deleteLater(); - auto error = reply->error(); - if(error != QNetworkReply::NoError) { - auto errStr = reply->errorString(); - if(error!=QNetworkReply::InternalServerError || ! errStr.endsWith("replied: Unknown")) { - if(error==QNetworkReply::OperationCanceledError) { - error = QNetworkReply::TimeoutError; - errStr = QCoreApplication::translate("Def","Connection Timeout"); - } - return QString(QMetaEnum::fromType().valueToKey(error))+" ("+QString::number(error)+") "+errStr+"\n"+QCoreApplication::translate("Def","Device replied")+":\n"+reply->readAll(); - } - } - auto status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if(status != 200) return QString::number(status)+" "+reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()+"\n"+QCoreApplication::translate("Def","Device replied")+":\n"+reply->readAll(); - if(outJson) { - auto data = reply->readAll(); - QJsonParseError jsonErr; - *outJson = QJsonDocument::fromJson(data, &jsonErr); - if(jsonErr.error != QJsonParseError::NoError) return "Json error: "+jsonErr.errorString()+"\n"+QCoreApplication::translate("Def","Device replied")+":\n"+data; - } - return ""; -} -QString checkReplyForJson(QNetworkReply *reply, QJsonDocument *doc, QByteArray *outData) { - reply->deleteLater(); - auto error = reply->error(); - auto data = reply->readAll(); - if(outData) *outData = data; - if(error != QNetworkReply::NoError) { - auto errStr = reply->errorString(); - if(error!=QNetworkReply::InternalServerError || ! errStr.endsWith("replied: Unknown")) { - if(error==QNetworkReply::OperationCanceledError) { - error = QNetworkReply::TimeoutError; - errStr = QCoreApplication::translate("Def","Connection Timeout"); - } - return QString(QMetaEnum::fromType().valueToKey(error))+" ("+QString::number(error)+") "+errStr+"\n"+QCoreApplication::translate("Def","Device replied")+":\n"+data; - } - } - auto status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if(status != 200) return QString::number(status)+" - "+reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()+"\n"+QCoreApplication::translate("Def","Device replied")+":\n"+data; - QJsonParseError jsonErr; - QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr); - if(jsonErr.error != QJsonParseError::NoError) return "Json error: "+jsonErr.errorString()+"\n"+QCoreApplication::translate("Def","Device replied")+":\n"+data; - if(! json["success"].toBool()) return QCoreApplication::translate("Def","Fail")+". "+QCoreApplication::translate("Def","Device replied")+":\n"+data; - if(doc) doc->swap(json); - return ""; -} - -bool isTextValid(const QString &strIP){ - if(! strIP.isEmpty()) { - QRegExp rx2("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); - if (!rx2.exactMatch(strIP)) return false; - } - return true; -} -QString getRandomString(int len) { - static const char table[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - static const int tableSize = sizeof(table) - 1; - QString str; - str.resize(len); - for(int i=0; ihttpPost(strUrl, QJsonDocument(json).toJson(QJsonDocument::Compact)); -} -bool copyDir(const QString &source, const QString &destination, bool override) -{ - QDir directory(source); - if (!directory.exists()) - { - return false; - } - - - QString srcPath = QDir::toNativeSeparators(source); - if (!srcPath.endsWith(QDir::separator())) - srcPath += QDir::separator(); - QString dstPath = QDir::toNativeSeparators(destination); - if (!dstPath.endsWith(QDir::separator())) - dstPath += QDir::separator(); - - - bool error = false; - QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden); - for (QStringList::size_type i=0; i != fileNames.size(); ++i) - { - QString fileName = fileNames.at(i); - QString srcFilePath = srcPath + fileName; - QString dstFilePath = dstPath + fileName; - QFileInfo fileInfo(srcFilePath); - if (fileInfo.isFile() || fileInfo.isSymLink()) - { - if (override) - { - QFile::setPermissions(dstFilePath, QFile::WriteOwner); - } - QFile::copy(srcFilePath, dstFilePath); - } - else if (fileInfo.isDir()) - { - QDir dstDir(dstFilePath); - dstDir.mkpath(dstFilePath); - if (!copyDir(srcFilePath, dstFilePath, override)) - { - error = true; - } - } - } - - - return !error; -} -unsigned char GetCheckCodeIn8(unsigned char * pBuffer,unsigned int uiSize) { - unsigned int i=0; - unsigned char ucCheckCode=0; - for (i=0;i +#include +#include +#include +#include +#include +#include + +bool gVideoCompress = true; +bool gVideoTranscoding = true; +bool gTextAntialiasing = false; +bool gShowLoraScreen = false; +bool gWidthSplit = false; + +QNetworkRequest netReq(const QString &url, const QByteArray &contentType, int timeout) { + QNetworkRequest request{url}; + request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); + if(timeout) request.setTransferTimeout(timeout); + if(! contentType.isEmpty()) request.setRawHeader("Content-Type", contentType); + return request; +} +QString replyErr(QNetworkReply *reply) { + reply->deleteLater(); + auto error = reply->error(); + if(error != QNetworkReply::NoError) { + auto errStr = reply->errorString(); + if(error!=QNetworkReply::InternalServerError || ! errStr.endsWith("replied: Unknown")) { + if(error==QNetworkReply::OperationCanceledError) { + error = QNetworkReply::TimeoutError; + errStr = QCoreApplication::translate("Def","Connection Timeout"); + } + return QString(QMetaEnum::fromType().valueToKey(error))+" ("+QString::number(error)+") "+errStr; + } + } + auto status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if(status != 200) return QString::number(status)+" "+reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); + return ""; +} +QString checkReply(QNetworkReply *reply, QJsonDocument *outJson) { + auto err = replyErr(reply); + if(! err.isEmpty()) { + auto data = reply->readAll(); + if(! data.isEmpty()) err = err+"\n"+QCoreApplication::translate("Def","Device replied")+": "+data; + return err; + } + if(outJson) { + auto data = reply->readAll(); + QJsonParseError jsonErr; + *outJson = QJsonDocument::fromJson(data, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) return "Json error: "+jsonErr.errorString()+"\n"+QCoreApplication::translate("Def","Device replied")+": "+data; + } + return ""; +} +QString checkReplyForJson(QNetworkReply *reply, QJsonDocument *outJson, QByteArray *outData) { + auto err = replyErr(reply); + auto data = reply->readAll(); + if(outData) *outData = data; + if(! err.isEmpty()) { + if(! data.isEmpty()) err = err+"\n"+QCoreApplication::translate("Def","Device replied")+": "+data; + return err; + } + QJsonParseError jsonErr; + QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) return "Json error: "+jsonErr.errorString()+"\n"+QCoreApplication::translate("Def","Device replied")+": "+data; + if(! json["success"].toBool()) return QCoreApplication::translate("Def","Fail")+". "+QCoreApplication::translate("Def","Device replied")+": "+data; + if(outJson) outJson->swap(json); + return ""; +} + +bool isTextValid(const QString &strIP){ + if(! strIP.isEmpty()) { + QRegExp rx2("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); + if (!rx2.exactMatch(strIP)) return false; + } + return true; +} +QString getRandomString(int len) { + static const char table[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + static const int tableSize = sizeof(table) - 1; + QString str; + str.resize(len); + for(int i=0; ihttpPost(strUrl, QJsonDocument(json).toJson(QJsonDocument::Compact)); +} +bool copyDir(const QString &source, const QString &destination, bool override) +{ + QDir directory(source); + if (!directory.exists()) + { + return false; + } + + + QString srcPath = QDir::toNativeSeparators(source); + if (!srcPath.endsWith(QDir::separator())) + srcPath += QDir::separator(); + QString dstPath = QDir::toNativeSeparators(destination); + if (!dstPath.endsWith(QDir::separator())) + dstPath += QDir::separator(); + + + bool error = false; + QStringList fileNames = directory.entryList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden); + for (QStringList::size_type i=0; i != fileNames.size(); ++i) + { + QString fileName = fileNames.at(i); + QString srcFilePath = srcPath + fileName; + QString dstFilePath = dstPath + fileName; + QFileInfo fileInfo(srcFilePath); + if (fileInfo.isFile() || fileInfo.isSymLink()) + { + if (override) + { + QFile::setPermissions(dstFilePath, QFile::WriteOwner); + } + QFile::copy(srcFilePath, dstFilePath); + } + else if (fileInfo.isDir()) + { + QDir dstDir(dstFilePath); + dstDir.mkpath(dstFilePath); + if (!copyDir(srcFilePath, dstFilePath, override)) + { + error = true; + } + } + } + + + return !error; +} +unsigned char GetCheckCodeIn8(unsigned char * pBuffer,unsigned int uiSize) { + unsigned int i=0; + unsigned char ucCheckCode=0; + for (i=0;i -#define MACRO_FENGEFU "/" -#include -#include -#include -#include - -enum { - MainPage_DeviceManager = 0, - MainPage_ProgManager, - MainPage_Setting, - MainPage_LoraScreen, - MainPage_End, -}; - -enum { - - ENUM_IMPORT_DLG=1, - ENUM_EXPORT_DLG=2, - ENUM_DELETE_DLG=3, - ENUM_SELECT_NETWORK=5, -}; - - -#define STREAM_SYNC_HEAD_NUM 3 -#define STREAM_SYNC_HEAD 0x7e -typedef struct _SYSTIMER -{ - int y; //获取年份 - int m; //获取当前月份 - int d; //获得几号 - int h; //获取当前为几时 - int mm; //获取分钟 - int s; //获取秒 - int w; //获取星期几,注意1为星期天,7为星期六 -}SYSTIMER,*P_SYSTIMER; - -typedef struct _RESTORE_IP -{ - char cNewIp[20]; - char cMask[20]; - char cGateway[20]; - char cDns[20]; -// char cLocalIp[20]; - -}RESTORE_IP,*P_RESTORE_IP; -typedef struct _STREAM_PACKET -{ - unsigned char SyncHead[STREAM_SYNC_HEAD_NUM]; - unsigned char ucCommType; - char ucSerialCode[20]; - unsigned int iLength; - char pDataBuffer[2049]; -}STREAM_PACKET,* P_STREAM_PACKET; -enum _NET_COMMU_TYPE -{ - COMMAND_SAVE_ADVANCE_PARAM_NOT_RESET=0x40, - COMMAND_ONLY_RESET_CARD_IP=0X43, - COMMAND_SET_M31_DOUBLE_HUB=0X44, - COMMAND_CONNECT_COLSE =0x7A, - COMMAND_UPGRADE = 0x80, - COMMAND_SIGNLE_FILE_UPGRADE , - COMMAND_LOOPCHECK , - COMMAND_VERIFY_CLOCK , - COMMAND_SCREEN_OPERATOR,//0x84 - COMMAND_SET_SERIAL_NUM, - NET_COMMU_TYPE_PLAY_IN_LINE , // 网络同步在线播放. - NET_COMMU_TYPE_PREVIEW_IN_LINE, // 网络在线预览. - NET_COMMU_TYPE_UPGRADE_SYSTEM, // 系统升级. - NET_COMMU_TYPE_RECOVER_SYSTEM, // 系统还原到上一次正确的启动. - SCREEN_OPERATOR_COMM_PARAMS_SAVE, // 参数保存. - NET_COMMU_TYPE_COMM_EXIT,//普通退出,不重启 - NET_COMMU_TYPE_AUDIO_PLAY,//0X8C - NET_COMMU_TYPE_IO, - NET_COMMU_TYPE_IO_CHECK, - NET_COMMU_TYPE_LIMITE_TIME, - NET_COMMU_TYPE_SYSTEM_BROADCAST,//0X90 - NET_COMMU_TYPE_REALTIME_INSERT_PLAY, - //NET_COMMU_TYPE_SHANSUO_INSERT_PLAY, - NET_COMMU_TYPE_MODIFY_SERIAL_ID, - NET_COMMU_TYPE_KERNEL_UPGRADE_SYSTEM, - NET_COMMU_TYPE_UPGRADE_FINISHED_EXIT, - NET_COMMU_TYPE_REAL_TIME_INSERT_PLAY_WITH_LIST_EXIT, - NET_COMMU_TYPE_ZNSZ,// 智能设置命令. - NET_COMMU_TYPE_SELECT_PROGRAM_PLAY,// 选节目播放.0x97 - NET_COMMU_TYPE_SELECT_MULI_PROGRAM_PLAY,//98选播多个节目 - NET_COMMU_TYPE_GET_PROGRAM_NAME,//99获取所有节目的名称 - NET_COMMU_TYPE_GET_CUR_PLAY_STATUS,//9a查询当前播放的详细信息 - NET_COMMU_TYPE_POWER_PANEL_ON_OR_OFF,//9b开关大屏幕 - NET_COMMU_TYPE_ADJUST_BRIGHTNESS,//9c调节亮度 - NET_COMMU_TYPE_GET_SYSTEM_STATUS,//9d获取系统状态 - NET_COMMU_TYPE_VERIFY_SIGN,//校验签名9e - NET_COMMU_TYPE_SET_WEB_SERVER_PARAM,//配置web服务器参数 - NET_COMMU_TYPE_GET_WEB_SERVER_PARAM,//a0 - NET_COMMU_TYPE_SET_WIFI_PARAM,//a1配置wifi参数 - NET_COMMU_TYPE_GET_WIFI_PARAM,//a2获取wifi参数 - NET_COMMU_TYPE_SCAN_AP_WIFI_PARAM,//a3获取ap热点的名称 - NET_COMMU_TYPE_GET_ANDROID=0xa4, - NET_COMMU_TYPE_INSTALL_APK=0xa5, - NET_COMMU_TYPE_UNINSTALL_APK=0xa6, - NET_COMMU_TYPE_SET_DNS=0xa7, - NET_COMMU_TYPE_GET_DNS=0xa8, - NET_COMMU_TYPE_SET_PROXY=0xa9, - NET_COMMU_TYPE_GET_PROXY=0xaa, - NET_COMMU_TYPE_SET_ANDROID_COMMUNICATION=0xab, - NET_COMMU_TYPE_GET_ANDROID_COMMUNICATION=0xac, - NET_COMMU_TYPE_GET_SIM_STATUS=0xad, - NET_COMMU_TYPE_GET_APN_PARAM=0xae, - NET_COMMU_TYPE_GET_APK_VERSION=0xaf, - NET_COMMU_TYPE_SET_REALTIME_PARAM=0xb0, - NET_COMMU_TYPE_GET_REALTIME_PARAM=0xb1, - NET_COMMU_TYPE_SET_REALTIME_LINSTEN_PARAM=0xb2, - NET_COMMU_TYPE_GET_REALTIME_LINSTEN_PARAM=0xb3, - NET_COMMU_TYPE_SET_HUAWEI_4G=0xB4, - NET_COMMU_TYPE_GET_HUAWEI_4G=0xB5, - NET_COMMU_TYPE_CLEAR_ANDROID_PROGRAM=0xB6, - NET_COMMU_TYPE_SET_AP_PARAM=0xB7, - NET_COMMU_TYPE_GET_AP_PARAM=0xB8, - GET_REALY_RESOLUTION=0xB9, - GET_REALY_ANDROID_FIRMWARE_INFO=0xBA, - NET_COMMU_TYPE_NUM, - - COMMAND_UPGRADE_ANSWER =0xC0, - COMMAND_SIGNLE_FILE_UPGRADE_ANSWER , - COMMAND_LOOPCHECK_ANSWER , - COMMAND_VERIFY_CLOCK_ANSWER , - COMMAND_SCREEN_OPERATOR_ANSWER, - COMMAND_SET_SERIAL_NUM_ANSWER, - NET_COMMU_TYPE_PLAY_IN_LINE_ANSWER , // 网络同步在线播放. - NET_COMMU_TYPE_PREVIEW_IN_LINE_ANSWER, // 网络在线预览. - NET_COMMU_TYPE_UPGRADE_SYSTEM_ANSWER, // 系统升级. - NET_COMMU_TYPE_RECOVER_SYSTEM_ANSWER, // 系统还原到上一次正确的启动. - SCREEN_OPERATOR_COMM_PARAMS_SAVE_ANSWER, - NET_COMMU_TYPE_COMM_EXIT_ANSWER, - NET_COMMU_TYPE_AUDIO_PLAY_ANSWER,//0XcC - NET_COMMU_TYPE_IO_ANSWER, - NET_COMMU_TYPE_IO_CHECK_ANSWER, - NET_COMMU_TYPE_LIMITE_TIME_ANSWER, - -//// - NET_COMMU_TYPE_SYSTEM_BROADCAST_ANSWER, - NET_COMMU_TYPE_REALTIME_INSERT_PLAY_ANSWER, - NET_COMMU_TYPE_REALTIME_INSERT_PLAY_WITH_GLINT_ANSWER , //带闪烁功能的实时插播 - - NET_COMMU_TYPE_KERNEL_UPGRADE_SYSTEM_ANSWER, - NET_COMMU_TYPE_UPGRADE_FINISHED_EXIT_ANSWER,//0xd4 - NET_COMMU_TYPE_REAL_TIME_INSERT_PLAY_WITH_LIST_EXIT_ANSWER, - NET_COMMU_TYPE_ZNSZ_ANSWER,// 智能设置命令. - NET_COMMU_TYPE_SELECT_PROGRAM_PLAY_ANSWER,//0x97 选节目播放. - NET_COMMU_TYPE_SELECT_MULI_PROGRAM_PLAY_ANSWER, - NET_COMMU_TYPE_GET_PROGRAM_NAME_ANSWER, - NET_COMMU_TYPE_GET_CUR_PLAY_STATUS_ANSWER, - NET_COMMU_TYPE_POWER_PANEL_ON_OR_OFF_ANSWER, - NET_COMMU_TYPE_ADJUST_BRIGHTNESS_ANSWER, - NET_COMMU_TYPE_GET_SYSTEM_STATUS_ANSWER,//获取系统状态 - NET_COMMU_TYPE_NUM_ANSWER, - - - COMMAND_CONNECT_COLSE_ANSWER - -}; -extern bool gVideoCompress; -extern bool gVideoTranscoding; -extern bool gTextAntialiasing; -extern bool gShowLoraScreen; -extern bool gWidthSplit; - -extern bool isTextValid(const QString &strIP); -extern quint64 dirFileSize(const QString &path); -extern bool isFileExist(QString fullFileName); -extern QString getRandomString(int length); -extern void HttpPostByTypeJsonObject(HpptClient *pHpptClient, QString strUrl,QJsonObject json); -extern bool copyDir(const QString &source, const QString &destination, bool override); -extern unsigned char GetCheckCodeIn8(unsigned char * pBuffer,unsigned int uiSize); - -enum _ENUM_CONTRL_WIDGET { - Setting_Bright=0, - Setting_PowerControl, - Setting_NetCfg, - Setting_VerifyClock, - Setting_Encrypt, - Setting_HDMI, - Setting_Volume, - Setting_Advanced, - Setting_Test, - Setting_End, -}; - -QNetworkRequest netReq(const QString &url, int = QNetworkRequest::DefaultTransferTimeoutConstant, const QVariant &contentType = QVariant::Invalid); -inline QNetworkRequest reqForJson(const QString &url) { - return netReq(url, 30000, "application/json"); -} -QString parseReplyJson(QNetworkReply *, QJsonDocument * = 0); -QString checkReplyForJson(QNetworkReply *, QJsonDocument * = 0, QByteArray * = 0); - -#define Def_CtrlReqPre \ - waitingDlg->show();\ - auto card = gSelCards->at(0);\ - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - -#define Def_CtrlSetReqAfter \ - QString err = checkReplyForJson(reply);\ - if(! err.isEmpty()) {\ - waitingDlg->close();\ - QMessageBox::critical(gMainWin, tr("Error"), err);\ - return;\ - }\ - waitingDlg->success(); - -#define Def_CtrlSingleGetReply \ - QJsonDocument json;\ - QString err = checkReplyForJson(reply, &json);\ - if(! err.isEmpty()) {\ - waitingDlg->close();\ - QMessageBox::critical(gMainWin, tr("Error"), err);\ - return;\ - } - -#define Def_CtrlSetMulti(tip) \ - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));\ - connect(reply, &QNetworkReply::finished, this, [reply, card] {\ - QString err = checkReplyForJson(reply);\ - gFdResInfo->append(card->m_strCardId+" "+tip+" "+(err.isEmpty()?QCoreApplication::translate("Def","Success"):err));\ - }); - -#define DDDef_HttpCheckJsonErr\ - auto error = reply->error();\ - if(error != QNetworkReply::NoError) {\ - auto errStr = reply->errorString();\ - if(error==QNetworkReply::OperationCanceledError) {\ - error = QNetworkReply::TimeoutError;\ - errStr = QCoreApplication::translate("Def","Connection Timeout");\ - }\ - if(waitingDlg) waitingDlg->close();\ - QMessageBox::critical(gMainWin, QCoreApplication::translate("Def","Error"), QString::number(error)+" "+QMetaEnum::fromType().valueToKey(error)+" "+errStr);\ - return;\ - }\ - auto status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\ - if(status != 200) {\ - if(waitingDlg) waitingDlg->close();\ - QMessageBox::critical(gMainWin, QCoreApplication::translate("Def","Error"), QString::number(status)+" "+reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());\ - return;\ - }\ - auto resp = reply->readAll();\ - QJsonParseError jsonErr;\ - QJsonDocument json = QJsonDocument::fromJson(resp, &jsonErr);\ - if(jsonErr.error != QJsonParseError::NoError) {\ - if(waitingDlg) waitingDlg->close();\ - QMessageBox::critical(gMainWin, QCoreApplication::translate("Def","Error"), "JsonParseError "+jsonErr.errorString());\ - return;\ - }\ - if(! json["success"].toBool()) {\ - if(waitingDlg) waitingDlg->close();\ - QMessageBox::warning(gMainWin, QCoreApplication::translate("Def","Tip Info"), QCoreApplication::translate("Def","Fail"));\ - return;\ - } - - -#define CHECK_CARD_SELECTED \ - if(m_pLedlist!=nullptr) {\ - if(m_pLedlist->count()==0 || (m_pLedlist->count()==1 && m_pLedCard==nullptr)) {\ - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));\ - return;\ - }\ - } - -#define MACRO_DEFINE_TIPDLG_FUCN(TIP,SUCCESS,FAILED) \ - if(m_pLedlist!=nullptr) {\ - if(m_pLedlist->count()<=1) {\ - if(m_pLedCard!=nullptr) {\ - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);\ - if(m_PostingDlg==nullptr) {\ - m_PostingDlg = new LoEmptyDialog(this);\ - connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg()));\ - connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock()));\ - m_PostingDlg->lock(TIP,SUCCESS,FAILED);\ - m_pGetAskTimer->start(5000);\ - m_PostingDlg->exec();\ - }\ - }\ - } else emit sigSend(json,TIP);\ - } - -#define MACRO_DEFINE_TIPDLG_ALL_FUCN(READBACK,SUCCESS,FAILED) \ - if(m_pLedCard!=nullptr)\ - {\ - if(m_PostingDlg==nullptr)\ - {\ - m_PostingDlg = new LoEmptyDialog(this);\ - connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg()));\ - connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock()));\ - m_PostingDlg->lock(READBACK+" "+m_pLedCard->m_strCardId,SUCCESS,FAILED);\ - m_pGetAskTimer->start(5000);\ - m_PostingDlg->exec();\ - }\ - }\ - - -#define MARCO_DEFINE_CONTROL_FUNC2(PARENT,PARENT1) \ - pHpptClient = new HpptClient(this);\ - connect(pHpptClient,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponse(QString , QString , QByteArray)));\ - pHpptClientAll = new HpptClient(this);\ - connect(pHpptClientAll,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponseAll(QString , QString , QByteArray)));\ - m_pGetAskTimer=new QTimer(this);\ - connect(PARENT1,SIGNAL(sigSwitchIndexChanged(int)),this,SLOT(OnControlTypeSwitchIndexChanged(int)));\ - connect(PARENT,SIGNAL(sigSelectedDeviceList(QList *)),this,SLOT(onSelectedDeviceList(QList *)));\ - connect(this,SIGNAL(sigSend(QJsonObject &,QString)),PARENT,SLOT(OnControlSendJson(QJsonObject &,QString)));\ - onSelectedDeviceList(list); - -#define MACRO_ASKTIME_STOP \ -if(m_pGetAskTimer && m_pGetAskTimer->isActive()) m_pGetAskTimer->stop(); - -#define MACRO_POSTING_DLG_UNLOCK \ -if(m_PostingDlg && m_PostingDlg->getLockStatus()) m_PostingDlg->unlock(); - -#define MACRO_DEFINE_CONTROL_FUNC3 \ - if(m_pLedlist!=nullptr)\ - {\ - if(m_pLedlist->count()==1)\ - {\ - m_pLedCard=list->at(0);\ - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";\ - if(m_oldLedlist!=m_pLedCard&&m_bSelected==true)\ - {\ - m_oldLedlist=m_pLedCard;\ - onReadbackAllThisPage();\ - }\ - }\ - } - -typedef struct _ST_ANSY_PROGRAM_PACKET -{ - unsigned char SyncHead[3]; - unsigned char ucCommType; - int iBaoLiu; - unsigned int iLength; - unsigned char pDataBuffer[20]; -}ST_ANSY_PROGRAM_PACKET,*P_ST_ANSY_PROGRAM_PACKET; - -#endif // GLOBALDEFINE_H +#ifndef GLOBALDEFINE_H +#define GLOBALDEFINE_H +#include +#include +#include +#include +#include + +enum { + MainPage_DeviceManager = 0, + MainPage_ProgManager, + MainPage_Setting, + MainPage_LoraScreen, + MainPage_End, +}; + +struct RESTORE_IP { + char cNewIp[20]; + char cMask[20]; + char cGateway[20]; + char cDns[20]; +}; +struct Packet { + unsigned char SyncHead[3]; + unsigned char ucCommType; + char serialCode[20]; + unsigned int iLength; +}; +struct STREAM_PACKET { + unsigned char SyncHead[3]; + unsigned char ucCommType; + char ucSerialCode[20]; + unsigned int iLength; + char pDataBuffer[2049]; +}; +struct ST_ANSY_PROGRAM_PACKET { + unsigned char SyncHead[3]; + unsigned char ucCommType; + int iBaoLiu; + unsigned int iLength; + unsigned char pDataBuffer[20]; +}; + +enum _NET_COMMU_TYPE { + COMMAND_SAVE_ADVANCE_PARAM_NOT_RESET=0x40, + COMMAND_ONLY_RESET_CARD_IP=0X43, + COMMAND_SET_M31_DOUBLE_HUB=0X44, + COMMAND_CONNECT_COLSE =0x7A, + COMMAND_UPGRADE = 0x80, + COMMAND_SIGNLE_FILE_UPGRADE , + COMMAND_LOOPCHECK , + COMMAND_VERIFY_CLOCK , + COMMAND_SCREEN_OPERATOR,//0x84 + COMMAND_SET_SERIAL_NUM, + NET_COMMU_TYPE_PLAY_IN_LINE , // 网络同步在线播放. + NET_COMMU_TYPE_PREVIEW_IN_LINE, // 网络在线预览. + NET_COMMU_TYPE_UPGRADE_SYSTEM, // 系统升级. + NET_COMMU_TYPE_RECOVER_SYSTEM, // 系统还原到上一次正确的启动. + SCREEN_OPERATOR_COMM_PARAMS_SAVE, // 参数保存. + NET_COMMU_TYPE_COMM_EXIT,//普通退出,不重启 + NET_COMMU_TYPE_AUDIO_PLAY,//0X8C + NET_COMMU_TYPE_IO, + NET_COMMU_TYPE_IO_CHECK, + NET_COMMU_TYPE_LIMITE_TIME, + NET_COMMU_TYPE_SYSTEM_BROADCAST,//0X90 + NET_COMMU_TYPE_REALTIME_INSERT_PLAY, + + NET_COMMU_TYPE_MODIFY_SERIAL_ID, + NET_COMMU_TYPE_KERNEL_UPGRADE_SYSTEM, + NET_COMMU_TYPE_UPGRADE_FINISHED_EXIT, + NET_COMMU_TYPE_REAL_TIME_INSERT_PLAY_WITH_LIST_EXIT, + NET_COMMU_TYPE_ZNSZ,// 智能设置命令. + NET_COMMU_TYPE_SELECT_PROGRAM_PLAY,// 选节目播放.0x97 + NET_COMMU_TYPE_SELECT_MULI_PROGRAM_PLAY,//98选播多个节目 + NET_COMMU_TYPE_GET_PROGRAM_NAME,//99获取所有节目的名称 + NET_COMMU_TYPE_GET_CUR_PLAY_STATUS,//9a查询当前播放的详细信息 + NET_COMMU_TYPE_POWER_PANEL_ON_OR_OFF,//9b开关大屏幕 + NET_COMMU_TYPE_ADJUST_BRIGHTNESS,//9c调节亮度 + NET_COMMU_TYPE_GET_SYSTEM_STATUS,//9d获取系统状态 + NET_COMMU_TYPE_VERIFY_SIGN,//校验签名9e + NET_COMMU_TYPE_SET_WEB_SERVER_PARAM,//配置web服务器参数 + NET_COMMU_TYPE_GET_WEB_SERVER_PARAM,//a0 + NET_COMMU_TYPE_SET_WIFI_PARAM,//a1配置wifi参数 + NET_COMMU_TYPE_GET_WIFI_PARAM,//a2获取wifi参数 + NET_COMMU_TYPE_SCAN_AP_WIFI_PARAM,//a3获取ap热点的名称 + NET_COMMU_TYPE_GET_ANDROID=0xa4, + NET_COMMU_TYPE_INSTALL_APK=0xa5, + NET_COMMU_TYPE_UNINSTALL_APK=0xa6, + NET_COMMU_TYPE_SET_DNS=0xa7, + NET_COMMU_TYPE_GET_DNS=0xa8, + NET_COMMU_TYPE_SET_PROXY=0xa9, + NET_COMMU_TYPE_GET_PROXY=0xaa, + NET_COMMU_TYPE_SET_ANDROID_COMMUNICATION=0xab, + NET_COMMU_TYPE_GET_ANDROID_COMMUNICATION=0xac, + NET_COMMU_TYPE_GET_SIM_STATUS=0xad, + NET_COMMU_TYPE_GET_APN_PARAM=0xae, + NET_COMMU_TYPE_GET_APK_VERSION=0xaf, + NET_COMMU_TYPE_SET_REALTIME_PARAM=0xb0, + NET_COMMU_TYPE_GET_REALTIME_PARAM=0xb1, + NET_COMMU_TYPE_SET_REALTIME_LINSTEN_PARAM=0xb2, + NET_COMMU_TYPE_GET_REALTIME_LINSTEN_PARAM=0xb3, + NET_COMMU_TYPE_SET_HUAWEI_4G=0xB4, + NET_COMMU_TYPE_GET_HUAWEI_4G=0xB5, + NET_COMMU_TYPE_CLEAR_ANDROID_PROGRAM=0xB6, + NET_COMMU_TYPE_SET_AP_PARAM=0xB7, + NET_COMMU_TYPE_GET_AP_PARAM=0xB8, + GET_REALY_RESOLUTION=0xB9, + GET_REALY_ANDROID_FIRMWARE_INFO=0xBA, + NET_COMMU_TYPE_NUM, + + COMMAND_UPGRADE_ANSWER =0xC0, + COMMAND_SIGNLE_FILE_UPGRADE_ANSWER , + COMMAND_LOOPCHECK_ANSWER , + COMMAND_VERIFY_CLOCK_ANSWER , + COMMAND_SCREEN_OPERATOR_ANSWER, + COMMAND_SET_SERIAL_NUM_ANSWER, + NET_COMMU_TYPE_PLAY_IN_LINE_ANSWER , // 网络同步在线播放. + NET_COMMU_TYPE_PREVIEW_IN_LINE_ANSWER, // 网络在线预览. + NET_COMMU_TYPE_UPGRADE_SYSTEM_ANSWER, // 系统升级. + NET_COMMU_TYPE_RECOVER_SYSTEM_ANSWER, // 系统还原到上一次正确的启动. + SCREEN_OPERATOR_COMM_PARAMS_SAVE_ANSWER, + NET_COMMU_TYPE_COMM_EXIT_ANSWER, + NET_COMMU_TYPE_AUDIO_PLAY_ANSWER,//0XcC + NET_COMMU_TYPE_IO_ANSWER, + NET_COMMU_TYPE_IO_CHECK_ANSWER, + NET_COMMU_TYPE_LIMITE_TIME_ANSWER, + + NET_COMMU_TYPE_SYSTEM_BROADCAST_ANSWER, + NET_COMMU_TYPE_REALTIME_INSERT_PLAY_ANSWER, + NET_COMMU_TYPE_REALTIME_INSERT_PLAY_WITH_GLINT_ANSWER , //带闪烁功能的实时插播 + + NET_COMMU_TYPE_KERNEL_UPGRADE_SYSTEM_ANSWER, + NET_COMMU_TYPE_UPGRADE_FINISHED_EXIT_ANSWER,//0xd4 + NET_COMMU_TYPE_REAL_TIME_INSERT_PLAY_WITH_LIST_EXIT_ANSWER, + NET_COMMU_TYPE_ZNSZ_ANSWER,// 智能设置命令. + NET_COMMU_TYPE_SELECT_PROGRAM_PLAY_ANSWER,//0x97 选节目播放. + NET_COMMU_TYPE_SELECT_MULI_PROGRAM_PLAY_ANSWER, + NET_COMMU_TYPE_GET_PROGRAM_NAME_ANSWER, + NET_COMMU_TYPE_GET_CUR_PLAY_STATUS_ANSWER, + NET_COMMU_TYPE_POWER_PANEL_ON_OR_OFF_ANSWER, + NET_COMMU_TYPE_ADJUST_BRIGHTNESS_ANSWER, + NET_COMMU_TYPE_GET_SYSTEM_STATUS_ANSWER,//获取系统状态 + NET_COMMU_TYPE_NUM_ANSWER, + + COMMAND_CONNECT_COLSE_ANSWER +}; + +extern bool gVideoCompress; +extern bool gVideoTranscoding; +extern bool gTextAntialiasing; +extern bool gShowLoraScreen; +extern bool gWidthSplit; + +extern bool isTextValid(const QString &strIP); +extern quint64 dirFileSize(const QString &path); +extern bool isFileExist(QString fullFileName); +extern QString getRandomString(int length); +extern void HttpPostByTypeJsonObject(HpptClient *pHpptClient, QString strUrl,QJsonObject json); +extern bool copyDir(const QString &source, const QString &destination, bool override); +extern unsigned char GetCheckCodeIn8(unsigned char * pBuffer,unsigned int uiSize); + +enum _ENUM_CONTRL_WIDGET { + Setting_Bright=0, + Setting_PowerControl, + Setting_NetCfg, + Setting_VerifyClock, + Setting_Encrypt, + Setting_HDMI, + Setting_Volume, + Setting_Advanced, + Setting_Test, + Setting_End, +}; + +QNetworkRequest netReq(const QString &url, const QByteArray & = QByteArray(), int = QNetworkRequest::DefaultTransferTimeoutConstant); +inline QNetworkRequest reqForJson(const QString &url, int timeout = QNetworkRequest::DefaultTransferTimeoutConstant) { + return netReq(url, "application/json", timeout); +} +QString replyErr(QNetworkReply *); +QString checkReply(QNetworkReply *, QJsonDocument * = 0); +QString checkReplyForJson(QNetworkReply *, QJsonDocument * = 0, QByteArray * = 0); + +#define Def_CtrlReqPre \ + waitingDlg->show();\ + auto card = gSelCards->at(0);\ + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));\ + connect(waitingDlg, &WaitingDlg::rejected, reply, [reply] {\ + reply->blockSignals(true);\ + reply->abort();\ + reply->blockSignals(false);\ + reply->deleteLater();\ + }); + +#define Def_CtrlSetReqAfter \ + QString err = checkReplyForJson(reply);\ + if(! err.isEmpty()) {\ + waitingDlg->close();\ + QMessageBox::critical(gMainWin, tr("Error"), err);\ + return;\ + }\ + waitingDlg->success(); + +#define Def_CtrlSingleGetReply \ + QJsonDocument json;\ + QString err = checkReplyForJson(reply, &json);\ + if(! err.isEmpty()) {\ + waitingDlg->close();\ + QMessageBox::critical(gMainWin, tr("Error"), err);\ + return;\ + } + +#define Def_CtrlSetMulti(tip) \ + auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));\ + connect(reply, &QNetworkReply::finished, card, [=] {\ + QString err = checkReplyForJson(reply);\ + gFdResInfo->append(card->m_strCardId+" "+tip+" "+(err.isEmpty()?QCoreApplication::translate("Def","Success"):err));\ + }); + +#define CHECK_CARD_SELECTED \ + if(gSelCards->isEmpty()) {\ + QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));\ + return;\ + } + +#define MACRO_DEFINE_TIPDLG_FUCN(TIP,SUCCESS,FAILED) \ + if(gSelCards->count()==1) {\ + HttpPostByTypeJsonObject(pHpptClient, m_strUrl, json);\ + if(m_PostingDlg==nullptr) {\ + m_PostingDlg = new LoEmptyDialog(this);\ + connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg()));\ + connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock()));\ + m_PostingDlg->lock(TIP,SUCCESS,FAILED);\ + m_pGetAskTimer->start(5000);\ + m_PostingDlg->exec();\ + }\ + } else if(gSelCards->count() > 1) emit sigSend(json,TIP); + + +#define MACRO_DEFINE_TIPDLG_ALL_FUCN(READBACK,SUCCESS,FAILED) \ + if(gSelCards->count()==1) {\ + if(m_PostingDlg==nullptr) {\ + m_PostingDlg = new LoEmptyDialog(this);\ + connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg()));\ + connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock()));\ + m_PostingDlg->lock(READBACK+" "+gSelCards->at(0)->m_strCardId,SUCCESS,FAILED);\ + m_pGetAskTimer->start(5000);\ + m_PostingDlg->exec();\ + }\ + }\ + + +#define MARCO_DEFINE_CONTROL_FUNC2(PARENT,PARENT1) \ + pHpptClient = new HpptClient(this);\ + connect(pHpptClient,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponse(QString , QString , QByteArray)));\ + pHpptClientAll = new HpptClient(this);\ + connect(pHpptClientAll,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponseAll(QString , QString , QByteArray)));\ + m_pGetAskTimer=new QTimer(this);\ + connect(PARENT1,SIGNAL(sigSwitchIndexChanged(int)),this,SLOT(OnControlTypeSwitchIndexChanged(int)));\ + connect(PARENT,SIGNAL(sigSelectedDeviceList(QList *)),this,SLOT(onSelectedDeviceList(QList *)));\ + connect(this,SIGNAL(sigSend(QJsonObject &,QString)),PARENT,SLOT(OnControlSendJson(QJsonObject &,QString)));\ + onSelectedDeviceList(list); + +#define MACRO_ASKTIME_STOP \ +if(m_pGetAskTimer && m_pGetAskTimer->isActive()) m_pGetAskTimer->stop(); + +#define MACRO_POSTING_DLG_UNLOCK \ +if(m_PostingDlg && m_PostingDlg->getLockStatus()) m_PostingDlg->unlock(); + +#define MACRO_DEFINE_CONTROL_FUNC3 \ + if(m_pLedlist!=nullptr)\ + {\ + if(m_pLedlist->count()==1)\ + {\ + m_pLedCard=list->at(0);\ + m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";\ + if(m_oldLedlist!=m_pLedCard&&m_bSelected==true)\ + {\ + m_oldLedlist=m_pLedCard;\ + onReadbackAllThisPage();\ + }\ + }\ + } + +#endif // GLOBALDEFINE_H diff --git a/LedOK/gqt.h b/LedOK/gqt.h index 11bc6c8..c789f1c 100644 --- a/LedOK/gqt.h +++ b/LedOK/gqt.h @@ -1,122 +1,122 @@ -#ifndef GQT_H -#define GQT_H -#include -#include -#include - -inline long long steady_milli() { - return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); -} -inline long long system_milli() { - return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); -} -inline long long steady_micro() { - return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); -} -inline long long system_micro() { - return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); -} - -template -class Wrp { -public: - T *obj; - Wrp(T *obj = nullptr){ - this->obj = obj; - }; - inline Wrp& operator()(T *obj){ - this->obj = obj; - return *this; - } - inline Wrp& operator()(T *obj, QLayout *layout){ - this->obj = obj; - layout->addWidget(obj); - return *this; - } - inline Wrp& addTo(QLayout *layout){ - layout->addWidget(obj); - return *this; - } - inline Wrp& margin(int a){ - obj->setMargin(a); - return *this; - } - inline Wrp& font(const QFont &font){ - obj->setFont(font); - return *this; - } - inline Wrp& font(int size){ - QFont font = obj->font(); - font.setPointSize(size); - obj->setFont(font); - return *this; - } - - inline Wrp& width(int w){ - obj->setFixedWidth(w); - return *this; - } - inline Wrp& height(int h){ - obj->setFixedHeight(h); - return *this; - } - inline Wrp& padding(int wAdd, int hAdd, int minW = 32, int minH = 16){ - wAdd+=8; - hAdd+=8; - QSize size = obj->fontMetrics().size(Qt::TextShowMnemonic, obj->text()); - int &rwidth = size.rwidth(); - rwidth += wAdd; - if(rwidth < minW) rwidth = minW; - int &rheight = size.rheight(); - rheight += hAdd; - if(rheight < minH) rheight = minH; - obj->setFixedSize(size); - return *this; - } - - inline Wrp& alignC(){ - obj->setAlignment(Qt::AlignCenter); - return *this; - } - inline Wrp& alignR(){ - obj->setAlignment(Qt::AlignRight); - return *this; - } - - inline Wrp& connStart(){ - QObject::connect(obj, &QThread::finished, obj, &QThread::deleteLater); - obj->start(); - return *this; - } -}; - -class VBox : public QBoxLayout { -public: - inline VBox(QWidget *parent=nullptr) : QBoxLayout(TopToBottom, parent) {} - inline VBox(QBoxLayout *parent) : QBoxLayout(TopToBottom) { - parent->addLayout(this); - }; -}; -class HBox : public QBoxLayout { -public: - inline HBox(QWidget *parent=nullptr) : QBoxLayout(LeftToRight, parent) {} - inline HBox(QBoxLayout *parent) : QBoxLayout(LeftToRight) { - parent->addLayout(this); - }; -}; - -template -inline QThread *ThreadStart(Func &&f) { - QThread* thread = QThread::create(f); - QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater); - thread->start(); - return thread; -} - -inline void select(QComboBox *combo, const QVariant &data) { - int idx = combo->findData(data); - if(idx!=-1) combo->setCurrentIndex(idx); -} - - -#endif +#ifndef GQT_H +#define GQT_H +#include +#include +#include + +inline long long steady_milli() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +inline long long system_milli() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} +inline long long steady_micro() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +inline long long system_micro() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} + +template +class Wrp { +public: + T *obj; + Wrp(T *obj = nullptr){ + this->obj = obj; + }; + inline Wrp& operator()(T *obj){ + this->obj = obj; + return *this; + } + inline Wrp& operator()(T *obj, QLayout *layout){ + this->obj = obj; + layout->addWidget(obj); + return *this; + } + inline Wrp& addTo(QLayout *layout){ + layout->addWidget(obj); + return *this; + } + inline Wrp& margin(int a){ + obj->setMargin(a); + return *this; + } + inline Wrp& font(const QFont &font){ + obj->setFont(font); + return *this; + } + inline Wrp& font(int size){ + QFont font = obj->font(); + font.setPointSize(size); + obj->setFont(font); + return *this; + } + + inline Wrp& width(int w){ + obj->setFixedWidth(w); + return *this; + } + inline Wrp& height(int h){ + obj->setFixedHeight(h); + return *this; + } + inline Wrp& padding(int wAdd, int hAdd, int minW = 32, int minH = 16){ + wAdd+=8; + hAdd+=8; + QSize size = obj->fontMetrics().size(Qt::TextShowMnemonic, obj->text()); + int &rwidth = size.rwidth(); + rwidth += wAdd; + if(rwidth < minW) rwidth = minW; + int &rheight = size.rheight(); + rheight += hAdd; + if(rheight < minH) rheight = minH; + obj->setFixedSize(size); + return *this; + } + + inline Wrp& alignC(){ + obj->setAlignment(Qt::AlignCenter); + return *this; + } + inline Wrp& alignR(){ + obj->setAlignment(Qt::AlignRight); + return *this; + } + + inline Wrp& connStart(){ + QObject::connect(obj, &QThread::finished, obj, &QThread::deleteLater); + obj->start(); + return *this; + } +}; + +class VBox : public QBoxLayout { +public: + inline VBox(QWidget *parent=nullptr) : QBoxLayout(TopToBottom, parent) {} + inline VBox(QBoxLayout *parent) : QBoxLayout(TopToBottom) { + parent->addLayout(this); + }; +}; +class HBox : public QBoxLayout { +public: + inline HBox(QWidget *parent=nullptr) : QBoxLayout(LeftToRight, parent) {} + inline HBox(QBoxLayout *parent) : QBoxLayout(LeftToRight) { + parent->addLayout(this); + }; +}; + +template +inline QThread *ThreadStart(Func &&f) { + QThread* thread = QThread::create(f); + QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater); + thread->start(); + return thread; +} + +inline void select(QComboBox *combo, const QVariant &data) { + int idx = combo->findData(data); + if(idx!=-1) combo->setCurrentIndex(idx); +} + + +#endif diff --git a/LedOK/gutil/qcore.cpp b/LedOK/gutil/qcore.cpp new file mode 100644 index 0000000..4eae95f --- /dev/null +++ b/LedOK/gutil/qcore.cpp @@ -0,0 +1 @@ +#include "qcore.h" diff --git a/LedOK/gutil/qcore.h b/LedOK/gutil/qcore.h new file mode 100644 index 0000000..4d5b6dc --- /dev/null +++ b/LedOK/gutil/qcore.h @@ -0,0 +1,33 @@ +#ifndef QCORE_H +#define QCORE_H +#include + +inline QString byteSizeStr(double size) { + const char *units[]{"B", "KB", "MB", "GB", "TB", "PB"}; + auto i = 0; + for(; size >= 1024 && i < 5; i++) size /= 1024; + return QString::number(size, 'g', 3)+" "+units[i]; +} + +inline long long steady_milli() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +inline long long system_milli() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} +inline long long steady_micro() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +inline long long system_micro() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} + +template +inline QThread *ThreadStart(Func &&f) { + QThread* thread = QThread::create(f); + QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater); + thread->start(); + return thread; +} + +#endif diff --git a/LedOK/gutil/qgui.cpp b/LedOK/gutil/qgui.cpp new file mode 100644 index 0000000..745f9da --- /dev/null +++ b/LedOK/gutil/qgui.cpp @@ -0,0 +1,33 @@ +#include "qgui.h" + +const int AlignRight = Qt::AlignRight | Qt::AlignVCenter; + +Table::Table(std::initializer_list colAttrs, int rows, QWidget *parent) : NumTable{rows, (int)colAttrs.size(), parent} { + int i = 0; + for(typename std::initializer_list::const_iterator it = colAttrs.begin(); it != colAttrs.end(); ++it) { + auto item = horizontalHeaderItem(i); + if(item==0) setHorizontalHeaderItem(i, item = new QTableWidgetItem()); + item->setText(it->text); + item->setData(0x99, it->width); + if(it->width > 0) horizontalHeader()->resizeSection(i, it->width); + if(it->resizeMode > -1) horizontalHeader()->setSectionResizeMode(i, (QHeaderView::ResizeMode)it->resizeMode); + mFieldMap.insert(it->field, i++); + } +} + +int Table::sizeHintForColumn(int column) const { + auto item = horizontalHeaderItem(column); + if(item==0) return QTableWidget::sizeHintForColumn(column); + int width = item->data(0x99).toInt(); + if(width==0) return QTableWidget::sizeHintForColumn(column); + auto header = horizontalHeader(); + if(header->sectionResizeMode(column) != QHeaderView::ResizeToContents) return QTableWidget::sizeHintForColumn(column); + int colCnt = columnCount(); + int remainWidth = header->width(), stretchWidth = width; + for(int cc=0; ccsectionResizeMode(cc) == QHeaderView::ResizeToContents) stretchWidth += item->data(0x99).toInt(); + else remainWidth -= item->data(0x99).toInt(); + } + if(remainWidth<=0) return QTableWidget::sizeHintForColumn(column); + return width * remainWidth / stretchWidth; +} diff --git a/LedOK/gutil/qgui.h b/LedOK/gutil/qgui.h new file mode 100644 index 0000000..4412faa --- /dev/null +++ b/LedOK/gutil/qgui.h @@ -0,0 +1,301 @@ +#ifndef QGUI_H +#define QGUI_H + +#include +#include +#include +#include + +extern const int AlignRight; + +inline int setCurrentData(QComboBox *combo, const QVariant &data) { + auto idx = combo->findData(data); + if(idx>-1) combo->setCurrentIndex(idx); + return idx; +} + +class VBox : public QBoxLayout { +public: + inline VBox(QWidget *parent=nullptr) : QBoxLayout(TopToBottom, parent) {} + inline VBox(QBoxLayout *parent) : QBoxLayout(TopToBottom) { + parent->addLayout(this); + }; + inline VBox(QStackedLayout *parent) : QBoxLayout(TopToBottom) { + setContentsMargins(0,0,0,0); + auto wgt = new QWidget; + wgt->setLayout(this); + parent->addWidget(wgt); + }; +}; +class HBox : public QBoxLayout { +public: + inline HBox(QWidget *parent=nullptr) : QBoxLayout(LeftToRight, parent) {} + inline HBox(QBoxLayout *parent) : QBoxLayout(LeftToRight) { + parent->addLayout(this); + }; + inline HBox(QStackedLayout *parent) : QBoxLayout(LeftToRight) { + setContentsMargins(0,0,0,0); + auto wgt = new QWidget; + wgt->setLayout(this); + parent->addWidget(wgt); + }; +}; +class Grid : public QGridLayout { +public: + inline Grid(QWidget *parent=0) : QGridLayout(parent) {} + inline Grid(QBoxLayout *parent) { + parent->addLayout(this); + }; + inline Grid(QStackedLayout *parent) { + auto wgt = new QWidget; + wgt->setLayout(this); + parent->addWidget(wgt); + }; +}; + +class NumTable : public QTableWidget { + Q_OBJECT +public: + explicit NumTable(QWidget *parent = 0) : QTableWidget{parent} {} + NumTable(int rows, int columns, QWidget *parent = 0) : QTableWidget{rows, columns, parent} {} + + inline auto setNoEdit() { + setEditTriggers(QAbstractItemView::NoEditTriggers); + return this; + } + inline auto setColWidth(int value) { + horizontalHeader()->setDefaultSectionSize(value); + return this; + } + inline auto setRowHeight(int value) { + verticalHeader()->setDefaultSectionSize(value); + return this; + } + + inline auto setHeaderText(int column, QString text) { + auto item = horizontalHeaderItem(column); + if(item==0) setHorizontalHeaderItem(column, item = new QTableWidgetItem()); + item->setText(text); + return item; + } + + inline auto itemValid(int row, int column) { + auto item = QTableWidget::item(row, column); + if(item==0) setItem(row, column, item = new QTableWidgetItem); + return item; + } + inline auto text(int row, int column) { + auto item = QTableWidget::item(row, column); + if(item==0) return QString(); + return item->text(); + } + inline auto setText(int row, int column, const QString &text) { + auto item = QTableWidget::item(row, column); + if(item) item->setText(text); + else setItem(row, column, item = new QTableWidgetItem(text)); + return item; + } + + inline auto data(int row, int col) { + auto item = QTableWidget::item(row, col); + if(item==0) return QVariant(); + return item->data(Qt::UserRole); + } + inline auto setData(int row, int col, const QVariant &value) { + auto item = QTableWidget::item(row, col); + if(item==0) setItem(row, col, item = new QTableWidgetItem); + item->setData(Qt::UserRole, value); + return item; + } +}; + +struct ColAttr { + QString field; + QString text; + int width{0}; + int resizeMode{-1}; +}; +class Table : public NumTable { + Q_OBJECT +public: + explicit Table(QWidget *parent = nullptr) : NumTable{parent} {} + Table(std::initializer_list colAttrs, int rows = 0, QWidget *parent = nullptr); + + inline auto setDefs() { + setSelectionBehavior(QTableWidget::SelectRows); + setEditTriggers(QAbstractItemView::NoEditTriggers); + setAlternatingRowColors(true); + return this; + } + inline auto setColStretch() { + horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + return this; + } + inline auto setRowStretch() { + verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); + return this; + } + inline auto setColFit() { + horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + return this; + } + inline auto setRowFit() { + verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + return this; + } + inline auto setColWidth(int value) { + horizontalHeader()->setDefaultSectionSize(value); + return this; + } + inline auto setRowHeight(int value) { + verticalHeader()->setDefaultSectionSize(value); + return this; + } + + inline auto setHeaderText(QString column, QString text) { + auto col = mFieldMap[column]; + auto item = horizontalHeaderItem(col); + if(item==0) setHorizontalHeaderItem(col, item = new QTableWidgetItem()); + item->setText(text); + return item; + } + + inline auto appendRow() { + auto value = rowCount(); + setRowCount(value + 1); + return value; + } + + inline auto item(int row, QString column) { + auto col = mFieldMap[column]; + return QTableWidget::item(row, col); + } + inline void setItem(int row, QString column, QTableWidgetItem *item) { + auto col = mFieldMap[column]; + QTableWidget::setItem(row, col, item); + } + inline auto text(int row, QString column) { + auto col = mFieldMap[column]; + auto item = QTableWidget::item(row, col); + if(item==0) return QString(); + return item->text(); + } + inline auto setText(int row, QString column, const QString &text) { + auto col = mFieldMap[column]; + auto item = QTableWidget::item(row, col); + if(item) item->setText(text); + else QTableWidget::setItem(row, col, item = new QTableWidgetItem(text)); + return item; + } + + inline auto data(int row, QString column) { + auto col = mFieldMap[column]; + auto item = QTableWidget::item(row, col); + if(item==0) return QVariant(); + return item->data(Qt::UserRole); + } + inline auto setData(int row, QString column, const QVariant &value) { + auto col = mFieldMap[column]; + auto item = QTableWidget::item(row, col); + if(item==0) QTableWidget::setItem(row, col, item = new QTableWidgetItem); + item->setData(Qt::UserRole, value); + return item; + } + + inline auto cellWidget(int row, QString column) { + auto col = mFieldMap[column]; + return QTableWidget::cellWidget(row, col); + } + inline void setCellWidget(int row, QString column, QWidget *widget) { + auto col = mFieldMap[column]; + QTableWidget::setCellWidget(row, col, widget); + } + + QMap mFieldMap; + +public Q_SLOTS: + inline void clearRows() {setRowCount(0);} + +protected: + int sizeHintForColumn(int column) const override; +}; + +class ResizeEmitedWgt : public QWidget { + Q_OBJECT +public: + explicit ResizeEmitedWgt(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()) : QWidget{parent, f} {} +protected: + void resizeEvent(QResizeEvent *) override {emit resized();} +signals: + void resized(); +}; + + +template +class Wrp { +public: + T *obj; + Wrp(T *obj = nullptr){ + this->obj = obj; + }; + inline Wrp& operator()(T *obj){ + this->obj = obj; + return *this; + } + inline Wrp& operator()(T *obj, QLayout *layout){ + this->obj = obj; + layout->addWidget(obj); + return *this; + } + inline Wrp& addTo(QLayout *layout){ + layout->addWidget(obj); + return *this; + } + inline Wrp& margin(int a){ + obj->setMargin(a); + return *this; + } + inline Wrp& font(const QFont &font){ + obj->setFont(font); + return *this; + } + inline Wrp& font(int size){ + QFont font = obj->font(); + font.setPointSize(size); + obj->setFont(font); + return *this; + } + + inline Wrp& width(int w){ + obj->setFixedWidth(w); + return *this; + } + inline Wrp& height(int h){ + obj->setFixedHeight(h); + return *this; + } + inline Wrp& padding(int wAdd, int hAdd, int minW = 32, int minH = 16){ + wAdd+=8; + hAdd+=8; + QSize size = obj->fontMetrics().size(Qt::TextShowMnemonic, obj->text()); + int &rwidth = size.rwidth(); + rwidth += wAdd; + if(rwidth < minW) rwidth = minW; + int &rheight = size.rheight(); + rheight += hAdd; + if(rheight < minH) rheight = minH; + obj->setFixedSize(size); + return *this; + } + + inline Wrp& alignC(){ + obj->setAlignment(Qt::AlignCenter); + return *this; + } + inline Wrp& alignR(){ + obj->setAlignment(Qt::AlignRight); + return *this; + } +}; + +#endif diff --git a/LedOK/gutil/qnetwork.cpp b/LedOK/gutil/qnetwork.cpp new file mode 100644 index 0000000..4c4a020 --- /dev/null +++ b/LedOK/gutil/qnetwork.cpp @@ -0,0 +1,83 @@ +#include "qnetwork.h" + +#include +#include + +const char *const FormBoundary = "----GangphonQtBoundary_.oOo._"; + +QNetworkAccessManager &netAccess() { + static QNetworkAccessManager access; + return access; +}; + +QString errStr(QNetworkReply *reply) { + reply->deleteLater(); + auto error = reply->error(); + if(error != QNetworkReply::NoError) { + if(error==QNetworkReply::OperationCanceledError) return QString(QMetaEnum::fromType().valueToKey(QNetworkReply::TimeoutError))+" ("+QString::number(QNetworkReply::TimeoutError)+") "+QCoreApplication::translate("Net","Connection Timeout"); + auto errStr = reply->errorString(); + if(error!=QNetworkReply::InternalServerError || ! errStr.endsWith("replied: Unknown")) return QString(QMetaEnum::fromType().valueToKey(error))+" ("+QString::number(error)+") "+errStr; + } + auto status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if(status != 200) return QString::number(status)+" "+reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); + return ""; +} +QString errStrWithData(QNetworkReply *reply, QJsonDocument *outJson) { + auto err = errStr(reply); + if(! err.isEmpty()) { + auto data = reply->readAll(); + if(! data.isEmpty()) err += "\n"+data; + return err; + } + if(outJson) { + auto data = reply->readAll(); + QJsonParseError jsonErr; + *outJson = QJsonDocument::fromJson(data, &jsonErr); + if(jsonErr.error != QJsonParseError::NoError) return "JSON "+QCoreApplication::translate("Net","Error")+": "+data; + } + return ""; +} + + +const char* socketErrKey(int value) { + static auto metaEnum = QMetaEnum::fromType(); + return metaEnum.valueToKey(value); +} + +bool TcpSocket::waitForConnected(int msecs) { + if(state() == ConnectedState) return true; + QEventLoop loop; + connect(this, &QTcpSocket::connected, &loop, &QEventLoop::quit); + return connAndExec(msecs, &loop); +} +bool TcpSocket::waitForDisconnected(int msecs) { + if(state() == UnconnectedState) return true; + QEventLoop loop; + connect(this, &QTcpSocket::disconnected, &loop, &QEventLoop::quit); + return connAndExec(msecs, &loop); +} +bool TcpSocket::waitForBytesWritten(int msecs) { + QEventLoop loop; + connect(this, &QTcpSocket::bytesWritten, &loop, &QEventLoop::quit); + return connAndExec(msecs, &loop); +} +bool TcpSocket::waitForReadyRead(int msecs) { + QEventLoop loop; + connect(this, &QTcpSocket::readyRead, &loop, &QEventLoop::quit); + return connAndExec(msecs, &loop); +} + +bool TcpSocket::connAndExec(int msecs, QEventLoop *loop) { + connect(this, &QTcpSocket::errorOccurred, loop, [loop] { + loop->exit(1); + }); + if(msecs > 0) { + connect(this, &TcpSocket::timeout, loop, &QEventLoop::exit); + if(timerId!=0) killTimer(timerId); + timerId = startTimer(msecs); + } + auto res = loop->exec(); + timerStop(); + if(res==5) setSocketError(SocketTimeoutError); + return res==0; +} diff --git a/LedOK/gutil/qnetwork.h b/LedOK/gutil/qnetwork.h new file mode 100644 index 0000000..8b1fe86 --- /dev/null +++ b/LedOK/gutil/qnetwork.h @@ -0,0 +1,90 @@ +#ifndef QNETWORK_H +#define QNETWORK_H + +#include +#include +#include +#include + +extern const char *const FormBoundary; + +QNetworkAccessManager &netAccess(); + +class NetReq : public QNetworkRequest { +public: + NetReq(); + explicit NetReq(const QString &url) : QNetworkRequest{url}{}; + explicit NetReq(const QUrl &url) : QNetworkRequest{url}{}; + NetReq(const QNetworkRequest &other) : QNetworkRequest{other}{}; + + inline NetReq &type(const QByteArray &value) { + setRawHeader("Content-Type", value); + return *this; + } + inline NetReq &typeJson() { + setRawHeader("Content-Type", "application/json"); + return *this; + } + inline NetReq &timeout(int timeout) { + setTransferTimeout(timeout); + return *this; + } + inline NetReq &v5() { + setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy); + return *this; + } + + inline QNetworkReply *get() { + return netAccess().get(*this); + } + inline QNetworkReply *post(const QByteArray &data) { + return netAccess().post(*this, data); + } + inline QNetworkReply *post(const QJsonObject &json) { + setRawHeader("Content-Type", "application/json"); + return netAccess().post(*this, QJsonDocument{json}.toJson(QJsonDocument::Compact)); + } + inline QNetworkReply *post(const QJsonArray &json) { + setRawHeader("Content-Type", "application/json"); + return netAccess().post(*this, QJsonDocument{json}.toJson(QJsonDocument::Compact)); + } + inline QNetworkReply *post(QHttpMultiPart *multiPart) { + return netAccess().post(*this, multiPart); + } +}; + +QString errStr(QNetworkReply *); +QString errStrWithData(QNetworkReply *, QJsonDocument * = 0); + +const char* socketErrKey(int value); + +class TcpSocket : public QTcpSocket { + Q_OBJECT +public: + explicit TcpSocket(QObject *parent = nullptr) : QTcpSocket{parent} {}; + ~TcpSocket() { + if(timerId!=0) killTimer(timerId); + }; + bool waitForConnected(int msecs = 30000) override; + bool waitForDisconnected(int msecs = 30000) override; + bool waitForBytesWritten(int msecs = 30000) override; + bool waitForReadyRead(int msecs = 30000) override; +protected: + void timerEvent(QTimerEvent *e) override { + if(e->timerId()!=timerId) return; + killTimer(timerId); + timerId = 0; + emit timeout(5); + }; + bool connAndExec(int msecs, QEventLoop *loop); + inline void timerStop() { + if(timerId==0) return; + killTimer(timerId); + timerId = 0; + } + int timerId = 0; +signals: + void timeout(int); +}; + +#endif // QNETWORK_H diff --git a/LedOK/importbninprogramdlg.cpp b/LedOK/importbninprogramdlg.cpp index cdfd725..aa1b8b3 100644 --- a/LedOK/importbninprogramdlg.cpp +++ b/LedOK/importbninprogramdlg.cpp @@ -1,14 +1,14 @@ -#include "importbninprogramdlg.h" -#include "ui_importbninprogramdlg.h" - -ImportBnInProgramDlg::ImportBnInProgramDlg(QWidget *parent) : - LoQDialog(parent), - ui(new Ui::ImportBnInProgramDlg) -{ - ui->setupUi(this); -} - -ImportBnInProgramDlg::~ImportBnInProgramDlg() -{ - delete ui; -} +#include "importbninprogramdlg.h" +#include "ui_importbninprogramdlg.h" + +ImportBnInProgramDlg::ImportBnInProgramDlg(QWidget *parent) : + LoQDialog(parent), + ui(new Ui::ImportBnInProgramDlg) +{ + ui->setupUi(this); +} + +ImportBnInProgramDlg::~ImportBnInProgramDlg() +{ + delete ui; +} diff --git a/LedOK/importbninprogramdlg.h b/LedOK/importbninprogramdlg.h index 40f863a..392994a 100644 --- a/LedOK/importbninprogramdlg.h +++ b/LedOK/importbninprogramdlg.h @@ -1,22 +1,22 @@ -#ifndef IMPORTBNINPROGRAMDLG_H -#define IMPORTBNINPROGRAMDLG_H - -#include - -namespace Ui { -class ImportBnInProgramDlg; -} - -class ImportBnInProgramDlg : public LoQDialog -{ - Q_OBJECT - -public: - explicit ImportBnInProgramDlg(QWidget *parent = nullptr); - ~ImportBnInProgramDlg(); - -private: - Ui::ImportBnInProgramDlg *ui; -}; - -#endif // IMPORTBNINPROGRAMDLG_H +#ifndef IMPORTBNINPROGRAMDLG_H +#define IMPORTBNINPROGRAMDLG_H + +#include + +namespace Ui { +class ImportBnInProgramDlg; +} + +class ImportBnInProgramDlg : public LoQDialog +{ + Q_OBJECT + +public: + explicit ImportBnInProgramDlg(QWidget *parent = nullptr); + ~ImportBnInProgramDlg(); + +private: + Ui::ImportBnInProgramDlg *ui; +}; + +#endif // IMPORTBNINPROGRAMDLG_H diff --git a/LedOK/importbninprogramdlg.ui b/LedOK/importbninprogramdlg.ui index 1194194..51fd2dd 100644 --- a/LedOK/importbninprogramdlg.ui +++ b/LedOK/importbninprogramdlg.ui @@ -1,68 +1,68 @@ - - - ImportBnInProgramDlg - - - - 0 - 0 - 638 - 296 - - - - Dialog - - - - - 10 - 210 - 621 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - buttonBox - rejected() - ImportBnInProgramDlg - reject() - - - 316 - 260 - - - 286 - 274 - - - - - buttonBox - accepted() - ImportBnInProgramDlg - accept() - - - 248 - 254 - - - 157 - 274 - - - - - + + + ImportBnInProgramDlg + + + + 0 + 0 + 638 + 296 + + + + Dialog + + + + + 10 + 210 + 621 + 32 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + buttonBox + rejected() + ImportBnInProgramDlg + reject() + + + 316 + 260 + + + 286 + 274 + + + + + buttonBox + accepted() + ImportBnInProgramDlg + accept() + + + 248 + 254 + + + 157 + 274 + + + + + diff --git a/LedOK/importprogramdlg.ui b/LedOK/importprogramdlg.ui index eb5f518..cb87e5a 100644 --- a/LedOK/importprogramdlg.ui +++ b/LedOK/importprogramdlg.ui @@ -1,80 +1,80 @@ - - - Dialog - - - Qt::NonModal - - - - 0 - 0 - 320 - 240 - - - - - 320 - 240 - - - - Dialog - - - false - - - - - 10 - 200 - 301 - 32 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - + + + Dialog + + + Qt::NonModal + + + + 0 + 0 + 320 + 240 + + + + + 320 + 240 + + + + Dialog + + + false + + + + + 10 + 200 + 301 + 32 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + buttonBox + accepted() + Dialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + Dialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/LedOK/main.cpp b/LedOK/main.cpp index 77ad255..4497704 100644 --- a/LedOK/main.cpp +++ b/LedOK/main.cpp @@ -1,7 +1,9 @@ #include "mainwindow.h" #include +#include #include #include +#include #ifdef _MSC_VER //MSVC编译器 #include @@ -29,7 +31,7 @@ LONG WINAPI handleException(_EXCEPTION_POINTERS *excep) { #endif QString gFileHome; - +QString css; int main(int argc, char *argv[]) { QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); @@ -38,12 +40,18 @@ int main(int argc, char *argv[]) { QApplication::setOrganizationDomain("www.ledok.cn"); QApplication::setApplicationName("LedOK Express"); QApplication a(argc, argv); - gFileHome = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); + a.setStyle(QStyleFactory::create("Fusion")); + QFile file(":/css.css"); + if(file.exists() && file.open(QFile::ReadOnly)) { + a.setStyleSheet(css = file.readAll()); + file.close(); + } QFont font; font.setFamilies(QStringList{"Arial","Microsoft YaHei UI"}); font.setPixelSize(14); a.setFont(font); + gFileHome = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); QSplashScreen splash(QPixmap(":/res/splash.png")); splash.show(); splash.showMessage(QObject::tr("Setting up the LedOK Express..."), Qt::AlignRight | Qt::AlignTop, Qt::white); diff --git a/LedOK/mainwindow.cpp b/LedOK/mainwindow.cpp index 47835ef..f72e7c4 100644 --- a/LedOK/mainwindow.cpp +++ b/LedOK/mainwindow.cpp @@ -1,10 +1,10 @@ #include "mainwindow.h" #include "base/aboutdlg.h" #include "base/softconfigdialog.h" -#include "base/updaterdialog.h" +#include "gutil/qgui.h" #include "cfg.h" #include "tools.h" -#include "wDevicesManager/upgradeapkdialog.h" +#include "device/upgradeapkdialog.h" #include #include #include @@ -14,6 +14,7 @@ #include #include #include +#include "QSimpleUpdater.h" QWidget *gMainWin; extern QPoint gPlayPos; @@ -46,30 +47,36 @@ protected: }; MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { + setAttribute(Qt::WA_AlwaysShowToolTips); gMainWin = this; - QMenu *menuLang = new QMenu(); - QAction *actLan = nullptr; - QAction *actCN = new QAction("中文"); + auto menuLang = new QMenu(); + + auto actCN = new QAction("中文"); actCN->setCheckable(true); actCN->setObjectName("zh_CN"); - QAction *actTW = new QAction("中文繁体"); + menuLang->addAction(actCN); + + auto actTW = new QAction("中文繁体"); actTW->setCheckable(true); actTW->setObjectName("zh_TW"); - QAction *actEn = new QAction("English"); + menuLang->addAction(actTW); + + auto actEn = new QAction("English"); actEn->setCheckable(true); actEn->setObjectName("en"); - QAction *actJa = new QAction("日本語"); + menuLang->addAction(actEn); + + auto actJa = new QAction("日本語"); actJa->setCheckable(true); actJa->setObjectName("ja"); - menuLang->addAction(actCN); - menuLang->addAction(actTW); - menuLang->addAction(actEn); menuLang->addAction(actJa); + langGrp = new QActionGroup(menuLang); langGrp->addAction(actCN); langGrp->addAction(actTW); langGrp->addAction(actEn); langGrp->addAction(actJa); + connect(menuLang, &QMenu::triggered, this, [this](QAction* action) { auto lanName = action->objectName(); translator.load("app_"+lanName, ":/i18n"); @@ -77,12 +84,8 @@ MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { }); QSettings settings; - settings.remove("MainSetting"); - settings.remove("MainWindowMaximized"); - settings.remove("posMainWindow"); - settings.remove("sizeMainWindow"); - settings.remove("DirectlyConnectNetWork"); QString langName = settings.value("Language").toString(); + QAction *actLan = nullptr; if(! langName.isEmpty()) { if(langName.endsWith("CN")) actLan = actCN; else if(langName.endsWith("TW")) actLan = actTW; @@ -105,8 +108,8 @@ MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { QApplication::installTranslator(&transQt); auto geo = settings.value("MainGeo").toRect(); - if(geo.width()>=800 && geo.height()>=500 && geo.x()>=-600 && geo.x()<=1280 && geo.y()>=-200 && geo.y()<=720) setGeometry(geo); - else resize(1280, 720); + if(geo.width()>=800 && geo.height()>=500 && geo.x()>=-600 && geo.x()<=1280 && geo.y()>=-200 && geo.y()<=800) setGeometry(geo); + else resize(1280, 800); if(settings.value("MainIsMax", false).toBool()) setWindowState(Qt::WindowMaximized); gPlayPos = settings.value("PlayPos").toPoint(); @@ -115,7 +118,6 @@ MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { icon.load(":/res/Logo.png"); titlePos = QPointF(26, 80); iconPos = QPointF(38, 20); - setStyleSheet(Tools::styleSheet()); auto plt = palette(); plt.setBrush(QPalette::Window, QColor(0xdddddd)); setPalette(plt); @@ -146,33 +148,87 @@ MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { bn_Setting = new QPushButton(); bn_Setting->setIcon(QIcon(":/res/AppSetting.png")); + bn_Setting->setToolTip(tr("Setting")); + pLayout->addWidget(bn_Setting); pLayout->addWidget(m_wTitle->bn_Minimize); pLayout->addWidget(m_wTitle->bn_Maximize); pLayout->addWidget(m_wTitle->bn_Close); - QMenu *menu_setting = new QMenu(); + auto menu_setting = new QMenu(); act_lang = new QAction(); act_lang->setMenu(menuLang); menu_setting->addAction(act_lang); - act_softconfiguration = new QAction(tr("Software Configuration")); - act_softconfiguration->setObjectName("Software Configuration"); + act_softconfiguration = new QAction(tr("Software Config")); + connect(act_softconfiguration, &QAction::triggered, this, [this] { + SoftConfigDialog dlg(this); + dlg.exec(); + mBtnGrp->button(MainPage_LoraScreen)->setVisible(gShowLoraScreen); + }); menu_setting->addAction(act_softconfiguration); act_update = new QAction(tr("Check for updates")); - act_update->setObjectName("Update"); + connect(act_update, &QAction::triggered, this, [this] { + QDialog dlg(this); + dlg.setWindowFlag(Qt::WindowContextHelpButtonHint, false); + dlg.setWindowTitle(tr("Software Update")); + dlg.resize(500, 400); + + auto vBox = new VBox(&dlg); + + auto label = new QLabel(tr("CurVersion")+": "+APP_VERSION); + auto font = label->font(); + font.setPointSize(14); + label->setFont(font); + vBox->addWidget(label); + + auto fdVerInfo = new QTextEdit; + fdVerInfo->setReadOnly(true); + vBox->addWidget(fdVerInfo); + + auto btnUpdate = new QPushButton(tr("Update")); + btnUpdate->setFixedWidth(80); + connect(btnUpdate, &QPushButton::clicked, this, [] { + QSimpleUpdater::getInstance()->setNotifyOnUpdate(UpdVerUrl, true); + QSimpleUpdater::getInstance()->setNotifyOnFinish(UpdVerUrl, false); + QSimpleUpdater::getInstance()->setMandatoryUpdate(UpdVerUrl, true); + QSimpleUpdater::getInstance()->checkForUpdates(UpdVerUrl); + }); + vBox->addWidget(btnUpdate, 0, Qt::AlignHCenter); + + auto updater = QSimpleUpdater::getInstance(); + connect(updater, &QSimpleUpdater::checkingFinished, fdVerInfo, [fdVerInfo, btnUpdate] { + if(QSimpleUpdater::getInstance()->getUpdateAvailable(UpdVerUrl)) fdVerInfo->setText(tr("LatestVersion:") + QSimpleUpdater::getInstance()->getLatestVersion(UpdVerUrl) + "\n" + tr("Update log:") + "\n" + QSimpleUpdater::getInstance()->getChangelog(UpdVerUrl)); + else { + fdVerInfo->setText(tr("The current version is already the latest version") + "\n\n" + tr("Update log:") + "\n" + QSimpleUpdater::getInstance()->getChangelog(UpdVerUrl)); + btnUpdate->setVisible(false); + } + }); + updater->setModuleVersion(UpdVerUrl, APP_VERSION); + updater->setNotifyOnUpdate(UpdVerUrl, false); + updater->setNotifyOnFinish(UpdVerUrl, false); + updater->checkForUpdates(UpdVerUrl); + dlg.exec(); + }); menu_setting->addAction(act_update); act_updatefirmware = new QAction(tr("firmware manager")); - act_updatefirmware->setObjectName("Update firmware"); + connect(act_updatefirmware, &QAction::triggered, this, [this] { + UpgradeApkDialog dlg(this); + dlg.exec(); + }); menu_setting->addAction(act_updatefirmware); act_help = new QAction(); - act_help->setObjectName("Help"); + connect(act_help, &QAction::triggered, this, [this] { + auto act = langGrp->checkedAction(); + if(act==0) return; + QDesktopServices::openUrl(QUrl::fromLocalFile(QCoreApplication::applicationDirPath()+"/help/"+act->objectName()+".pdf")); + }); menu_setting->addAction(act_help); - auto actInfo = new QAction(tr("Info")); + actInfo = new QAction; connect(actInfo, &QAction::triggered, this, [this] { QMessageBox::information(this, tr("Info"), QString("SupportsSsl: ").append(QSslSocket::supportsSsl()?"true":"false") @@ -182,32 +238,12 @@ MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { menu_setting->addAction(actInfo); act_about = new QAction(tr("About")); - act_about->setObjectName("About"); - menu_setting->addAction(act_about); - - bn_Setting->setMenu(menu_setting);//按钮上添加下拉菜单 - bn_Setting->setToolTip(tr("Setting")); - - connect(menu_setting, &QMenu::triggered, this, [this](QAction* act) { - if(act->objectName()=="About") { - AboutDlg pDlg(this); - pDlg.exec(); - }else if(act->objectName()=="Help") { - auto act = langGrp->checkedAction(); - if(act==0) return; - QDesktopServices::openUrl(QUrl::fromLocalFile(QCoreApplication::applicationDirPath()+"/help/"+act->objectName()+".pdf")); - } else if(act->objectName()=="Update") { - UpdaterDialog *pDlg=new UpdaterDialog(this); - pDlg->exec(); - } else if(act->objectName()=="Update firmware") { - auto dlg = new UpgradeApkDialog(this); - dlg->showMaximized(); - } else if(act->objectName()=="Software Configuration") { - SoftConfigDialog dlg(this); - dlg.exec(); - mBtnGrp->button(MainPage_LoraScreen)->setVisible(gShowLoraScreen); - } + connect(act_about, &QAction::triggered, this, [this] { + AboutDlg dlg(this); + dlg.exec(); }); + menu_setting->addAction(act_about); + bn_Setting->setMenu(menu_setting);//按钮上添加下拉菜单 QSimpleUpdater *updater = QSimpleUpdater::getInstance(); connect(updater, &QSimpleUpdater::checkingFinished, this, [this]() { @@ -296,6 +332,8 @@ MainWindow::MainWindow(QWidget *parent) : BaseWin(parent) { hBox->addWidget(m_pOneKeyCheckCard); hBox->addStretch(); + //hBox->addWidget(new QLabel("ver: " APP_VERSION ".2")); + vBox->addLayout(hBox); gVideoCompress = settings.value("VideoCompress", true).toBool(); @@ -373,9 +411,7 @@ void MainWindow::test() { qDebug()<<"status"<request(); qDebug()<<"reply url"<url(); - qDebug()<<"req url"<readAll(); qDebug()<<"resp"<fdIP) { auto ipstr = mDevicePanel->fdIP->toPlainText(); if(! ipstr.isEmpty()) settings.setValue("SpecifyIP", ipstr); + else settings.remove("SpecifyIP"); } if(m_pTimerSendResoreIpOneKey!=nullptr) { if(m_pTimerSendResoreIpOneKey->isActive()) m_pTimerSendResoreIpOneKey->stop(); @@ -426,9 +463,10 @@ void MainWindow::transUi() { m_pOneKeyCheckCard->setText(tr("Check card")); act_lang->setText(tr("Language")); act_help->setText(tr("Help")); + actInfo->setText(tr("Info")); act_about->setText(tr("About")); act_update->setText(tr("Check for updates")); act_updatefirmware->setText(tr("firmware manager")); - act_softconfiguration->setText(tr("Software Configuration")); + act_softconfiguration->setText(tr("Software Config")); bn_Setting->setToolTip(tr("Setting")); } diff --git a/LedOK/mainwindow.h b/LedOK/mainwindow.h index 9c1b730..f132861 100644 --- a/LedOK/mainwindow.h +++ b/LedOK/mainwindow.h @@ -8,6 +8,7 @@ #include "mguangyingpinwidget.h" #include "progpanel.h" #include +#include class MainWindow : public BaseWin { Q_OBJECT @@ -23,7 +24,7 @@ private: LoQTitleBar *m_wTitle; QActionGroup *langGrp; QAction *act_lang; - QAction *act_help; + QAction *act_help, *actInfo; QAction *act_update; QAction *act_updatefirmware; QAction *act_softconfiguration; diff --git a/LedOK/mguangyingpinwidget.cpp b/LedOK/mguangyingpinwidget.cpp index 8b2b1a6..bd23d90 100644 --- a/LedOK/mguangyingpinwidget.cpp +++ b/LedOK/mguangyingpinwidget.cpp @@ -1,867 +1,867 @@ -#include -#include "mguangyingpinwidget.h" -#include "ui_mguangyingpinwidget.h" -#include -#include "globaldefine.h" -mGuangYingPinWidget::mGuangYingPinWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::mGuangYingPinWidget) -{ - setAutoFillBackground(true); - QPalette pal; - pal.setBrush(QPalette::Window, QColor(0xeeeeee)); - setPalette(pal); - - ui->setupUi(this); - ui->pushButton1->setProperty("ssType", "progManageTool"); - ui->pushButton2->setProperty("ssType", "progManageTool"); - ui->pushButton3->setProperty("ssType", "progManageTool"); - ui->pushButton4->setProperty("ssType", "progManageTool"); - ui->pushButton5->setProperty("ssType", "progManageTool"); - ui->pushButton6->setProperty("ssType", "progManageTool"); - ui->pushButton7->setProperty("ssType", "progManageTool"); - ui->pushButton8->setProperty("ssType", "progManageTool"); - ui->pushButton9->setProperty("ssType", "progManageTool"); - ui->pushButton10->setProperty("ssType", "progManageTool"); - ui->pushButton11->setProperty("ssType", "progManageTool"); - ui->pushButton12->setProperty("ssType", "progManageTool"); - ui->pushButton13->setProperty("ssType", "progManageTool"); - ui->pushButton14->setProperty("ssType", "progManageTool"); - ui->pushButton15->setProperty("ssType", "progManageTool"); - ui->pushButton16->setProperty("ssType", "progManageTool"); - ui->pushButton17->setProperty("ssType", "progManageTool"); - ui->pushButton18->setProperty("ssType", "progManageTool"); - ui->pushButton19->setProperty("ssType", "progManageTool"); - ui->pushButton20->setProperty("ssType", "progManageTool"); - - ui->pushButtonSend->setProperty("ssType", "progManageTool"); - ui->pushButtonPrevious->setProperty("ssType", "progManageTool"); - ui->pushButtonPrevious->setIcon(QIcon(":/res/previous.png")); - ui->pushButtonNext->setProperty("ssType", "progManageTool"); - ui->pushButtonNext->setIcon(QIcon(":/res/next.png")); - ui->pushButtonLoop->setProperty("ssType", "progManageTool"); - ui->pushButtonLoop->setIcon(QIcon(":/res/loop.png")); - ui->pushButtonMainOpen->setProperty("ssType", "progManageTool"); - ui->pushButtonAuxOpen->setProperty("ssType", "progManageTool"); - ui->pushButtonBrightnessSet->setProperty("ssType", "progManageTool"); - ui->pushButtonScreenOn->setProperty("ssType", "progManageTool"); - ui->pushButtonScreenOff->setProperty("ssType", "progManageTool"); - ui->pushButtonRefresh->setProperty("ssType", "progManageTool"); - ui->pushButtonClearLog->setProperty("ssType", "progManageTool"); - m_recvNum = 0; - m_sendNum = 0; - sPortThread = new TA_SerialThread; - sPortThread->SearchPort(); - - for(uint8_t i = 0;i < sPortThread->portCnt;i++) - { - ui->comboBox_SPortName->addItem(sPortThread->m_arrSerial[i].portName()); - ui->comboBox_SPortNameAux->addItem(sPortThread->m_arrSerial[i].portName()); - } - - //0:1200 1:2400 2:4800 3:9600 4:19200 5:38400 6:57600 7:115200 - if(ui->comboBox_SPortName->count()>=1) - { - ui->comboBox_SPortBaud->setCurrentIndex(3); - //0:5 1:6 2:7 3:8 - ui->comboBox_SPortDataBit->setCurrentIndex(3); - //0:no p 2:e p 3:o p 4:s p 5:m p - ui->comboBox_SPortOEBit->setCurrentIndex(0); - //0:1 1:2 2:1.5 - ui->comboBox_SPortStopBit->setCurrentIndex(0); - - ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(255, 0, 0);"); - ui->label_ComStatus->setText(tr("State:Off")); - - ui->comboBox_SPortBaudAux->setCurrentIndex(3); - ui->comboBox_SPortDataBitAux->setCurrentIndex(3); - ui->comboBox_SPortOEBitAux->setCurrentIndex(0); - ui->comboBox_SPortStopBitAux->setCurrentIndex(0); - ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(255, 0, 0);"); - ui->label_ComStatusAux->setText(tr("State:Off")); - if(ui->comboBox_SPortName->count()>1) - { - ui->comboBox_SPortNameAux->setCurrentIndex(1); - } - } - ui->lineEdit_ResendTimes->setValidator(new QIntValidator(1,1000,this)); - ui->lineEdit_DelayMill->setValidator(new QIntValidator(1,1000,this)); - - - connect(ui->pushButtonMainOpen, SIGNAL(clicked(bool)), this, SLOT(MWOnoffPort())); - connect(ui->pushButtonAuxOpen, SIGNAL(clicked(bool)), this, SLOT(MWOnoffPortAux())); - connect(ui->pushButton1, SIGNAL(clicked()), this, SLOT(OnAnsyProgram1())); - connect(ui->pushButton2, SIGNAL(clicked()), this, SLOT(OnAnsyProgram2())); - connect(ui->pushButton3, SIGNAL(clicked()), this, SLOT(OnAnsyProgram3())); - connect(ui->pushButton4, SIGNAL(clicked()), this, SLOT(OnAnsyProgram4())); - connect(ui->pushButton5, SIGNAL(clicked()), this, SLOT(OnAnsyProgram5())); - connect(ui->pushButton6, SIGNAL(clicked()), this, SLOT(OnAnsyProgram6())); - connect(ui->pushButton7, SIGNAL(clicked()), this, SLOT(OnAnsyProgram7())); - connect(ui->pushButton8, SIGNAL(clicked()), this, SLOT(OnAnsyProgram8())); - connect(ui->pushButton9, SIGNAL(clicked()), this, SLOT(OnAnsyProgram9())); - connect(ui->pushButton10, SIGNAL(clicked()), this, SLOT(OnAnsyProgram10())); - connect(ui->pushButton11, SIGNAL(clicked()), this, SLOT(OnAnsyProgram11())); - connect(ui->pushButton12, SIGNAL(clicked()), this, SLOT(OnAnsyProgram12())); - connect(ui->pushButton13, SIGNAL(clicked()), this, SLOT(OnAnsyProgram13())); - connect(ui->pushButton14, SIGNAL(clicked()), this, SLOT(OnAnsyProgram14())); - connect(ui->pushButton15, SIGNAL(clicked()), this, SLOT(OnAnsyProgram15())); - connect(ui->pushButton16, SIGNAL(clicked()), this, SLOT(OnAnsyProgram16())); - connect(ui->pushButton17, SIGNAL(clicked()), this, SLOT(OnAnsyProgram17())); - connect(ui->pushButton18, SIGNAL(clicked()), this, SLOT(OnAnsyProgram18())); - connect(ui->pushButton19, SIGNAL(clicked()), this, SLOT(OnAnsyProgram19())); - connect(ui->pushButton20, SIGNAL(clicked()), this, SLOT(OnAnsyProgram20())); - connect(ui->pushButtonClearLog, SIGNAL(clicked()), this, SLOT(OnClearLog())); - connect(ui->pushButtonSend, SIGNAL(clicked()), this, SLOT(OnAnsyProgramCustom())); - connect(ui->pushButtonNext, SIGNAL(clicked()), this, SLOT(OnAnsyProgramNext())); - connect(ui->pushButtonPrevious, SIGNAL(clicked()), this, SLOT(OnAnsyProgramPrevious())); - connect(ui->pushButtonLoop, SIGNAL(clicked()), this, SLOT(OnAnsyProgramLoop())); - connect(ui->pushButtonBrightnessSet, SIGNAL(clicked()), this, SLOT(OnBrightnessSet())); - connect(ui->pushButtonScreenOn, SIGNAL(clicked()), this, SLOT(OnScreenOn())); - connect(ui->pushButtonScreenOff, SIGNAL(clicked()), this, SLOT(OnScreenOff())); - connect(ui->spinBox_ProgramIndex, SIGNAL(valueChanged(int)), this, SLOT(OnAnsyProgramCustomByChanged(int))); - connect(ui->spinBox_BrightnessValue, SIGNAL(valueChanged(int)), this, SLOT(OnBrightnessSetByChanged(int))); - connect(ui->pushButtonRefresh, SIGNAL(clicked()), this, SLOT(OnRefresh())); -} - -mGuangYingPinWidget::~mGuangYingPinWidget(){ - delete ui; -} - -void mGuangYingPinWidget::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void mGuangYingPinWidget::transUi() { - ui->pushButtonSend->setText(tr("Send")); - ui->pushButtonMainOpen->setText(tr("Open")); - ui->pushButtonAuxOpen->setText(tr("Open")); - ui->pushButtonBrightnessSet->setText(tr("Set")); - ui->pushButtonScreenOn->setText(tr("Screen On")); - ui->pushButtonScreenOff->setText(tr("Screen Off")); - ui->pushButtonRefresh->setText(tr("Refresh")); - ui->groupBoxMain->setTitle(tr("Main")); - ui->groupBoxAux->setTitle(tr("Auxiliary")); - ui->groupBoxParam->setTitle(tr("Param configuration")); - ui->label_PortName->setText(tr("PortName")); - ui->label_BaudRate->setText(tr("BaudRate")); - ui->label_DataBit->setText(tr("DataBit")); - ui->label_OEBit->setText(tr("OEBit")); - ui->label_StopBit->setText(tr("StopBit")); - ui->label_PortNameAux->setText(tr("PortName")); - ui->label_BaudRateAux->setText(tr("BaudRate")); - ui->label_DataBitAux->setText(tr("DataBit")); - ui->label_OEBitAux->setText(tr("OEBit")); - ui->label_StopBitAux->setText(tr("StopBit")); - - ui->label_ResendTimes->setText(tr("Resend times")); - ui->label_DelayMill->setText(tr("Delay millsecond")); - ui->label_ProgramNum->setText(tr("Program number")); - ui->label_BrightNess->setText(tr("Brightness")); - ui->label_ComStatus->setText(tr("State:Off")); - ui->label_ComStatusAux->setText(tr("State:Off")); - ui->pushButtonClearLog->setText(tr("Clear")); - ui->checkBoxDebug->setText(tr("Debug")); - ui->groupBox_Network->setTitle(tr("Network")); - ui->groupBox_com->setTitle(tr("Com")); -} - -void mGuangYingPinWidget::OnAnsyProgram1(void) -{ - MACRO_ANSY_PROGRAM(1) -} -void mGuangYingPinWidget::OnAnsyProgram2(void) -{ - MACRO_ANSY_PROGRAM(2) - -}void mGuangYingPinWidget::OnAnsyProgram3(void) -{ - MACRO_ANSY_PROGRAM(3) -}void mGuangYingPinWidget::OnAnsyProgram4(void) -{ - MACRO_ANSY_PROGRAM(4) -}void mGuangYingPinWidget::OnAnsyProgram5(void) -{ - MACRO_ANSY_PROGRAM(5) -}void mGuangYingPinWidget::OnAnsyProgram6(void) -{ - MACRO_ANSY_PROGRAM(6) -}void mGuangYingPinWidget::OnAnsyProgram7(void) -{ - MACRO_ANSY_PROGRAM(7) -}void mGuangYingPinWidget::OnAnsyProgram8(void) -{ - MACRO_ANSY_PROGRAM(8) -}void mGuangYingPinWidget::OnAnsyProgram9(void) -{ - MACRO_ANSY_PROGRAM(9) -}void mGuangYingPinWidget::OnAnsyProgram10(void) -{ - MACRO_ANSY_PROGRAM(10) -}void mGuangYingPinWidget::OnAnsyProgram11(void) -{ - MACRO_ANSY_PROGRAM(11) -}void mGuangYingPinWidget::OnAnsyProgram12(void) -{ - MACRO_ANSY_PROGRAM(12) -}void mGuangYingPinWidget::OnAnsyProgram13(void) -{ - MACRO_ANSY_PROGRAM(13) -}void mGuangYingPinWidget::OnAnsyProgram14(void) -{ - MACRO_ANSY_PROGRAM(14) -}void mGuangYingPinWidget::OnAnsyProgram15(void) -{ - MACRO_ANSY_PROGRAM(15) -}void mGuangYingPinWidget::OnAnsyProgram16(void) -{ - MACRO_ANSY_PROGRAM(16) -}void mGuangYingPinWidget::OnAnsyProgram17(void) -{ - MACRO_ANSY_PROGRAM(17) -}void mGuangYingPinWidget::OnAnsyProgram18(void) -{ - MACRO_ANSY_PROGRAM(18) -}void mGuangYingPinWidget::OnAnsyProgram19(void) -{ - MACRO_ANSY_PROGRAM(19) -} -void mGuangYingPinWidget::OnAnsyProgram20(void) -{ - MACRO_ANSY_PROGRAM(20) -} -void mGuangYingPinWidget::OnClearLog(void) -{ - ui->textEditReadBuf->clear(); -} -void mGuangYingPinWidget::OnAnsyProgramCustom(void) -{ - int itemp=ui->spinBox_ProgramIndex->value(); - MACRO_ANSY_PROGRAM(itemp) - - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("OnAnsyProgramCustom"); - } -} -void mGuangYingPinWidget::OnAnsyProgramCustomByChanged(int icurIndex) -{ - MACRO_ANSY_PROGRAM(icurIndex) -} -void mGuangYingPinWidget::OnBrightnessSetByChanged(int icurValue) -{ - if(ui->pushButtonMainOpen->text()==tr("Close")) - Set_Brightness_buf_and_send(ui->comboBox_SPortName->currentIndex(),icurValue); - if(ui->pushButtonAuxOpen->text()==tr("Close")) - Set_Brightness_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),icurValue); - } - -void mGuangYingPinWidget::OnAnsyProgramNext(void) -{ - ui->spinBox_ProgramIndex->setValue(ui->spinBox_ProgramIndex->value()+1); - OnAnsyProgramCustom(); -// int itemp=ui->spinBox_ProgramIndex->value(); -// MACRO_ANSY_PROGRAM(itemp) -// if(ui->pushButtonMainOpen->text()==tr("Close")) -// NextProgram_buf_and_send(ui->comboBox_SPortName->currentIndex()); -// if(ui->pushButtonAuxOpen->text()==tr("Close")) -// NextProgram_buf_and_send(ui->comboBox_SPortNameAux->currentIndex()); - -} -void mGuangYingPinWidget::OnAnsyProgramPrevious(void) -{ - ui->spinBox_ProgramIndex->setValue(ui->spinBox_ProgramIndex->value()-1); - OnAnsyProgramCustom(); -// int itemp=ui->spinBox_ProgramIndex->value(); -// MACRO_ANSY_PROGRAM(itemp) -} -void mGuangYingPinWidget::OnAnsyProgramLoop(void) -{ - MACRO_ANSY_PROGRAM(0) -} -void mGuangYingPinWidget::OnBrightnessSet(void) -{ - if(ui->groupBox_com->isChecked()) - { - if(ui->pushButtonMainOpen->text()==tr("Close")) - Set_Brightness_buf_and_send(ui->comboBox_SPortName->currentIndex(),ui->spinBox_BrightnessValue->value()); - if(ui->pushButtonAuxOpen->text()==tr("Close")) - Set_Brightness_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),ui->spinBox_BrightnessValue->value()); - } - - if(ui->groupBox_Network->isChecked()) - { - Set_Brightness_buf_and_send_by_udp(ui->spinBox_BrightnessValue->value()); - } -} -void mGuangYingPinWidget::OnScreenOn(void) -{ - if(ui->groupBox_com->isChecked()) - { - if(ui->pushButtonMainOpen->text()==tr("Close")) - Screen_OnOff_buf_and_send(ui->comboBox_SPortName->currentIndex(),0x11); - if(ui->pushButtonAuxOpen->text()==tr("Close")) - Screen_OnOff_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),0x11); - } - if(ui->groupBox_Network->isChecked()) - { - Screen_OnOff_buf_and_send_by_udp(0x11); - } -} -void mGuangYingPinWidget::OnScreenOff(void) -{ - if(ui->groupBox_com->isChecked()) - { - if(ui->pushButtonMainOpen->text()==tr("Close")) - Screen_OnOff_buf_and_send(ui->comboBox_SPortName->currentIndex(),0x10); - if(ui->pushButtonAuxOpen->text()==tr("Close")) - Screen_OnOff_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),0x10); - } - if(ui->groupBox_Network->isChecked()) - { - Screen_OnOff_buf_and_send_by_udp(0x10); - - } -} -void mGuangYingPinWidget::OnRefresh() -{ - bool resetAllComboxFlag=true; - if(ui->comboBox_SPortName->count()>0) - resetAllComboxFlag=false; -// ui->comboBox_SPortName->clear(); -// ui->comboBox_SPortNameAux->clear(); - - sPortThread->SearchPort(); -// for (int m=0;mportCnt;m++) { - -// } - - - for(uint8_t i = 0;i < sPortThread->portCnt;i++) - { - bool iHaveFlag=false; - for(int j=0;jcomboBox_SPortName->count();j++) - { - if(ui->comboBox_SPortName->itemText(j)==sPortThread->m_arrSerial[i].portName()) - { - iHaveFlag=true; - break; - } - } - if(iHaveFlag==false) - { - ui->comboBox_SPortName->addItem(sPortThread->m_arrSerial[i].portName()); - } - bool iHaveAuxFlag=false; - for(int jj=0;jjcomboBox_SPortNameAux->count();jj++) - { - if(ui->comboBox_SPortNameAux->itemText(jj)==sPortThread->m_arrSerial[i].portName()) - { - iHaveAuxFlag=true; - break; - } - } - if(iHaveAuxFlag==false) - { - ui->comboBox_SPortNameAux->addItem(sPortThread->m_arrSerial[i].portName()); - if(ui->comboBox_SPortNameAux->count()>1&&ui->pushButtonAuxOpen->text()==tr("Open")) - { - ui->comboBox_SPortNameAux->setCurrentIndex(i); - } - - } -// ui->comboBox_SPortName->addItem(sPortThread->m_arrSerial[i].portName()); -// ui->comboBox_SPortNameAux->addItem(sPortThread->m_arrSerial[i].portName()); - } - - if(resetAllComboxFlag) - { - //0:1200 1:2400 2:4800 3:9600 4:19200 5:38400 6:57600 7:115200 - if(ui->comboBox_SPortName->count()>=1) - { - ui->comboBox_SPortBaud->setCurrentIndex(3); - //0:5 1:6 2:7 3:8 - ui->comboBox_SPortDataBit->setCurrentIndex(3); - //0:no p 2:e p 3:o p 4:s p 5:m p - ui->comboBox_SPortOEBit->setCurrentIndex(0); - //0:1 1:2 2:1.5 - ui->comboBox_SPortStopBit->setCurrentIndex(0); - - ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(255, 0, 0);"); - ui->label_ComStatus->setText(tr("State:Off")); - - ui->comboBox_SPortBaudAux->setCurrentIndex(3); - ui->comboBox_SPortDataBitAux->setCurrentIndex(3); - ui->comboBox_SPortOEBitAux->setCurrentIndex(0); - ui->comboBox_SPortStopBitAux->setCurrentIndex(0); - ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(255, 0, 0);"); - ui->label_ComStatusAux->setText(tr("State:Off")); - if(ui->comboBox_SPortName->count()>1) - { - ui->comboBox_SPortNameAux->setCurrentIndex(1); - } - } - - } - -} -void mGuangYingPinWidget::MWOnoffPort(void) -{ - uint8_t comIndex = ui->comboBox_SPortName->currentIndex(); - - if(ui->pushButtonMainOpen->text()==tr("Open")) - { - sPortThread->InitPortName(comIndex,ui->comboBox_SPortName->currentText()); - sPortThread->InitPortBaudRate(comIndex,ui->comboBox_SPortBaud->currentText().toInt()); - - //qDebug()<comboBox_SPortDataBit->currentIndex(); - switch(ui->comboBox_SPortDataBit->currentIndex()) - { - case 0: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data5); break;//0:5 - case 1: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data6); break;//1:6 - case 2: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data7); break;//2:7 - case 3: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data8); break;//3:8 - default: break; - } - - switch(ui->comboBox_SPortStopBit->currentIndex()) - { - case 0:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneStop);break; - case 1:sPortThread->InitPortStopBits(comIndex,QSerialPort::TwoStop);break; - case 2:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneAndHalfStop);break; - default: break; - } - - switch(ui->comboBox_SPortOEBit->currentIndex()) - { - case 0:sPortThread->InitPortParity(comIndex,QSerialPort::NoParity);break; - case 1:sPortThread->InitPortParity(comIndex,QSerialPort::EvenParity);break; - case 2:sPortThread->InitPortParity(comIndex,QSerialPort::OddParity);break; - case 3:sPortThread->InitPortParity(comIndex,QSerialPort::SpaceParity);break; - case 4:sPortThread->InitPortParity(comIndex,QSerialPort::MarkParity);break; - default: break; - } - if(sPortThread->OpenPort(comIndex)) - { - connect(&(sPortThread->m_arrSerial[comIndex]), SIGNAL(readyRead()), this, SLOT(MWReadData())); - - //参数设置禁止 - ui->comboBox_SPortName->setEnabled(false); - ui->comboBox_SPortBaud->setEnabled(false); - ui->comboBox_SPortDataBit->setEnabled(false); - ui->comboBox_SPortOEBit->setEnabled(false); - ui->comboBox_SPortStopBit->setEnabled(false); - ui->pushButtonMainOpen->setText(tr("Close")); - //发送设置使能 - ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(0, 255, 0);"); - ui->label_ComStatus->setText(tr("State:On")); - } - else { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("OpenPort COM failed"),this,1); - pDlg->exec(); - } - - - } - else - { - sPortThread->ClosePort(comIndex); - //参数设置使能 - ui->comboBox_SPortName->setEnabled(true); - ui->comboBox_SPortBaud->setEnabled(true); - ui->comboBox_SPortDataBit->setEnabled(true); - ui->comboBox_SPortOEBit->setEnabled(true); - ui->comboBox_SPortStopBit->setEnabled(true); - ui->pushButtonMainOpen->setText(tr("Open")); - //发送设置禁止 - ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(255, 0, 0);"); - ui->label_ComStatus->setText(tr("State:Off")); - } -} -void mGuangYingPinWidget::MWOnoffPortAux(void) -{ - uint8_t comIndex = ui->comboBox_SPortNameAux->currentIndex(); - - if(ui->pushButtonAuxOpen->text()==tr("Open")) - { - sPortThread->InitPortName(comIndex,ui->comboBox_SPortNameAux->currentText()); - sPortThread->InitPortBaudRate(comIndex,ui->comboBox_SPortBaudAux->currentText().toInt()); - - //qDebug()<comboBox_SPortDataBit->currentIndex(); - switch(ui->comboBox_SPortDataBitAux->currentIndex()) - { - case 0: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data5); break;//0:5 - case 1: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data6); break;//1:6 - case 2: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data7); break;//2:7 - case 3: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data8); break;//3:8 - default: break; - } - - switch(ui->comboBox_SPortStopBitAux->currentIndex()) - { - case 0:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneStop);break; - case 1:sPortThread->InitPortStopBits(comIndex,QSerialPort::TwoStop);break; - case 2:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneAndHalfStop);break; - default: break; - } - - switch(ui->comboBox_SPortOEBitAux->currentIndex()) - { - case 0:sPortThread->InitPortParity(comIndex,QSerialPort::NoParity);break; - case 1:sPortThread->InitPortParity(comIndex,QSerialPort::EvenParity);break; - case 2:sPortThread->InitPortParity(comIndex,QSerialPort::OddParity);break; - case 3:sPortThread->InitPortParity(comIndex,QSerialPort::SpaceParity);break; - case 4:sPortThread->InitPortParity(comIndex,QSerialPort::MarkParity);break; - default: break; - } - if(sPortThread->OpenPort(comIndex)) - { - connect(&(sPortThread->m_arrSerial[comIndex]), SIGNAL(readyRead()), this, SLOT(MWReadDataAux())); - - //参数设置禁止 - ui->comboBox_SPortNameAux->setEnabled(false); - ui->comboBox_SPortBaudAux->setEnabled(false); - ui->comboBox_SPortDataBitAux->setEnabled(false); - ui->comboBox_SPortOEBitAux->setEnabled(false); - ui->comboBox_SPortStopBitAux->setEnabled(false); - ui->pushButtonAuxOpen->setText(tr("Close")); - //发送设置使能 - ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(0, 255, 0);"); - ui->label_ComStatusAux->setText(tr("State:On")); - - } - else { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("OpenPort COM failed"),this,1); - pDlg->exec(); - - } - - } - else - { - sPortThread->ClosePort(comIndex); - //参数设置使能 - ui->comboBox_SPortNameAux->setEnabled(true); - ui->comboBox_SPortBaudAux->setEnabled(true); - ui->comboBox_SPortDataBitAux->setEnabled(true); - ui->comboBox_SPortOEBitAux->setEnabled(true); - ui->comboBox_SPortStopBitAux->setEnabled(true); - ui->pushButtonAuxOpen->setText(tr("Open")); - //发送设置禁止 - ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(255, 0, 0);"); - ui->label_ComStatusAux->setText(tr("State:Off")); - } -} -void mGuangYingPinWidget::Set_program_buf_and_send(int iComIndex,int iProgramIndex) -{ - unsigned char uctemp[3]={0}; - uctemp[0]=0x30+iProgramIndex; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - unsigned short iDelayTimes=m_uiResendTimes*m_uimillisecond; - qint64 dwStart; - qint64 dwStop; - dwStart = QDateTime::currentMSecsSinceEpoch(); - dwStop=dwStart; - for(int i=0;i<(int)m_uiResendTimes;i++) - { - int itiaozheng=dwStop-dwStart-m_uimillisecond;//时间发送间隔和参数发送间隔的差异 - if(itiaozheng<0) - itiaozheng=0; - unsigned short itemp=(iDelayTimes-i*m_uimillisecond)-itiaozheng;//补充差异,比如实际用了110毫秒,参数100毫秒,则发送过去的协议数据应该是让控制卡减少延时,所以在延时值上再减去补差 - if(itemp<0) - itemp=0; - dwStart=dwStop; - memcpy(&uctemp[1],(unsigned char *)&itemp,2*sizeof(unsigned char)); - MWSendCmd(iComIndex,0x42,uctemp,3,g_iCountCmd); - - - int itempDelay=0; - if(itiaozheng>0) - itempDelay=m_uimillisecond-itiaozheng; - else - itempDelay=m_uimillisecond; - mymidelay(itempDelay); - dwStop = QDateTime::currentMSecsSinceEpoch(); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("dwStart="+QString::number(dwStart)+",dwStop="+QString::number(dwStop)+",dwStop-dwStart="+QString::number(dwStop-dwStart)+",Delay="+QString::number(itempDelay)+",buf delay value="+QString::number(itemp)+"\r\n"); - } - } - g_iCountCmd++; - -} -void mGuangYingPinWidget::Set_program_buf_and_send_by_udp(int iProgramIndex) -{ - unsigned char uctemp[3]={0}; - uctemp[0]=0x30+iProgramIndex; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - unsigned short iDelayTimes=m_uiResendTimes*m_uimillisecond; - qint64 dwStart; - qint64 dwStop; - dwStart = QDateTime::currentMSecsSinceEpoch(); - dwStop=dwStart; - for(int i=0;i<(int)m_uiResendTimes;i++) - { - int itiaozheng=dwStop-dwStart-m_uimillisecond;//时间发送间隔和参数发送间隔的差异 - if(itiaozheng<0) - itiaozheng=0; - unsigned short itemp=(iDelayTimes-i*m_uimillisecond)-itiaozheng;//补充差异,比如实际用了110毫秒,参数100毫秒,则发送过去的协议数据应该是让控制卡减少延时,所以在延时值上再减去补差 - if(itemp<0) - itemp=0; - dwStart=dwStop; - memcpy(&uctemp[1],(unsigned char *)&itemp,2*sizeof(unsigned char)); - MWSendCmdByUdp(0x42,uctemp,3,g_iCountCmd); - - - int itempDelay=0; - if(itiaozheng>0) - itempDelay=m_uimillisecond-itiaozheng; - else - itempDelay=m_uimillisecond; - mymidelay(itempDelay); - dwStop = QDateTime::currentMSecsSinceEpoch(); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("dwStart="+QString::number(dwStart)+",dwStop="+QString::number(dwStop)+",dwStop-dwStart="+QString::number(dwStop-dwStart)+",Delay="+QString::number(itempDelay)+",buf delay value="+QString::number(itemp)+"\r\n"); - } - } - g_iCountCmd++; - -} -void mGuangYingPinWidget::Set_Brightness_buf_and_send(int iComIndex,int iBrightnessValue) -{ - unsigned char uctemp[2]={0}; - uctemp[0]=0xF1; - uctemp[1]=iBrightnessValue; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - for(int i=0;i<(int)m_uiResendTimes;i++) - { - MWSendCmd(iComIndex,0x42,uctemp,2,g_iCountCmd); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("SetBrightNess="+QString::number(iBrightnessValue)); - } - mymidelay(m_uimillisecond); - } -} -void mGuangYingPinWidget::Set_Brightness_buf_and_send_by_udp(int iBrightnessValue) -{ - unsigned char uctemp[2]={0}; - uctemp[0]=0xF1; - uctemp[1]=iBrightnessValue; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - for(int i=0;i<(int)m_uiResendTimes;i++) - { - MWSendCmdByUdp(0x42,uctemp,2,g_iCountCmd); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("SetBrightNess="+QString::number(iBrightnessValue)); - } - mymidelay(m_uimillisecond); - } -} -void mGuangYingPinWidget::Screen_OnOff_buf_and_send(int iComIndex,int iScreenOnOff) -{ - unsigned char uctemp[3]={0}; - uctemp[0]=iScreenOnOff; - uctemp[1]=0; - uctemp[2]=0; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - for(int i=0;i<(int)m_uiResendTimes;i++) - { - MWSendCmd(iComIndex,0x42,uctemp,3,g_iCountCmd); - if(ui->checkBoxDebug->isChecked()) - { - if(iScreenOnOff==0x11) - ui->textEditReadBuf->append("Screen On"); - else - ui->textEditReadBuf->append("Screen Off"); - } - mymidelay(m_uimillisecond); - } -} -void mGuangYingPinWidget::Screen_OnOff_buf_and_send_by_udp(int iScreenOnOff) -{ - unsigned char uctemp[3]={0}; - uctemp[0]=iScreenOnOff; - uctemp[1]=0; - uctemp[2]=0; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - for(int i=0;i<(int)m_uiResendTimes;i++) - { - MWSendCmdByUdp(0x42,uctemp,3,g_iCountCmd); - if(ui->checkBoxDebug->isChecked()) - { - if(iScreenOnOff==0x11) - ui->textEditReadBuf->append("Screen On"); - else - ui->textEditReadBuf->append("Screen Off"); - } - mymidelay(m_uimillisecond); - } -} -void mGuangYingPinWidget::NextProgram_buf_and_send(int iComIndex) -{ - unsigned char uctemp[1]={0}; - uctemp[0]=0xF3; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - for(int i=0;i<(int)m_uiResendTimes;i++) - { - MWSendCmd(iComIndex,0x42,uctemp,1,g_iCountCmd); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("Next Program"); - } - mymidelay(m_uimillisecond); - } -} -void mGuangYingPinWidget::NextProgram_buf_and_send_by_udp() -{ - unsigned char uctemp[1]={0}; - uctemp[0]=0xF3; - int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); - int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); - for(int i=0;i<(int)m_uiResendTimes;i++) - { - MWSendCmdByUdp(0x42,uctemp,1,g_iCountCmd); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("Next Program"); - } - mymidelay(m_uimillisecond); - } -} -void mGuangYingPinWidget::mymidelay(int imlsec) -{ - qint64 dwStart, dwStop; - dwStart = QDateTime::currentMSecsSinceEpoch(); - do{ - dwStop = QDateTime::currentMSecsSinceEpoch(); - } while(dwStop-imlsec(&tempStreadPakcet), iLenPacket); - //sPortThread->SendDataBuf(iComIndex,databuf); - - - QList networkinterfaces = QNetworkInterface::allInterfaces(); - foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表 - { - foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址,子网掩码和广播地址 - { - QHostAddress broadcastAddress("255.255.255.255"); - entry.setBroadcast(QHostAddress::Broadcast); - QUdpSocket *tempUdpSocket= new QUdpSocket(this); - if(!tempUdpSocket->bind(entry.ip())) - break; - int iSendLength=tempUdpSocket->writeDatagram((char *)&tempStreadPakcet,iLenPacket,broadcastAddress,31296); - if(iSendLength != iLenPacket) { - char *aa=reinterpret_cast(&tempStreadPakcet); - tempUdpSocket->writeDatagram(&aa[iSendLength],iLenPacket-iSendLength,broadcastAddress,31296); - } - delete tempUdpSocket; - } - } - if(ui->checkBoxDebug->isChecked()) { - ui->textEditReadBuf->append("udp:"+tr(databuf.toHex())); - } -} -void mGuangYingPinWidget::MWSendCmd(uint8_t iComIndex,unsigned char cmd,unsigned char *pUcValue,unsigned int iLength,int iCountCmd) -{ - ST_ANSY_PROGRAM_PACKET tempStreadPakcet; - tempStreadPakcet.SyncHead[0]=0x7e; - tempStreadPakcet.SyncHead[1]=0x7e; - tempStreadPakcet.SyncHead[2]=0x55; - tempStreadPakcet.ucCommType=cmd; - tempStreadPakcet.iBaoLiu=iCountCmd; - tempStreadPakcet.iLength=iLength; - memcpy(tempStreadPakcet.pDataBuffer,pUcValue,iLength); - tempStreadPakcet.pDataBuffer[tempStreadPakcet.iLength]=GetCheckCodeIn8(&tempStreadPakcet.ucCommType,tempStreadPakcet.iLength+sizeof(tempStreadPakcet.iBaoLiu)+sizeof(tempStreadPakcet.ucCommType)+sizeof(tempStreadPakcet.iLength)); - int iLenPacket=3*sizeof(unsigned char)+sizeof(char)+sizeof(int)+sizeof(int)+tempStreadPakcet.iLength+sizeof(char);/////除正文外的协议结构大小; - QByteArray databuf = QByteArray(reinterpret_cast(&tempStreadPakcet), iLenPacket); - sPortThread->SendDataBuf(iComIndex,databuf); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->append("com:"+tr(databuf.toHex())); - } -//sPortThread->SendDataBuf(ui->comboBox_SPortName->currentIndex(),ui->textEdit->toPlainText().toLatin1()); -// m_sendNum += (ui->textEdit->toPlainText().toLatin1()).length(); -// MWRSNumDisplay(); -} - -void mGuangYingPinWidget::MWReadData(void) -{ - QByteArray buf; - buf = sPortThread->GetDataBuf(ui->comboBox_SPortName->currentIndex()); - if(!buf.isEmpty()) - { - QString str = tr(buf.toHex()); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->moveCursor(QTextCursor::End); - ui->textEditReadBuf->insertPlainText(str); - } - MWRSNumDisplay(); - } - buf.clear(); -} -void mGuangYingPinWidget::MWReadDataAux(void) -{ - QByteArray buf; - buf = sPortThread->GetDataBuf(ui->comboBox_SPortNameAux->currentIndex()); - if(!buf.isEmpty()) - { - QString str = tr(buf.toHex()); - if(ui->checkBoxDebug->isChecked()) - { - ui->textEditReadBuf->moveCursor(QTextCursor::End); - ui->textEditReadBuf->insertPlainText(str); - } - MWRSNumDisplay(); - } - buf.clear(); -} -QString mGuangYingPinWidget::ByteArrayToHexString(QByteArray &ba) -{ - QDataStream out(&ba,QIODevice::ReadWrite); //将str的数据 读到out里面去 - QString buf; - while(!out.atEnd()) - { - qint8 outChar = 0; - out >> outChar; //每次一个字节的填充到 outchar - QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0')).toUpper() + QString(" "); //2 字符宽度 - buf += str; - } - return buf; -} -void mGuangYingPinWidget::MWClearRecv(void) -{ -// ui->textBrowser->clear(); -// m_recvNum = 0; -// m_sendNum = 0; -// MWRSNumDisplay(); -} - -void mGuangYingPinWidget::MWRSNumDisplay(void) -{ -// ui->label_RecvNum->setText(tr("已接收:") + QString::number(m_recvNum,10)); -// ui->label_SendNum->setText(tr("已发送:") + QString::number(m_sendNum,10)); -} +#include +#include "mguangyingpinwidget.h" +#include "ui_mguangyingpinwidget.h" +#include +#include "globaldefine.h" +mGuangYingPinWidget::mGuangYingPinWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::mGuangYingPinWidget) +{ + setAutoFillBackground(true); + QPalette pal; + pal.setBrush(QPalette::Window, QColor(0xeeeeee)); + setPalette(pal); + + ui->setupUi(this); + ui->pushButton1->setProperty("ssType", "progManageTool"); + ui->pushButton2->setProperty("ssType", "progManageTool"); + ui->pushButton3->setProperty("ssType", "progManageTool"); + ui->pushButton4->setProperty("ssType", "progManageTool"); + ui->pushButton5->setProperty("ssType", "progManageTool"); + ui->pushButton6->setProperty("ssType", "progManageTool"); + ui->pushButton7->setProperty("ssType", "progManageTool"); + ui->pushButton8->setProperty("ssType", "progManageTool"); + ui->pushButton9->setProperty("ssType", "progManageTool"); + ui->pushButton10->setProperty("ssType", "progManageTool"); + ui->pushButton11->setProperty("ssType", "progManageTool"); + ui->pushButton12->setProperty("ssType", "progManageTool"); + ui->pushButton13->setProperty("ssType", "progManageTool"); + ui->pushButton14->setProperty("ssType", "progManageTool"); + ui->pushButton15->setProperty("ssType", "progManageTool"); + ui->pushButton16->setProperty("ssType", "progManageTool"); + ui->pushButton17->setProperty("ssType", "progManageTool"); + ui->pushButton18->setProperty("ssType", "progManageTool"); + ui->pushButton19->setProperty("ssType", "progManageTool"); + ui->pushButton20->setProperty("ssType", "progManageTool"); + + ui->pushButtonSend->setProperty("ssType", "progManageTool"); + ui->pushButtonPrevious->setProperty("ssType", "progManageTool"); + ui->pushButtonPrevious->setIcon(QIcon(":/res/previous.png")); + ui->pushButtonNext->setProperty("ssType", "progManageTool"); + ui->pushButtonNext->setIcon(QIcon(":/res/next.png")); + ui->pushButtonLoop->setProperty("ssType", "progManageTool"); + ui->pushButtonLoop->setIcon(QIcon(":/res/loop.png")); + ui->pushButtonMainOpen->setProperty("ssType", "progManageTool"); + ui->pushButtonAuxOpen->setProperty("ssType", "progManageTool"); + ui->pushButtonBrightnessSet->setProperty("ssType", "progManageTool"); + ui->pushButtonScreenOn->setProperty("ssType", "progManageTool"); + ui->pushButtonScreenOff->setProperty("ssType", "progManageTool"); + ui->pushButtonRefresh->setProperty("ssType", "progManageTool"); + ui->pushButtonClearLog->setProperty("ssType", "progManageTool"); + m_recvNum = 0; + m_sendNum = 0; + sPortThread = new TA_SerialThread; + sPortThread->SearchPort(); + + for(uint8_t i = 0;i < sPortThread->portCnt;i++) + { + ui->comboBox_SPortName->addItem(sPortThread->m_arrSerial[i].portName()); + ui->comboBox_SPortNameAux->addItem(sPortThread->m_arrSerial[i].portName()); + } + + //0:1200 1:2400 2:4800 3:9600 4:19200 5:38400 6:57600 7:115200 + if(ui->comboBox_SPortName->count()>=1) + { + ui->comboBox_SPortBaud->setCurrentIndex(3); + //0:5 1:6 2:7 3:8 + ui->comboBox_SPortDataBit->setCurrentIndex(3); + //0:no p 2:e p 3:o p 4:s p 5:m p + ui->comboBox_SPortOEBit->setCurrentIndex(0); + //0:1 1:2 2:1.5 + ui->comboBox_SPortStopBit->setCurrentIndex(0); + + ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(255, 0, 0);"); + ui->label_ComStatus->setText(tr("State:Off")); + + ui->comboBox_SPortBaudAux->setCurrentIndex(3); + ui->comboBox_SPortDataBitAux->setCurrentIndex(3); + ui->comboBox_SPortOEBitAux->setCurrentIndex(0); + ui->comboBox_SPortStopBitAux->setCurrentIndex(0); + ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(255, 0, 0);"); + ui->label_ComStatusAux->setText(tr("State:Off")); + if(ui->comboBox_SPortName->count()>1) + { + ui->comboBox_SPortNameAux->setCurrentIndex(1); + } + } + ui->lineEdit_ResendTimes->setValidator(new QIntValidator(1,1000,this)); + ui->lineEdit_DelayMill->setValidator(new QIntValidator(1,1000,this)); + + + connect(ui->pushButtonMainOpen, SIGNAL(clicked(bool)), this, SLOT(MWOnoffPort())); + connect(ui->pushButtonAuxOpen, SIGNAL(clicked(bool)), this, SLOT(MWOnoffPortAux())); + connect(ui->pushButton1, SIGNAL(clicked()), this, SLOT(OnAnsyProgram1())); + connect(ui->pushButton2, SIGNAL(clicked()), this, SLOT(OnAnsyProgram2())); + connect(ui->pushButton3, SIGNAL(clicked()), this, SLOT(OnAnsyProgram3())); + connect(ui->pushButton4, SIGNAL(clicked()), this, SLOT(OnAnsyProgram4())); + connect(ui->pushButton5, SIGNAL(clicked()), this, SLOT(OnAnsyProgram5())); + connect(ui->pushButton6, SIGNAL(clicked()), this, SLOT(OnAnsyProgram6())); + connect(ui->pushButton7, SIGNAL(clicked()), this, SLOT(OnAnsyProgram7())); + connect(ui->pushButton8, SIGNAL(clicked()), this, SLOT(OnAnsyProgram8())); + connect(ui->pushButton9, SIGNAL(clicked()), this, SLOT(OnAnsyProgram9())); + connect(ui->pushButton10, SIGNAL(clicked()), this, SLOT(OnAnsyProgram10())); + connect(ui->pushButton11, SIGNAL(clicked()), this, SLOT(OnAnsyProgram11())); + connect(ui->pushButton12, SIGNAL(clicked()), this, SLOT(OnAnsyProgram12())); + connect(ui->pushButton13, SIGNAL(clicked()), this, SLOT(OnAnsyProgram13())); + connect(ui->pushButton14, SIGNAL(clicked()), this, SLOT(OnAnsyProgram14())); + connect(ui->pushButton15, SIGNAL(clicked()), this, SLOT(OnAnsyProgram15())); + connect(ui->pushButton16, SIGNAL(clicked()), this, SLOT(OnAnsyProgram16())); + connect(ui->pushButton17, SIGNAL(clicked()), this, SLOT(OnAnsyProgram17())); + connect(ui->pushButton18, SIGNAL(clicked()), this, SLOT(OnAnsyProgram18())); + connect(ui->pushButton19, SIGNAL(clicked()), this, SLOT(OnAnsyProgram19())); + connect(ui->pushButton20, SIGNAL(clicked()), this, SLOT(OnAnsyProgram20())); + connect(ui->pushButtonClearLog, SIGNAL(clicked()), this, SLOT(OnClearLog())); + connect(ui->pushButtonSend, SIGNAL(clicked()), this, SLOT(OnAnsyProgramCustom())); + connect(ui->pushButtonNext, SIGNAL(clicked()), this, SLOT(OnAnsyProgramNext())); + connect(ui->pushButtonPrevious, SIGNAL(clicked()), this, SLOT(OnAnsyProgramPrevious())); + connect(ui->pushButtonLoop, SIGNAL(clicked()), this, SLOT(OnAnsyProgramLoop())); + connect(ui->pushButtonBrightnessSet, SIGNAL(clicked()), this, SLOT(OnBrightnessSet())); + connect(ui->pushButtonScreenOn, SIGNAL(clicked()), this, SLOT(OnScreenOn())); + connect(ui->pushButtonScreenOff, SIGNAL(clicked()), this, SLOT(OnScreenOff())); + connect(ui->spinBox_ProgramIndex, SIGNAL(valueChanged(int)), this, SLOT(OnAnsyProgramCustomByChanged(int))); + connect(ui->spinBox_BrightnessValue, SIGNAL(valueChanged(int)), this, SLOT(OnBrightnessSetByChanged(int))); + connect(ui->pushButtonRefresh, SIGNAL(clicked()), this, SLOT(OnRefresh())); +} + +mGuangYingPinWidget::~mGuangYingPinWidget(){ + delete ui; +} + +void mGuangYingPinWidget::changeEvent(QEvent *event) { + QWidget::changeEvent(event); + if(event->type() == QEvent::LanguageChange) transUi(); +} +void mGuangYingPinWidget::transUi() { + ui->pushButtonSend->setText(tr("Send")); + ui->pushButtonMainOpen->setText(tr("Open")); + ui->pushButtonAuxOpen->setText(tr("Open")); + ui->pushButtonBrightnessSet->setText(tr("Set")); + ui->pushButtonScreenOn->setText(tr("Screen On")); + ui->pushButtonScreenOff->setText(tr("Screen Off")); + ui->pushButtonRefresh->setText(tr("Refresh")); + ui->groupBoxMain->setTitle(tr("Main")); + ui->groupBoxAux->setTitle(tr("Auxiliary")); + ui->groupBoxParam->setTitle(tr("Param configuration")); + ui->label_PortName->setText(tr("PortName")); + ui->label_BaudRate->setText(tr("BaudRate")); + ui->label_DataBit->setText(tr("DataBit")); + ui->label_OEBit->setText(tr("OEBit")); + ui->label_StopBit->setText(tr("StopBit")); + ui->label_PortNameAux->setText(tr("PortName")); + ui->label_BaudRateAux->setText(tr("BaudRate")); + ui->label_DataBitAux->setText(tr("DataBit")); + ui->label_OEBitAux->setText(tr("OEBit")); + ui->label_StopBitAux->setText(tr("StopBit")); + + ui->label_ResendTimes->setText(tr("Resend times")); + ui->label_DelayMill->setText(tr("Delay millsecond")); + ui->label_ProgramNum->setText(tr("Program number")); + ui->label_BrightNess->setText(tr("Brightness")); + ui->label_ComStatus->setText(tr("State:Off")); + ui->label_ComStatusAux->setText(tr("State:Off")); + ui->pushButtonClearLog->setText(tr("Clear")); + ui->checkBoxDebug->setText(tr("Debug")); + ui->groupBox_Network->setTitle(tr("Network")); + ui->groupBox_com->setTitle(tr("Com")); +} + +void mGuangYingPinWidget::OnAnsyProgram1(void) +{ + MACRO_ANSY_PROGRAM(1) +} +void mGuangYingPinWidget::OnAnsyProgram2(void) +{ + MACRO_ANSY_PROGRAM(2) + +}void mGuangYingPinWidget::OnAnsyProgram3(void) +{ + MACRO_ANSY_PROGRAM(3) +}void mGuangYingPinWidget::OnAnsyProgram4(void) +{ + MACRO_ANSY_PROGRAM(4) +}void mGuangYingPinWidget::OnAnsyProgram5(void) +{ + MACRO_ANSY_PROGRAM(5) +}void mGuangYingPinWidget::OnAnsyProgram6(void) +{ + MACRO_ANSY_PROGRAM(6) +}void mGuangYingPinWidget::OnAnsyProgram7(void) +{ + MACRO_ANSY_PROGRAM(7) +}void mGuangYingPinWidget::OnAnsyProgram8(void) +{ + MACRO_ANSY_PROGRAM(8) +}void mGuangYingPinWidget::OnAnsyProgram9(void) +{ + MACRO_ANSY_PROGRAM(9) +}void mGuangYingPinWidget::OnAnsyProgram10(void) +{ + MACRO_ANSY_PROGRAM(10) +}void mGuangYingPinWidget::OnAnsyProgram11(void) +{ + MACRO_ANSY_PROGRAM(11) +}void mGuangYingPinWidget::OnAnsyProgram12(void) +{ + MACRO_ANSY_PROGRAM(12) +}void mGuangYingPinWidget::OnAnsyProgram13(void) +{ + MACRO_ANSY_PROGRAM(13) +}void mGuangYingPinWidget::OnAnsyProgram14(void) +{ + MACRO_ANSY_PROGRAM(14) +}void mGuangYingPinWidget::OnAnsyProgram15(void) +{ + MACRO_ANSY_PROGRAM(15) +}void mGuangYingPinWidget::OnAnsyProgram16(void) +{ + MACRO_ANSY_PROGRAM(16) +}void mGuangYingPinWidget::OnAnsyProgram17(void) +{ + MACRO_ANSY_PROGRAM(17) +}void mGuangYingPinWidget::OnAnsyProgram18(void) +{ + MACRO_ANSY_PROGRAM(18) +}void mGuangYingPinWidget::OnAnsyProgram19(void) +{ + MACRO_ANSY_PROGRAM(19) +} +void mGuangYingPinWidget::OnAnsyProgram20(void) +{ + MACRO_ANSY_PROGRAM(20) +} +void mGuangYingPinWidget::OnClearLog(void) +{ + ui->textEditReadBuf->clear(); +} +void mGuangYingPinWidget::OnAnsyProgramCustom(void) +{ + int itemp=ui->spinBox_ProgramIndex->value(); + MACRO_ANSY_PROGRAM(itemp) + + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("OnAnsyProgramCustom"); + } +} +void mGuangYingPinWidget::OnAnsyProgramCustomByChanged(int icurIndex) +{ + MACRO_ANSY_PROGRAM(icurIndex) +} +void mGuangYingPinWidget::OnBrightnessSetByChanged(int icurValue) +{ + if(ui->pushButtonMainOpen->text()==tr("Close")) + Set_Brightness_buf_and_send(ui->comboBox_SPortName->currentIndex(),icurValue); + if(ui->pushButtonAuxOpen->text()==tr("Close")) + Set_Brightness_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),icurValue); + } + +void mGuangYingPinWidget::OnAnsyProgramNext(void) +{ + ui->spinBox_ProgramIndex->setValue(ui->spinBox_ProgramIndex->value()+1); + OnAnsyProgramCustom(); +// int itemp=ui->spinBox_ProgramIndex->value(); +// MACRO_ANSY_PROGRAM(itemp) +// if(ui->pushButtonMainOpen->text()==tr("Close")) +// NextProgram_buf_and_send(ui->comboBox_SPortName->currentIndex()); +// if(ui->pushButtonAuxOpen->text()==tr("Close")) +// NextProgram_buf_and_send(ui->comboBox_SPortNameAux->currentIndex()); + +} +void mGuangYingPinWidget::OnAnsyProgramPrevious(void) +{ + ui->spinBox_ProgramIndex->setValue(ui->spinBox_ProgramIndex->value()-1); + OnAnsyProgramCustom(); +// int itemp=ui->spinBox_ProgramIndex->value(); +// MACRO_ANSY_PROGRAM(itemp) +} +void mGuangYingPinWidget::OnAnsyProgramLoop(void) +{ + MACRO_ANSY_PROGRAM(0) +} +void mGuangYingPinWidget::OnBrightnessSet(void) +{ + if(ui->groupBox_com->isChecked()) + { + if(ui->pushButtonMainOpen->text()==tr("Close")) + Set_Brightness_buf_and_send(ui->comboBox_SPortName->currentIndex(),ui->spinBox_BrightnessValue->value()); + if(ui->pushButtonAuxOpen->text()==tr("Close")) + Set_Brightness_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),ui->spinBox_BrightnessValue->value()); + } + + if(ui->groupBox_Network->isChecked()) + { + Set_Brightness_buf_and_send_by_udp(ui->spinBox_BrightnessValue->value()); + } +} +void mGuangYingPinWidget::OnScreenOn(void) +{ + if(ui->groupBox_com->isChecked()) + { + if(ui->pushButtonMainOpen->text()==tr("Close")) + Screen_OnOff_buf_and_send(ui->comboBox_SPortName->currentIndex(),0x11); + if(ui->pushButtonAuxOpen->text()==tr("Close")) + Screen_OnOff_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),0x11); + } + if(ui->groupBox_Network->isChecked()) + { + Screen_OnOff_buf_and_send_by_udp(0x11); + } +} +void mGuangYingPinWidget::OnScreenOff(void) +{ + if(ui->groupBox_com->isChecked()) + { + if(ui->pushButtonMainOpen->text()==tr("Close")) + Screen_OnOff_buf_and_send(ui->comboBox_SPortName->currentIndex(),0x10); + if(ui->pushButtonAuxOpen->text()==tr("Close")) + Screen_OnOff_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),0x10); + } + if(ui->groupBox_Network->isChecked()) + { + Screen_OnOff_buf_and_send_by_udp(0x10); + + } +} +void mGuangYingPinWidget::OnRefresh() +{ + bool resetAllComboxFlag=true; + if(ui->comboBox_SPortName->count()>0) + resetAllComboxFlag=false; +// ui->comboBox_SPortName->clear(); +// ui->comboBox_SPortNameAux->clear(); + + sPortThread->SearchPort(); +// for (int m=0;mportCnt;m++) { + +// } + + + for(uint8_t i = 0;i < sPortThread->portCnt;i++) + { + bool iHaveFlag=false; + for(int j=0;jcomboBox_SPortName->count();j++) + { + if(ui->comboBox_SPortName->itemText(j)==sPortThread->m_arrSerial[i].portName()) + { + iHaveFlag=true; + break; + } + } + if(iHaveFlag==false) + { + ui->comboBox_SPortName->addItem(sPortThread->m_arrSerial[i].portName()); + } + bool iHaveAuxFlag=false; + for(int jj=0;jjcomboBox_SPortNameAux->count();jj++) + { + if(ui->comboBox_SPortNameAux->itemText(jj)==sPortThread->m_arrSerial[i].portName()) + { + iHaveAuxFlag=true; + break; + } + } + if(iHaveAuxFlag==false) + { + ui->comboBox_SPortNameAux->addItem(sPortThread->m_arrSerial[i].portName()); + if(ui->comboBox_SPortNameAux->count()>1&&ui->pushButtonAuxOpen->text()==tr("Open")) + { + ui->comboBox_SPortNameAux->setCurrentIndex(i); + } + + } +// ui->comboBox_SPortName->addItem(sPortThread->m_arrSerial[i].portName()); +// ui->comboBox_SPortNameAux->addItem(sPortThread->m_arrSerial[i].portName()); + } + + if(resetAllComboxFlag) + { + //0:1200 1:2400 2:4800 3:9600 4:19200 5:38400 6:57600 7:115200 + if(ui->comboBox_SPortName->count()>=1) + { + ui->comboBox_SPortBaud->setCurrentIndex(3); + //0:5 1:6 2:7 3:8 + ui->comboBox_SPortDataBit->setCurrentIndex(3); + //0:no p 2:e p 3:o p 4:s p 5:m p + ui->comboBox_SPortOEBit->setCurrentIndex(0); + //0:1 1:2 2:1.5 + ui->comboBox_SPortStopBit->setCurrentIndex(0); + + ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(255, 0, 0);"); + ui->label_ComStatus->setText(tr("State:Off")); + + ui->comboBox_SPortBaudAux->setCurrentIndex(3); + ui->comboBox_SPortDataBitAux->setCurrentIndex(3); + ui->comboBox_SPortOEBitAux->setCurrentIndex(0); + ui->comboBox_SPortStopBitAux->setCurrentIndex(0); + ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(255, 0, 0);"); + ui->label_ComStatusAux->setText(tr("State:Off")); + if(ui->comboBox_SPortName->count()>1) + { + ui->comboBox_SPortNameAux->setCurrentIndex(1); + } + } + + } + +} +void mGuangYingPinWidget::MWOnoffPort(void) +{ + uint8_t comIndex = ui->comboBox_SPortName->currentIndex(); + + if(ui->pushButtonMainOpen->text()==tr("Open")) + { + sPortThread->InitPortName(comIndex,ui->comboBox_SPortName->currentText()); + sPortThread->InitPortBaudRate(comIndex,ui->comboBox_SPortBaud->currentText().toInt()); + + //qDebug()<comboBox_SPortDataBit->currentIndex(); + switch(ui->comboBox_SPortDataBit->currentIndex()) + { + case 0: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data5); break;//0:5 + case 1: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data6); break;//1:6 + case 2: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data7); break;//2:7 + case 3: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data8); break;//3:8 + default: break; + } + + switch(ui->comboBox_SPortStopBit->currentIndex()) + { + case 0:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneStop);break; + case 1:sPortThread->InitPortStopBits(comIndex,QSerialPort::TwoStop);break; + case 2:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneAndHalfStop);break; + default: break; + } + + switch(ui->comboBox_SPortOEBit->currentIndex()) + { + case 0:sPortThread->InitPortParity(comIndex,QSerialPort::NoParity);break; + case 1:sPortThread->InitPortParity(comIndex,QSerialPort::EvenParity);break; + case 2:sPortThread->InitPortParity(comIndex,QSerialPort::OddParity);break; + case 3:sPortThread->InitPortParity(comIndex,QSerialPort::SpaceParity);break; + case 4:sPortThread->InitPortParity(comIndex,QSerialPort::MarkParity);break; + default: break; + } + if(sPortThread->OpenPort(comIndex)) + { + connect(&(sPortThread->m_arrSerial[comIndex]), SIGNAL(readyRead()), this, SLOT(MWReadData())); + + //参数设置禁止 + ui->comboBox_SPortName->setEnabled(false); + ui->comboBox_SPortBaud->setEnabled(false); + ui->comboBox_SPortDataBit->setEnabled(false); + ui->comboBox_SPortOEBit->setEnabled(false); + ui->comboBox_SPortStopBit->setEnabled(false); + ui->pushButtonMainOpen->setText(tr("Close")); + //发送设置使能 + ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(0, 255, 0);"); + ui->label_ComStatus->setText(tr("State:On")); + } + else { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("OpenPort COM failed"),this,1); + pDlg->exec(); + } + + + } + else + { + sPortThread->ClosePort(comIndex); + //参数设置使能 + ui->comboBox_SPortName->setEnabled(true); + ui->comboBox_SPortBaud->setEnabled(true); + ui->comboBox_SPortDataBit->setEnabled(true); + ui->comboBox_SPortOEBit->setEnabled(true); + ui->comboBox_SPortStopBit->setEnabled(true); + ui->pushButtonMainOpen->setText(tr("Open")); + //发送设置禁止 + ui->graphicsView_ComStatus->setStyleSheet("background-color: rgb(255, 0, 0);"); + ui->label_ComStatus->setText(tr("State:Off")); + } +} +void mGuangYingPinWidget::MWOnoffPortAux(void) +{ + uint8_t comIndex = ui->comboBox_SPortNameAux->currentIndex(); + + if(ui->pushButtonAuxOpen->text()==tr("Open")) + { + sPortThread->InitPortName(comIndex,ui->comboBox_SPortNameAux->currentText()); + sPortThread->InitPortBaudRate(comIndex,ui->comboBox_SPortBaudAux->currentText().toInt()); + + //qDebug()<comboBox_SPortDataBit->currentIndex(); + switch(ui->comboBox_SPortDataBitAux->currentIndex()) + { + case 0: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data5); break;//0:5 + case 1: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data6); break;//1:6 + case 2: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data7); break;//2:7 + case 3: sPortThread->InitPortDataBits(comIndex,QSerialPort::Data8); break;//3:8 + default: break; + } + + switch(ui->comboBox_SPortStopBitAux->currentIndex()) + { + case 0:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneStop);break; + case 1:sPortThread->InitPortStopBits(comIndex,QSerialPort::TwoStop);break; + case 2:sPortThread->InitPortStopBits(comIndex,QSerialPort::OneAndHalfStop);break; + default: break; + } + + switch(ui->comboBox_SPortOEBitAux->currentIndex()) + { + case 0:sPortThread->InitPortParity(comIndex,QSerialPort::NoParity);break; + case 1:sPortThread->InitPortParity(comIndex,QSerialPort::EvenParity);break; + case 2:sPortThread->InitPortParity(comIndex,QSerialPort::OddParity);break; + case 3:sPortThread->InitPortParity(comIndex,QSerialPort::SpaceParity);break; + case 4:sPortThread->InitPortParity(comIndex,QSerialPort::MarkParity);break; + default: break; + } + if(sPortThread->OpenPort(comIndex)) + { + connect(&(sPortThread->m_arrSerial[comIndex]), SIGNAL(readyRead()), this, SLOT(MWReadDataAux())); + + //参数设置禁止 + ui->comboBox_SPortNameAux->setEnabled(false); + ui->comboBox_SPortBaudAux->setEnabled(false); + ui->comboBox_SPortDataBitAux->setEnabled(false); + ui->comboBox_SPortOEBitAux->setEnabled(false); + ui->comboBox_SPortStopBitAux->setEnabled(false); + ui->pushButtonAuxOpen->setText(tr("Close")); + //发送设置使能 + ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(0, 255, 0);"); + ui->label_ComStatusAux->setText(tr("State:On")); + + } + else { + X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("OpenPort COM failed"),this,1); + pDlg->exec(); + + } + + } + else + { + sPortThread->ClosePort(comIndex); + //参数设置使能 + ui->comboBox_SPortNameAux->setEnabled(true); + ui->comboBox_SPortBaudAux->setEnabled(true); + ui->comboBox_SPortDataBitAux->setEnabled(true); + ui->comboBox_SPortOEBitAux->setEnabled(true); + ui->comboBox_SPortStopBitAux->setEnabled(true); + ui->pushButtonAuxOpen->setText(tr("Open")); + //发送设置禁止 + ui->graphicsView_ComStatusAux->setStyleSheet("background-color: rgb(255, 0, 0);"); + ui->label_ComStatusAux->setText(tr("State:Off")); + } +} +void mGuangYingPinWidget::Set_program_buf_and_send(int iComIndex,int iProgramIndex) +{ + unsigned char uctemp[3]={0}; + uctemp[0]=0x30+iProgramIndex; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + unsigned short iDelayTimes=m_uiResendTimes*m_uimillisecond; + qint64 dwStart; + qint64 dwStop; + dwStart = QDateTime::currentMSecsSinceEpoch(); + dwStop=dwStart; + for(int i=0;i<(int)m_uiResendTimes;i++) + { + int itiaozheng=dwStop-dwStart-m_uimillisecond;//时间发送间隔和参数发送间隔的差异 + if(itiaozheng<0) + itiaozheng=0; + unsigned short itemp=(iDelayTimes-i*m_uimillisecond)-itiaozheng;//补充差异,比如实际用了110毫秒,参数100毫秒,则发送过去的协议数据应该是让控制卡减少延时,所以在延时值上再减去补差 + if(itemp<0) + itemp=0; + dwStart=dwStop; + memcpy(&uctemp[1],(unsigned char *)&itemp,2*sizeof(unsigned char)); + MWSendCmd(iComIndex,0x42,uctemp,3,g_iCountCmd); + + + int itempDelay=0; + if(itiaozheng>0) + itempDelay=m_uimillisecond-itiaozheng; + else + itempDelay=m_uimillisecond; + mymidelay(itempDelay); + dwStop = QDateTime::currentMSecsSinceEpoch(); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("dwStart="+QString::number(dwStart)+",dwStop="+QString::number(dwStop)+",dwStop-dwStart="+QString::number(dwStop-dwStart)+",Delay="+QString::number(itempDelay)+",buf delay value="+QString::number(itemp)+"\r\n"); + } + } + g_iCountCmd++; + +} +void mGuangYingPinWidget::Set_program_buf_and_send_by_udp(int iProgramIndex) +{ + unsigned char uctemp[3]={0}; + uctemp[0]=0x30+iProgramIndex; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + unsigned short iDelayTimes=m_uiResendTimes*m_uimillisecond; + qint64 dwStart; + qint64 dwStop; + dwStart = QDateTime::currentMSecsSinceEpoch(); + dwStop=dwStart; + for(int i=0;i<(int)m_uiResendTimes;i++) + { + int itiaozheng=dwStop-dwStart-m_uimillisecond;//时间发送间隔和参数发送间隔的差异 + if(itiaozheng<0) + itiaozheng=0; + unsigned short itemp=(iDelayTimes-i*m_uimillisecond)-itiaozheng;//补充差异,比如实际用了110毫秒,参数100毫秒,则发送过去的协议数据应该是让控制卡减少延时,所以在延时值上再减去补差 + if(itemp<0) + itemp=0; + dwStart=dwStop; + memcpy(&uctemp[1],(unsigned char *)&itemp,2*sizeof(unsigned char)); + MWSendCmdByUdp(0x42,uctemp,3,g_iCountCmd); + + + int itempDelay=0; + if(itiaozheng>0) + itempDelay=m_uimillisecond-itiaozheng; + else + itempDelay=m_uimillisecond; + mymidelay(itempDelay); + dwStop = QDateTime::currentMSecsSinceEpoch(); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("dwStart="+QString::number(dwStart)+",dwStop="+QString::number(dwStop)+",dwStop-dwStart="+QString::number(dwStop-dwStart)+",Delay="+QString::number(itempDelay)+",buf delay value="+QString::number(itemp)+"\r\n"); + } + } + g_iCountCmd++; + +} +void mGuangYingPinWidget::Set_Brightness_buf_and_send(int iComIndex,int iBrightnessValue) +{ + unsigned char uctemp[2]={0}; + uctemp[0]=0xF1; + uctemp[1]=iBrightnessValue; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + for(int i=0;i<(int)m_uiResendTimes;i++) + { + MWSendCmd(iComIndex,0x42,uctemp,2,g_iCountCmd); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("SetBrightNess="+QString::number(iBrightnessValue)); + } + mymidelay(m_uimillisecond); + } +} +void mGuangYingPinWidget::Set_Brightness_buf_and_send_by_udp(int iBrightnessValue) +{ + unsigned char uctemp[2]={0}; + uctemp[0]=0xF1; + uctemp[1]=iBrightnessValue; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + for(int i=0;i<(int)m_uiResendTimes;i++) + { + MWSendCmdByUdp(0x42,uctemp,2,g_iCountCmd); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("SetBrightNess="+QString::number(iBrightnessValue)); + } + mymidelay(m_uimillisecond); + } +} +void mGuangYingPinWidget::Screen_OnOff_buf_and_send(int iComIndex,int iScreenOnOff) +{ + unsigned char uctemp[3]={0}; + uctemp[0]=iScreenOnOff; + uctemp[1]=0; + uctemp[2]=0; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + for(int i=0;i<(int)m_uiResendTimes;i++) + { + MWSendCmd(iComIndex,0x42,uctemp,3,g_iCountCmd); + if(ui->checkBoxDebug->isChecked()) + { + if(iScreenOnOff==0x11) + ui->textEditReadBuf->append("Screen On"); + else + ui->textEditReadBuf->append("Screen Off"); + } + mymidelay(m_uimillisecond); + } +} +void mGuangYingPinWidget::Screen_OnOff_buf_and_send_by_udp(int iScreenOnOff) +{ + unsigned char uctemp[3]={0}; + uctemp[0]=iScreenOnOff; + uctemp[1]=0; + uctemp[2]=0; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + for(int i=0;i<(int)m_uiResendTimes;i++) + { + MWSendCmdByUdp(0x42,uctemp,3,g_iCountCmd); + if(ui->checkBoxDebug->isChecked()) + { + if(iScreenOnOff==0x11) + ui->textEditReadBuf->append("Screen On"); + else + ui->textEditReadBuf->append("Screen Off"); + } + mymidelay(m_uimillisecond); + } +} +void mGuangYingPinWidget::NextProgram_buf_and_send(int iComIndex) +{ + unsigned char uctemp[1]={0}; + uctemp[0]=0xF3; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + for(int i=0;i<(int)m_uiResendTimes;i++) + { + MWSendCmd(iComIndex,0x42,uctemp,1,g_iCountCmd); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("Next Program"); + } + mymidelay(m_uimillisecond); + } +} +void mGuangYingPinWidget::NextProgram_buf_and_send_by_udp() +{ + unsigned char uctemp[1]={0}; + uctemp[0]=0xF3; + int m_uiResendTimes=ui->lineEdit_ResendTimes->text().toInt(); + int m_uimillisecond=ui->lineEdit_DelayMill->text().toInt(); + for(int i=0;i<(int)m_uiResendTimes;i++) + { + MWSendCmdByUdp(0x42,uctemp,1,g_iCountCmd); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("Next Program"); + } + mymidelay(m_uimillisecond); + } +} +void mGuangYingPinWidget::mymidelay(int imlsec) +{ + qint64 dwStart, dwStop; + dwStart = QDateTime::currentMSecsSinceEpoch(); + do{ + dwStop = QDateTime::currentMSecsSinceEpoch(); + } while(dwStop-imlsec(&tempStreadPakcet), iLenPacket); + //sPortThread->SendDataBuf(iComIndex,databuf); + + + QList networkinterfaces = QNetworkInterface::allInterfaces(); + foreach (QNetworkInterface interfaces, networkinterfaces) //networkinterfaces负责提供主机的IP地址和网络接口的列表 + { + foreach (QNetworkAddressEntry entry, interfaces.addressEntries())//QNetworkAddressEntry存储了一个IP地址,子网掩码和广播地址 + { + QHostAddress broadcastAddress("255.255.255.255"); + entry.setBroadcast(QHostAddress::Broadcast); + QUdpSocket *tempUdpSocket= new QUdpSocket(this); + if(!tempUdpSocket->bind(entry.ip())) + break; + int iSendLength=tempUdpSocket->writeDatagram((char *)&tempStreadPakcet,iLenPacket,broadcastAddress,31296); + if(iSendLength != iLenPacket) { + char *aa=reinterpret_cast(&tempStreadPakcet); + tempUdpSocket->writeDatagram(&aa[iSendLength],iLenPacket-iSendLength,broadcastAddress,31296); + } + delete tempUdpSocket; + } + } + if(ui->checkBoxDebug->isChecked()) { + ui->textEditReadBuf->append("udp:"+tr(databuf.toHex())); + } +} +void mGuangYingPinWidget::MWSendCmd(uint8_t iComIndex,unsigned char cmd,unsigned char *pUcValue,unsigned int iLength,int iCountCmd) +{ + ST_ANSY_PROGRAM_PACKET tempStreadPakcet; + tempStreadPakcet.SyncHead[0]=0x7e; + tempStreadPakcet.SyncHead[1]=0x7e; + tempStreadPakcet.SyncHead[2]=0x55; + tempStreadPakcet.ucCommType=cmd; + tempStreadPakcet.iBaoLiu=iCountCmd; + tempStreadPakcet.iLength=iLength; + memcpy(tempStreadPakcet.pDataBuffer,pUcValue,iLength); + tempStreadPakcet.pDataBuffer[tempStreadPakcet.iLength]=GetCheckCodeIn8(&tempStreadPakcet.ucCommType,tempStreadPakcet.iLength+sizeof(tempStreadPakcet.iBaoLiu)+sizeof(tempStreadPakcet.ucCommType)+sizeof(tempStreadPakcet.iLength)); + int iLenPacket=3*sizeof(unsigned char)+sizeof(char)+sizeof(int)+sizeof(int)+tempStreadPakcet.iLength+sizeof(char);/////除正文外的协议结构大小; + QByteArray databuf = QByteArray(reinterpret_cast(&tempStreadPakcet), iLenPacket); + sPortThread->SendDataBuf(iComIndex,databuf); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->append("com:"+tr(databuf.toHex())); + } +//sPortThread->SendDataBuf(ui->comboBox_SPortName->currentIndex(),ui->textEdit->toPlainText().toLatin1()); +// m_sendNum += (ui->textEdit->toPlainText().toLatin1()).length(); +// MWRSNumDisplay(); +} + +void mGuangYingPinWidget::MWReadData(void) +{ + QByteArray buf; + buf = sPortThread->GetDataBuf(ui->comboBox_SPortName->currentIndex()); + if(!buf.isEmpty()) + { + QString str = tr(buf.toHex()); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->moveCursor(QTextCursor::End); + ui->textEditReadBuf->insertPlainText(str); + } + MWRSNumDisplay(); + } + buf.clear(); +} +void mGuangYingPinWidget::MWReadDataAux(void) +{ + QByteArray buf; + buf = sPortThread->GetDataBuf(ui->comboBox_SPortNameAux->currentIndex()); + if(!buf.isEmpty()) + { + QString str = tr(buf.toHex()); + if(ui->checkBoxDebug->isChecked()) + { + ui->textEditReadBuf->moveCursor(QTextCursor::End); + ui->textEditReadBuf->insertPlainText(str); + } + MWRSNumDisplay(); + } + buf.clear(); +} +QString mGuangYingPinWidget::ByteArrayToHexString(QByteArray &ba) +{ + QDataStream out(&ba,QIODevice::ReadWrite); //将str的数据 读到out里面去 + QString buf; + while(!out.atEnd()) + { + qint8 outChar = 0; + out >> outChar; //每次一个字节的填充到 outchar + QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0')).toUpper() + QString(" "); //2 字符宽度 + buf += str; + } + return buf; +} +void mGuangYingPinWidget::MWClearRecv(void) +{ +// ui->textBrowser->clear(); +// m_recvNum = 0; +// m_sendNum = 0; +// MWRSNumDisplay(); +} + +void mGuangYingPinWidget::MWRSNumDisplay(void) +{ +// ui->label_RecvNum->setText(tr("已接收:") + QString::number(m_recvNum,10)); +// ui->label_SendNum->setText(tr("已发送:") + QString::number(m_sendNum,10)); +} diff --git a/LedOK/mguangyingpinwidget.h b/LedOK/mguangyingpinwidget.h index 0963ca5..acdcebb 100644 --- a/LedOK/mguangyingpinwidget.h +++ b/LedOK/mguangyingpinwidget.h @@ -1,95 +1,95 @@ -#ifndef MGUANGYINGPINWIDGET_H -#define MGUANGYINGPINWIDGET_H - -#include -#include "communication/taserialthread.h" -#include -#include -namespace Ui { -class mGuangYingPinWidget; -} - -#define MACRO_ANSY_PROGRAM(PROGRAM_INDEX) \ - if(ui->groupBox_com->isChecked())\ - {\ - if(ui->pushButtonMainOpen->text()==tr("Close"))\ - Set_program_buf_and_send(ui->comboBox_SPortName->currentIndex(),PROGRAM_INDEX);\ - if(ui->pushButtonAuxOpen->text()==tr("Close"))\ - Set_program_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),PROGRAM_INDEX);\ - }\ - if(ui->groupBox_Network->isChecked())\ - {\ - Set_program_buf_and_send_by_udp(PROGRAM_INDEX);\ - } -class mGuangYingPinWidget : public QWidget { - Q_OBJECT -public: - explicit mGuangYingPinWidget(QWidget *parent = nullptr); - ~mGuangYingPinWidget(); -protected: - void changeEvent(QEvent *) override; - void transUi(); -public slots: - void MWOnoffPort(void); - void MWOnoffPortAux(void); - void MWSendCmd(uint8_t iComIndex,unsigned char cmd,unsigned char *pUcValue,unsigned int iLength,int iCountCmd); - void MWSendCmdByUdp(unsigned char cmd,unsigned char *pUcValue,unsigned int iLength,int iCountCmd); - - void MWReadData(void); - void MWReadDataAux(void); - void MWClearRecv(void); - void MWRSNumDisplay(void); - void OnAnsyProgram1(void); - void OnAnsyProgram2(void); - void OnAnsyProgram3(void); - void OnAnsyProgram4(void); - void OnAnsyProgram5(void); - void OnAnsyProgram6(void); - void OnAnsyProgram7(void); - void OnAnsyProgram8(void); - void OnAnsyProgram9(void); - void OnAnsyProgram10(void); - void OnAnsyProgram11(void); - void OnAnsyProgram12(void); - void OnAnsyProgram13(void); - void OnAnsyProgram14(void); - void OnAnsyProgram15(void); - void OnAnsyProgram16(void); - void OnAnsyProgram17(void); - void OnAnsyProgram18(void); - void OnAnsyProgram19(void); - void OnAnsyProgram20(void); - void OnClearLog(void); - void OnAnsyProgramCustom(void); - void OnAnsyProgramNext(void); - void OnAnsyProgramPrevious(void); - void OnAnsyProgramLoop(void); - void OnBrightnessSet(void); - void OnScreenOn(void); - void OnScreenOff(void); - void OnAnsyProgramCustomByChanged(int icurIndex); - void OnBrightnessSetByChanged(int icurValue); - void OnRefresh(void); -private: - Ui::mGuangYingPinWidget *ui; - TA_SerialThread *sPortThread; - volatile uint32_t m_recvNum; - volatile uint32_t m_sendNum; - int g_iCountCmd=0; - int m_port=31296; - void Set_program_buf_and_send(int iComIndex,int iProgramIndex); - void Set_program_buf_and_send_by_udp(int iProgramIndex); - void Set_Brightness_buf_and_send(int iComIndex,int iBrightnessValue); - void Set_Brightness_buf_and_send_by_udp(int iBrightnessValue); - void Screen_OnOff_buf_and_send(int iComIndex,int iScreenOnOff); - void Screen_OnOff_buf_and_send_by_udp(int iScreenOnOff); - void NextProgram_buf_and_send(int iComIndex); - void NextProgram_buf_and_send_by_udp(); - - - void mymidelay(int imlsec); - QString ByteArrayToHexString(QByteArray &ba); - -}; - -#endif // MGUANGYINGPINWIDGET_H +#ifndef MGUANGYINGPINWIDGET_H +#define MGUANGYINGPINWIDGET_H + +#include +#include "communication/taserialthread.h" +#include +#include +namespace Ui { +class mGuangYingPinWidget; +} + +#define MACRO_ANSY_PROGRAM(PROGRAM_INDEX) \ + if(ui->groupBox_com->isChecked())\ + {\ + if(ui->pushButtonMainOpen->text()==tr("Close"))\ + Set_program_buf_and_send(ui->comboBox_SPortName->currentIndex(),PROGRAM_INDEX);\ + if(ui->pushButtonAuxOpen->text()==tr("Close"))\ + Set_program_buf_and_send(ui->comboBox_SPortNameAux->currentIndex(),PROGRAM_INDEX);\ + }\ + if(ui->groupBox_Network->isChecked())\ + {\ + Set_program_buf_and_send_by_udp(PROGRAM_INDEX);\ + } +class mGuangYingPinWidget : public QWidget { + Q_OBJECT +public: + explicit mGuangYingPinWidget(QWidget *parent = nullptr); + ~mGuangYingPinWidget(); +protected: + void changeEvent(QEvent *) override; + void transUi(); +public slots: + void MWOnoffPort(void); + void MWOnoffPortAux(void); + void MWSendCmd(uint8_t iComIndex,unsigned char cmd,unsigned char *pUcValue,unsigned int iLength,int iCountCmd); + void MWSendCmdByUdp(unsigned char cmd,unsigned char *pUcValue,unsigned int iLength,int iCountCmd); + + void MWReadData(void); + void MWReadDataAux(void); + void MWClearRecv(void); + void MWRSNumDisplay(void); + void OnAnsyProgram1(void); + void OnAnsyProgram2(void); + void OnAnsyProgram3(void); + void OnAnsyProgram4(void); + void OnAnsyProgram5(void); + void OnAnsyProgram6(void); + void OnAnsyProgram7(void); + void OnAnsyProgram8(void); + void OnAnsyProgram9(void); + void OnAnsyProgram10(void); + void OnAnsyProgram11(void); + void OnAnsyProgram12(void); + void OnAnsyProgram13(void); + void OnAnsyProgram14(void); + void OnAnsyProgram15(void); + void OnAnsyProgram16(void); + void OnAnsyProgram17(void); + void OnAnsyProgram18(void); + void OnAnsyProgram19(void); + void OnAnsyProgram20(void); + void OnClearLog(void); + void OnAnsyProgramCustom(void); + void OnAnsyProgramNext(void); + void OnAnsyProgramPrevious(void); + void OnAnsyProgramLoop(void); + void OnBrightnessSet(void); + void OnScreenOn(void); + void OnScreenOff(void); + void OnAnsyProgramCustomByChanged(int icurIndex); + void OnBrightnessSetByChanged(int icurValue); + void OnRefresh(void); +private: + Ui::mGuangYingPinWidget *ui; + TA_SerialThread *sPortThread; + volatile uint32_t m_recvNum; + volatile uint32_t m_sendNum; + int g_iCountCmd=0; + int m_port=31296; + void Set_program_buf_and_send(int iComIndex,int iProgramIndex); + void Set_program_buf_and_send_by_udp(int iProgramIndex); + void Set_Brightness_buf_and_send(int iComIndex,int iBrightnessValue); + void Set_Brightness_buf_and_send_by_udp(int iBrightnessValue); + void Screen_OnOff_buf_and_send(int iComIndex,int iScreenOnOff); + void Screen_OnOff_buf_and_send_by_udp(int iScreenOnOff); + void NextProgram_buf_and_send(int iComIndex); + void NextProgram_buf_and_send_by_udp(); + + + void mymidelay(int imlsec); + QString ByteArrayToHexString(QByteArray &ba); + +}; + +#endif // MGUANGYINGPINWIDGET_H diff --git a/LedOK/mguangyingpinwidget.ui b/LedOK/mguangyingpinwidget.ui index b3049d5..9406f2e 100644 --- a/LedOK/mguangyingpinwidget.ui +++ b/LedOK/mguangyingpinwidget.ui @@ -1,1524 +1,1524 @@ - - - mGuangYingPinWidget - - - - 0 - 0 - 866 - 718 - - - - false - - - - - - - - - Qt::Horizontal - - - - - - - - - Qt::Vertical - - - - - - - Com - - - true - - - true - - - - - - 0 - - - - - - 200 - 16777215 - - - - - 12 - - - - Main - - - Qt::AlignCenter - - - true - - - - - - - - PortName - - - - - - - - 80 - 0 - - - - - - - - - - 0 - - - - - BaudRate - - - - - - - - 1200 - - - - - 2400 - - - - - 4800 - - - - - 9600 - - - - - 19200 - - - - - 38400 - - - - - 57600 - - - - - 115200 - - - - - - - - - - 0 - - - - - DataBit - - - - - - - - 5 - - - - - 6 - - - - - 7 - - - - - 8 - - - - - - - - - - 0 - - - - - OEBit - - - - - - - - No - - - - - Even - - - - - Odd - - - - - Space - - - - - Mark - - - - - - - - - - 0 - - - - - StopBit - - - - - - - - 1 - - - - - 2 - - - - - 1.5 - - - - - - - - - - 0 - - - - - State:Close - - - - - - - - 30 - 30 - - - - - - - - - - - - - 80 - 30 - - - - Open - - - - - - - - - - - - - - Qt::Vertical - - - - - - - 0 - - - - - - 200 - 16777215 - - - - - 12 - - - - Auxiliary - - - Qt::AlignCenter - - - true - - - false - - - - - - - - PortName - - - - - - - - 80 - 0 - - - - - - - - - - - - BaudRate - - - - - - - - 1200 - - - - - 2400 - - - - - 4800 - - - - - 9600 - - - - - 19200 - - - - - 38400 - - - - - 57600 - - - - - 115200 - - - - - - - - - - - - DataBit - - - - - - - - 5 - - - - - 6 - - - - - 7 - - - - - 8 - - - - - - - - - - - - OEBit - - - - - - - - No - - - - - Even - - - - - Odd - - - - - Space - - - - - Mark - - - - - - - - - - - - StopBit - - - - - - - - 1 - - - - - 2 - - - - - 1.5 - - - - - - - - - - - - State:Close - - - - - - - - 30 - 30 - - - - - - - - - - - - - 80 - 30 - - - - Open - - - - - - - - - - - - - - - 0 - 0 - - - - - 80 - 40 - - - - - 12 - - - - Refresh - - - - - - - - - - Network - - - true - - - true - - - false - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - - - - Qt::Vertical - - - - - - - 0 - - - - - - 200 - 16777215 - - - - - 12 - - - - Param configuration - - - Qt::AlignCenter - - - true - - - - - - - - - 10 - - - - Resend times - - - - - - - - 80 - 16777215 - - - - 10 - - - - - - - - - - - - 10 - - - - Delay millsecond - - - - - - - - 80 - 16777215 - - - - 10 - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Horizontal - - - - - - - - - 2 - - - - - 0 - - - - - 0 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 1 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 2 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 3 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 4 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 5 - - - - - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 6 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 7 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 8 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 9 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 10 - - - - - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 11 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 12 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 13 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 14 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 15 - - - - - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 16 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 17 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 18 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 19 - - - - - - - - 40 - 40 - - - - - 40 - 40 - - - - 20 - - - - - - - - - - - - - Qt::Vertical - - - - - - - 0 - - - - - 0 - - - - - - 88 - 0 - - - - Program number - - - - - - - - 60 - 0 - - - - 999 - - - 21 - - - - - - - - 80 - 40 - - - - Send - - - - - - - Qt::Vertical - - - - - - - - 40 - 40 - - - - - - - - 32 - 32 - - - - true - - - - - - - - 40 - 40 - - - - - - - - 32 - 32 - - - - true - - - - - - - - 40 - 40 - - - - - - - - 32 - 32 - - - - true - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Horizontal - - - - - - - - - - 88 - 0 - - - - Brightness - - - - - - - - 60 - 0 - - - - 255 - - - 255 - - - - - - - - 80 - 40 - - - - Set - - - - - - - Qt::Vertical - - - - - - - - 80 - 40 - - - - Screen Off - - - - - - - - 80 - 40 - - - - Screen on - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - 20 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Clear - - - - - - - Debug - - - false - - - - - - - - - - - - - - - Qt::Horizontal - - - - - - - - - - - QAbstractScrollArea::AdjustIgnored - - - false - - - true - - - - - - - - - - - - + + + mGuangYingPinWidget + + + + 0 + 0 + 866 + 718 + + + + false + + + + + + + + + Qt::Horizontal + + + + + + + + + Qt::Vertical + + + + + + + Com + + + true + + + true + + + + + + 0 + + + + + + 200 + 16777215 + + + + + 12 + + + + Main + + + Qt::AlignCenter + + + true + + + + + + + + PortName + + + + + + + + 80 + 0 + + + + + + + + + + 0 + + + + + BaudRate + + + + + + + + 1200 + + + + + 2400 + + + + + 4800 + + + + + 9600 + + + + + 19200 + + + + + 38400 + + + + + 57600 + + + + + 115200 + + + + + + + + + + 0 + + + + + DataBit + + + + + + + + 5 + + + + + 6 + + + + + 7 + + + + + 8 + + + + + + + + + + 0 + + + + + OEBit + + + + + + + + No + + + + + Even + + + + + Odd + + + + + Space + + + + + Mark + + + + + + + + + + 0 + + + + + StopBit + + + + + + + + 1 + + + + + 2 + + + + + 1.5 + + + + + + + + + + 0 + + + + + State:Close + + + + + + + + 30 + 30 + + + + + + + + + + + + + 80 + 30 + + + + Open + + + + + + + + + + + + + + Qt::Vertical + + + + + + + 0 + + + + + + 200 + 16777215 + + + + + 12 + + + + Auxiliary + + + Qt::AlignCenter + + + true + + + false + + + + + + + + PortName + + + + + + + + 80 + 0 + + + + + + + + + + + + BaudRate + + + + + + + + 1200 + + + + + 2400 + + + + + 4800 + + + + + 9600 + + + + + 19200 + + + + + 38400 + + + + + 57600 + + + + + 115200 + + + + + + + + + + + + DataBit + + + + + + + + 5 + + + + + 6 + + + + + 7 + + + + + 8 + + + + + + + + + + + + OEBit + + + + + + + + No + + + + + Even + + + + + Odd + + + + + Space + + + + + Mark + + + + + + + + + + + + StopBit + + + + + + + + 1 + + + + + 2 + + + + + 1.5 + + + + + + + + + + + + State:Close + + + + + + + + 30 + 30 + + + + + + + + + + + + + 80 + 30 + + + + Open + + + + + + + + + + + + + + + 0 + 0 + + + + + 80 + 40 + + + + + 12 + + + + Refresh + + + + + + + + + + Network + + + true + + + true + + + false + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + + + + Qt::Vertical + + + + + + + 0 + + + + + + 200 + 16777215 + + + + + 12 + + + + Param configuration + + + Qt::AlignCenter + + + true + + + + + + + + + 10 + + + + Resend times + + + + + + + + 80 + 16777215 + + + + 10 + + + + + + + + + + + + 10 + + + + Delay millsecond + + + + + + + + 80 + 16777215 + + + + 10 + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + 2 + + + + + 0 + + + + + 0 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 1 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 2 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 3 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 4 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 5 + + + + + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 6 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 7 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 8 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 9 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 10 + + + + + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 11 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 12 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 13 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 14 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 15 + + + + + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 16 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 17 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 18 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 19 + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + 20 + + + + + + + + + + + + + Qt::Vertical + + + + + + + 0 + + + + + 0 + + + + + + 88 + 0 + + + + Program number + + + + + + + + 60 + 0 + + + + 999 + + + 21 + + + + + + + + 80 + 40 + + + + Send + + + + + + + Qt::Vertical + + + + + + + + 40 + 40 + + + + + + + + 32 + 32 + + + + true + + + + + + + + 40 + 40 + + + + + + + + 32 + 32 + + + + true + + + + + + + + 40 + 40 + + + + + + + + 32 + 32 + + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Horizontal + + + + + + + + + + 88 + 0 + + + + Brightness + + + + + + + + 60 + 0 + + + + 255 + + + 255 + + + + + + + + 80 + 40 + + + + Set + + + + + + + Qt::Vertical + + + + + + + + 80 + 40 + + + + Screen Off + + + + + + + + 80 + 40 + + + + Screen on + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + 20 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Clear + + + + + + + Debug + + + false + + + + + + + + + + + + + + + Qt::Horizontal + + + + + + + + + + + QAbstractScrollArea::AdjustIgnored + + + false + + + true + + + + + + + + + + + + diff --git a/LedOK/oescreenshot/oeamplifier.cpp b/LedOK/oescreenshot/oeamplifier.cpp index be42ae4..785823a 100644 --- a/LedOK/oescreenshot/oeamplifier.cpp +++ b/LedOK/oescreenshot/oeamplifier.cpp @@ -1,153 +1,153 @@ -/** - * @author : 陈鲁勇 - * @date : 2017年04月 - * @version: 1.0 - * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; - * 除非遵守本许可,否则您不能使用这个文件。 - * @remarks: 您可以获得该许可的副本: - * http://www.apache.org/licenses/LICENSE-2.0 - * 除非适用法律需要或者书面同意,按本许可分发的软件 - * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 - * 参见按照本许可控制许可权限及限制的特定语言的许可证。 - * - * 你可以获得该代码的最新版本: - * - * https://git.oschina.net/Mr_ChenLuYong/screenshot - * - * 开源社区的所有人都期待与你的共同维护。 - * - * - * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: - * - * 博客地址:http://blog.csdn.net/csnd_ayo - * - * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 - * - * 期待你提交Bug,欢迎Issues。 - * -*/ - - - -#include "oeamplifier.h" - - -#include -#include - -#ifndef QT_NO_DEBUG -#include -#endif - - -#include "oecommonhelper.h" - -OEAmplifier::OEAmplifier(std::shared_ptr originPainting, QWidget *parent) : - QWidget(parent), originPainting_(originPainting) { - /// 设置成无边框对话框 - setWindowFlags(Qt::FramelessWindowHint|Qt::WindowSystemMenuHint); - /// 开启鼠标实时追踪 - setMouseTracking(true); - - /// 设置默认大小 - sideLength_ = 122 * OECommonHelper::getWindowHeightMultiplyingPower(); - imageHeight_ = 90 * OECommonHelper::getWindowHeightMultiplyingPower(); - setFixedSize(sideLength_,sideLength_); - - /// 默认隐藏 - hide(); -} - -void OEAmplifier::onSizeChange(int w, int h) { - screenSize_ = QSize(w, h); -} - -void OEAmplifier::onPostionChange(int x, int y) { - cursorPoint_ = QPoint(x, y); - raise(); - int dest_x = x + 4; - int dest_y = y + 26; - - /// 超出屏幕检测 - const QSize& parent_size = parentWidget()->size(); - if (dest_y + height() > parent_size.height()) { - dest_y = y - 26 - height(); - } - if (dest_x + width() > parent_size.width()) { - dest_x = x - 4 - width(); - } - - move(dest_x, dest_y); -} - - - -/// 绘制鼠标拖拽时选区矩形的右下顶点的放大图; -void OEAmplifier::paintEvent(QPaintEvent *) { - QPainter painter(this); - - /// 绘制背景 - painter.fillRect(rect(), QColor(0, 0, 0, 160)); - - QPixmap endPointImage; - /// 绘制放大图; - const QSize& parent_size = parentWidget()->size(); - /** - * @bug : 在屏幕边缘绘制放大图时会出现图片拉伸 - * 这里暂时做了边缘检测,若是屏幕边缘则不进行放大图的绘制,和QQ截图的采取方式是一致的。 - * - * @marker: 颜色还是照样识别,但是局部放大的效果暂时禁用 - * - * @note : 解决方法,可以发现边缘时,将不能放大的地方,不描绘,或填充黑色,以避免图片被非预期的拉伸问题。 - */ - if ((cursorPoint_.x() + 15 < parent_size.width() && cursorPoint_.x() - 15 > 0) - && (cursorPoint_.y() + 11 < parent_size.height() && cursorPoint_.y() - 11 > 0)) { - endPointImage = originPainting_-> - copy(QRect(cursorPoint_.x() - 15, - cursorPoint_.y() - 11, 30, 22)) - .scaled(sideLength_, imageHeight_); - painter.drawPixmap(0,0, endPointImage); - } - else { - endPointImage = originPainting_-> - copy(QRect(cursorPoint_.x() - 15, - cursorPoint_.y() - 11, 30, 22)); - } - - - /// 绘制十字 - painter.setPen(QPen(QColor(0, 180, 255 , 180), 4)); - // 竖线; - painter.drawLine(QPoint(sideLength_ >> 1, 0), - QPoint(sideLength_ >> 1, - imageHeight_ - 4)); - // 横线; - painter.drawLine(QPoint(0, imageHeight_ >> 1), - QPoint(sideLength_, - imageHeight_ >> 1)); - - /// 绘制大图内边框 - painter.setPen(QPen(Qt::white, 2)); - painter.drawRect(2,2,width()-4, imageHeight_-4); - - /// 绘制外边框 - painter.setPen(QPen(Qt::black, 1)); - painter.drawRect(0,0,width()-1,height()-1); - - /// 当前选中矩形的宽高信息; - QString select_screen_info = QString("%1×%2") - .arg(screenSize_.width()).arg(screenSize_.height()); - - /// 当前鼠标像素值的RGB信息 - QImage image = originPainting_->toImage(); - QColor cursor_pixel = image.pixel(cursorPoint_); - QString select_pt_rgb = QString("RGB:(%1,%2,%3)") - .arg(cursor_pixel.red()) - .arg(cursor_pixel.green()) - .arg(cursor_pixel.blue()); - - /// 绘制坐标轴相关数据 - painter.setPen(Qt::white); - painter.drawText(QPoint(6, imageHeight_+14),select_screen_info); - painter.drawText(QPoint(6, imageHeight_+27),select_pt_rgb); -} +/** + * @author : 陈鲁勇 + * @date : 2017年04月 + * @version: 1.0 + * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; + * 除非遵守本许可,否则您不能使用这个文件。 + * @remarks: 您可以获得该许可的副本: + * http://www.apache.org/licenses/LICENSE-2.0 + * 除非适用法律需要或者书面同意,按本许可分发的软件 + * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 + * 参见按照本许可控制许可权限及限制的特定语言的许可证。 + * + * 你可以获得该代码的最新版本: + * + * https://git.oschina.net/Mr_ChenLuYong/screenshot + * + * 开源社区的所有人都期待与你的共同维护。 + * + * + * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: + * + * 博客地址:http://blog.csdn.net/csnd_ayo + * + * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 + * + * 期待你提交Bug,欢迎Issues。 + * +*/ + + + +#include "oeamplifier.h" + + +#include +#include + +#ifndef QT_NO_DEBUG +#include +#endif + + +#include "oecommonhelper.h" + +OEAmplifier::OEAmplifier(std::shared_ptr originPainting, QWidget *parent) : + QWidget(parent), originPainting_(originPainting) { + /// 设置成无边框对话框 + setWindowFlags(Qt::FramelessWindowHint|Qt::WindowSystemMenuHint); + /// 开启鼠标实时追踪 + setMouseTracking(true); + + /// 设置默认大小 + sideLength_ = 122 * OECommonHelper::getWindowHeightMultiplyingPower(); + imageHeight_ = 90 * OECommonHelper::getWindowHeightMultiplyingPower(); + setFixedSize(sideLength_,sideLength_); + + /// 默认隐藏 + hide(); +} + +void OEAmplifier::onSizeChange(int w, int h) { + screenSize_ = QSize(w, h); +} + +void OEAmplifier::onPostionChange(int x, int y) { + cursorPoint_ = QPoint(x, y); + raise(); + int dest_x = x + 4; + int dest_y = y + 26; + + /// 超出屏幕检测 + const QSize& parent_size = parentWidget()->size(); + if (dest_y + height() > parent_size.height()) { + dest_y = y - 26 - height(); + } + if (dest_x + width() > parent_size.width()) { + dest_x = x - 4 - width(); + } + + move(dest_x, dest_y); +} + + + +/// 绘制鼠标拖拽时选区矩形的右下顶点的放大图; +void OEAmplifier::paintEvent(QPaintEvent *) { + QPainter painter(this); + + /// 绘制背景 + painter.fillRect(rect(), QColor(0, 0, 0, 160)); + + QPixmap endPointImage; + /// 绘制放大图; + const QSize& parent_size = parentWidget()->size(); + /** + * @bug : 在屏幕边缘绘制放大图时会出现图片拉伸 + * 这里暂时做了边缘检测,若是屏幕边缘则不进行放大图的绘制,和QQ截图的采取方式是一致的。 + * + * @marker: 颜色还是照样识别,但是局部放大的效果暂时禁用 + * + * @note : 解决方法,可以发现边缘时,将不能放大的地方,不描绘,或填充黑色,以避免图片被非预期的拉伸问题。 + */ + if ((cursorPoint_.x() + 15 < parent_size.width() && cursorPoint_.x() - 15 > 0) + && (cursorPoint_.y() + 11 < parent_size.height() && cursorPoint_.y() - 11 > 0)) { + endPointImage = originPainting_-> + copy(QRect(cursorPoint_.x() - 15, + cursorPoint_.y() - 11, 30, 22)) + .scaled(sideLength_, imageHeight_); + painter.drawPixmap(0,0, endPointImage); + } + else { + endPointImage = originPainting_-> + copy(QRect(cursorPoint_.x() - 15, + cursorPoint_.y() - 11, 30, 22)); + } + + + /// 绘制十字 + painter.setPen(QPen(QColor(0, 180, 255 , 180), 4)); + // 竖线; + painter.drawLine(QPoint(sideLength_ >> 1, 0), + QPoint(sideLength_ >> 1, + imageHeight_ - 4)); + // 横线; + painter.drawLine(QPoint(0, imageHeight_ >> 1), + QPoint(sideLength_, + imageHeight_ >> 1)); + + /// 绘制大图内边框 + painter.setPen(QPen(Qt::white, 2)); + painter.drawRect(2,2,width()-4, imageHeight_-4); + + /// 绘制外边框 + painter.setPen(QPen(Qt::black, 1)); + painter.drawRect(0,0,width()-1,height()-1); + + /// 当前选中矩形的宽高信息; + QString select_screen_info = QString("%1×%2") + .arg(screenSize_.width()).arg(screenSize_.height()); + + /// 当前鼠标像素值的RGB信息 + QImage image = originPainting_->toImage(); + QColor cursor_pixel = image.pixel(cursorPoint_); + QString select_pt_rgb = QString("RGB:(%1,%2,%3)") + .arg(cursor_pixel.red()) + .arg(cursor_pixel.green()) + .arg(cursor_pixel.blue()); + + /// 绘制坐标轴相关数据 + painter.setPen(Qt::white); + painter.drawText(QPoint(6, imageHeight_+14),select_screen_info); + painter.drawText(QPoint(6, imageHeight_+27),select_pt_rgb); +} diff --git a/LedOK/oescreenshot/oeamplifier.h b/LedOK/oescreenshot/oeamplifier.h index d08b31c..3643152 100644 --- a/LedOK/oescreenshot/oeamplifier.h +++ b/LedOK/oescreenshot/oeamplifier.h @@ -1,93 +1,93 @@ -/** - * @author : 陈鲁勇 - * @date : 2017年04月 - * @version: 1.0 - * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; - * 除非遵守本许可,否则您不能使用这个文件。 - * @remarks: 您可以获得该许可的副本: - * http://www.apache.org/licenses/LICENSE-2.0 - * 除非适用法律需要或者书面同意,按本许可分发的软件 - * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 - * 参见按照本许可控制许可权限及限制的特定语言的许可证。 - * - * 你可以获得该代码的最新版本: - * - * https://git.oschina.net/Mr_ChenLuYong/screenshot - * - * 开源社区的所有人都期待与你的共同维护。 - * - * - * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: - * - * 博客地址:http://blog.csdn.net/csnd_ayo - * - * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 - * - * 期待你提交Bug,欢迎Issues。 - * -*/ - - - -#ifndef OEAMPLIFIER_H -#define OEAMPLIFIER_H -#include -#include - - -/** - * @class : OEAmplifier - * @brief : 放大取色器 - * @note : 关于鼠标位置局部放大的操作以及色卡取值的操作 - */ -class OEAmplifier : public QWidget -{ - Q_OBJECT -public: - explicit OEAmplifier(std::shared_ptr originPainting, QWidget *parent = 0); - -signals: - -public slots: - - - /** - * @brief : 大小修改 - * @param : w 宽度 - * @param : h 高度 - * @date : 2017年4月29日 - */ - void onSizeChange(int w, int h); - - /** - * @brief : 大小修改 - * @param : w 宽度 - * @param : h 高度 - * @date : 2017年4月29日 - */ - void onPostionChange(int x, int y); - -protected: - - /** - * @brief : 窗口自绘事件 - * @date : 2017年4月29日 - */ - virtual void paintEvent(QPaintEvent *); - -private: - - /// 外部组件的大小信息 - QSize screenSize_; - /// 鼠标的位置 - QPoint cursorPoint_; - /// 取色放大器的边长 - int sideLength_; - /// 放大区的高度 - int imageHeight_; - /// 屏幕原画 - std::shared_ptr originPainting_; - -}; - -#endif /// OEAMPLIFIER_H +/** + * @author : 陈鲁勇 + * @date : 2017年04月 + * @version: 1.0 + * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; + * 除非遵守本许可,否则您不能使用这个文件。 + * @remarks: 您可以获得该许可的副本: + * http://www.apache.org/licenses/LICENSE-2.0 + * 除非适用法律需要或者书面同意,按本许可分发的软件 + * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 + * 参见按照本许可控制许可权限及限制的特定语言的许可证。 + * + * 你可以获得该代码的最新版本: + * + * https://git.oschina.net/Mr_ChenLuYong/screenshot + * + * 开源社区的所有人都期待与你的共同维护。 + * + * + * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: + * + * 博客地址:http://blog.csdn.net/csnd_ayo + * + * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 + * + * 期待你提交Bug,欢迎Issues。 + * +*/ + + + +#ifndef OEAMPLIFIER_H +#define OEAMPLIFIER_H +#include +#include + + +/** + * @class : OEAmplifier + * @brief : 放大取色器 + * @note : 关于鼠标位置局部放大的操作以及色卡取值的操作 + */ +class OEAmplifier : public QWidget +{ + Q_OBJECT +public: + explicit OEAmplifier(std::shared_ptr originPainting, QWidget *parent = 0); + +signals: + +public slots: + + + /** + * @brief : 大小修改 + * @param : w 宽度 + * @param : h 高度 + * @date : 2017年4月29日 + */ + void onSizeChange(int w, int h); + + /** + * @brief : 大小修改 + * @param : w 宽度 + * @param : h 高度 + * @date : 2017年4月29日 + */ + void onPostionChange(int x, int y); + +protected: + + /** + * @brief : 窗口自绘事件 + * @date : 2017年4月29日 + */ + virtual void paintEvent(QPaintEvent *); + +private: + + /// 外部组件的大小信息 + QSize screenSize_; + /// 鼠标的位置 + QPoint cursorPoint_; + /// 取色放大器的边长 + int sideLength_; + /// 放大区的高度 + int imageHeight_; + /// 屏幕原画 + std::shared_ptr originPainting_; + +}; + +#endif /// OEAMPLIFIER_H diff --git a/LedOK/oescreenshot/oecommonhelper.cpp b/LedOK/oescreenshot/oecommonhelper.cpp index 6869685..d361f21 100644 --- a/LedOK/oescreenshot/oecommonhelper.cpp +++ b/LedOK/oescreenshot/oecommonhelper.cpp @@ -1,141 +1,141 @@ -/** - * @author : 陈鲁勇 - * @date : 2017年04月 - * @version: 1.0 - * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; - * 除非遵守本许可,否则您不能使用这个文件。 - * @remarks: 您可以获得该许可的副本: - * http://www.apache.org/licenses/LICENSE-2.0 - * 除非适用法律需要或者书面同意,按本许可分发的软件 - * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 - * 参见按照本许可控制许可权限及限制的特定语言的许可证。 - * - * 你可以获得该代码的最新版本: - * - * https://git.oschina.net/Mr_ChenLuYong/screenshot - * - * 开源社区的所有人都期待与你的共同维护。 - * - * - * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: - * - * 博客地址:http://blog.csdn.net/csnd_ayo - * - * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 - * - * 期待你提交Bug,欢迎Issues。 - * -*/ - - -#include "oecommonhelper.h" - -#include -#include -#include -#include -#include - -#include - -#ifndef QT_NO_DEBUG -#include -#endif - - -#define WINDOW_BASESIZE_WIDTH (1920) -#define WINDOW_BASESIZE_HEIGHT (1080) - -float OECommonHelper::widthMultiplyingPower_ = 0; -float OECommonHelper::heightMultiplyingPower_ = 0; - -void OECommonHelper::setStyle(const QString &style) { - QFile qss(style); - qss.open(QFile::ReadOnly); - qApp->setStyleSheet(qss.readAll()); - qss.close(); -} - -void OECommonHelper::setLanguagePack(const QString &language) { - // 加载中文包 - QTranslator translator; - translator.load(language); - qApp->installTranslator(&translator); -} - -void OECommonHelper::moveCenter(QWidget *widget, QRect parentRect) { - if (parentRect.isEmpty()) { - parentRect = QApplication::desktop()->rect(); - } - widget->move (((parentRect.width() - widget->width()) >> 1), - ((parentRect.height() - widget->height()) >> 1)); -} - -const float &OECommonHelper::getWindowWidthMultiplyingPower() { - if (widthMultiplyingPower_ == 0) { - upWindowSizeMultiplyingPower(); - } - return widthMultiplyingPower_; -} - -const float & OECommonHelper::getWindowHeightMultiplyingPower() { - if (heightMultiplyingPower_ == 0) { - upWindowSizeMultiplyingPower(); - } - return heightMultiplyingPower_; -} - -void OECommonHelper::upWindowSizeMultiplyingPower() { - QSize temp_size = QApplication::desktop()->size(); - widthMultiplyingPower_ = (float)temp_size.width() - / (float)WINDOW_BASESIZE_WIDTH; - heightMultiplyingPower_ = (float)temp_size.height() - / (float)WINDOW_BASESIZE_HEIGHT; -} - -bool OECommonHelper::getSmallestWindowFromCursor(QRect& out_rect) { - HWND hwnd; - POINT pt; - // 获得当前鼠标位置 - ::GetCursorPos(&pt); - // 获得当前位置桌面上的子窗口 - hwnd = ::ChildWindowFromPointEx(::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE); - if (hwnd != NULL) { - HWND temp_hwnd; - temp_hwnd = hwnd; - while (true) { - ::GetCursorPos(&pt); - ::ScreenToClient(temp_hwnd, &pt); - temp_hwnd = ::ChildWindowFromPointEx(temp_hwnd, pt, CWP_SKIPINVISIBLE); - if (temp_hwnd == NULL || temp_hwnd == hwnd) - break; - hwnd = temp_hwnd; - } - RECT temp_window; - ::GetWindowRect(hwnd, &temp_window); - out_rect.setRect(temp_window.left,temp_window.top, - temp_window.right - temp_window.left, - temp_window.bottom - temp_window.top); - return true; - } - return false; -} - -bool OECommonHelper::getCurrentWindowFromCursor(QRect &out_rect) -{ - HWND hwnd; - POINT pt; - // 获得当前鼠标位置 - ::GetCursorPos(&pt); - // 获得当前位置桌面上的子窗口 - hwnd = ::ChildWindowFromPointEx(::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE); - if (hwnd != NULL) { - RECT temp_window; - ::GetWindowRect(hwnd, &temp_window); - out_rect.setRect(temp_window.left, temp_window.top, - temp_window.right - temp_window.left, - temp_window.bottom - temp_window.top); - return true; - } - return false; -} +/** + * @author : 陈鲁勇 + * @date : 2017年04月 + * @version: 1.0 + * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; + * 除非遵守本许可,否则您不能使用这个文件。 + * @remarks: 您可以获得该许可的副本: + * http://www.apache.org/licenses/LICENSE-2.0 + * 除非适用法律需要或者书面同意,按本许可分发的软件 + * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 + * 参见按照本许可控制许可权限及限制的特定语言的许可证。 + * + * 你可以获得该代码的最新版本: + * + * https://git.oschina.net/Mr_ChenLuYong/screenshot + * + * 开源社区的所有人都期待与你的共同维护。 + * + * + * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: + * + * 博客地址:http://blog.csdn.net/csnd_ayo + * + * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 + * + * 期待你提交Bug,欢迎Issues。 + * +*/ + + +#include "oecommonhelper.h" + +#include +#include +#include +#include +#include + +#include + +#ifndef QT_NO_DEBUG +#include +#endif + + +#define WINDOW_BASESIZE_WIDTH (1920) +#define WINDOW_BASESIZE_HEIGHT (1080) + +float OECommonHelper::widthMultiplyingPower_ = 0; +float OECommonHelper::heightMultiplyingPower_ = 0; + +void OECommonHelper::setStyle(const QString &style) { + QFile qss(style); + qss.open(QFile::ReadOnly); + qApp->setStyleSheet(qss.readAll()); + qss.close(); +} + +void OECommonHelper::setLanguagePack(const QString &language) { + // 加载中文包 + QTranslator translator; + translator.load(language); + qApp->installTranslator(&translator); +} + +void OECommonHelper::moveCenter(QWidget *widget, QRect parentRect) { + if (parentRect.isEmpty()) { + parentRect = QApplication::desktop()->rect(); + } + widget->move (((parentRect.width() - widget->width()) >> 1), + ((parentRect.height() - widget->height()) >> 1)); +} + +const float &OECommonHelper::getWindowWidthMultiplyingPower() { + if (widthMultiplyingPower_ == 0) { + upWindowSizeMultiplyingPower(); + } + return widthMultiplyingPower_; +} + +const float & OECommonHelper::getWindowHeightMultiplyingPower() { + if (heightMultiplyingPower_ == 0) { + upWindowSizeMultiplyingPower(); + } + return heightMultiplyingPower_; +} + +void OECommonHelper::upWindowSizeMultiplyingPower() { + QSize temp_size = QApplication::desktop()->size(); + widthMultiplyingPower_ = (float)temp_size.width() + / (float)WINDOW_BASESIZE_WIDTH; + heightMultiplyingPower_ = (float)temp_size.height() + / (float)WINDOW_BASESIZE_HEIGHT; +} + +bool OECommonHelper::getSmallestWindowFromCursor(QRect& out_rect) { + HWND hwnd; + POINT pt; + // 获得当前鼠标位置 + ::GetCursorPos(&pt); + // 获得当前位置桌面上的子窗口 + hwnd = ::ChildWindowFromPointEx(::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE); + if (hwnd != NULL) { + HWND temp_hwnd; + temp_hwnd = hwnd; + while (true) { + ::GetCursorPos(&pt); + ::ScreenToClient(temp_hwnd, &pt); + temp_hwnd = ::ChildWindowFromPointEx(temp_hwnd, pt, CWP_SKIPINVISIBLE); + if (temp_hwnd == NULL || temp_hwnd == hwnd) + break; + hwnd = temp_hwnd; + } + RECT temp_window; + ::GetWindowRect(hwnd, &temp_window); + out_rect.setRect(temp_window.left,temp_window.top, + temp_window.right - temp_window.left, + temp_window.bottom - temp_window.top); + return true; + } + return false; +} + +bool OECommonHelper::getCurrentWindowFromCursor(QRect &out_rect) +{ + HWND hwnd; + POINT pt; + // 获得当前鼠标位置 + ::GetCursorPos(&pt); + // 获得当前位置桌面上的子窗口 + hwnd = ::ChildWindowFromPointEx(::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE); + if (hwnd != NULL) { + RECT temp_window; + ::GetWindowRect(hwnd, &temp_window); + out_rect.setRect(temp_window.left, temp_window.top, + temp_window.right - temp_window.left, + temp_window.bottom - temp_window.top); + return true; + } + return false; +} diff --git a/LedOK/oescreenshot/oecommonhelper.h b/LedOK/oescreenshot/oecommonhelper.h index e8c1e29..30d3c96 100644 --- a/LedOK/oescreenshot/oecommonhelper.h +++ b/LedOK/oescreenshot/oecommonhelper.h @@ -1,128 +1,128 @@ -/** - * @author : 陈鲁勇 - * @date : 2017年04月 - * @version: 1.0 - * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; - * 除非遵守本许可,否则您不能使用这个文件。 - * @remarks: 您可以获得该许可的副本: - * http://www.apache.org/licenses/LICENSE-2.0 - * 除非适用法律需要或者书面同意,按本许可分发的软件 - * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 - * 参见按照本许可控制许可权限及限制的特定语言的许可证。 - * - * 你可以获得该代码的最新版本: - * - * https://git.oschina.net/Mr_ChenLuYong/screenshot - * - * 开源社区的所有人都期待与你的共同维护。 - * - * - * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: - * - * 博客地址:http://blog.csdn.net/csnd_ayo - * - * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 - * - * 期待你提交Bug,欢迎Issues。 - * -*/ - - - -#ifndef COMMONHELPER_H -#define COMMONHELPER_H -#include -#include - -class QWidget; - -/** - * @class : OECommonHelper - * @brief : 通用助手 - * @note : 完成一些比较常用又通用的功能 - */ -class OECommonHelper -{ -public: - - /** - * @brief : 设置QSS文件 - * @param : style 文件名 - * @author: 陈鲁勇 - * @date : 2017年04月10日 - * @remark: 如果是qrc路径,请带上 qrc:/ - **/ - static void setStyle(const QString &style); - - /** - * @brief : 设置语言包 - * @param : language 语言包的文件名 - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static void setLanguagePack(const QString& language); - - /** - * @brief : 将窗口移动到中心 - * @param : widget 要移动的窗口 - * @param : parentRect 矩形几何数据 - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static void moveCenter(QWidget* widget, QRect parentRect = {}); - - - /** - * @brief : 获得当前界面与开发时的界面之间的横向倍率 - * @return: float 倍率 - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static const float& getWindowWidthMultiplyingPower(void); - - - /** - * @brief : 获得当前界面与开发时的界面之间的纵向倍率 - * @return: float 倍率 - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static const float& getWindowHeightMultiplyingPower(void); - - - /** - * @brief : 获得当前鼠标位置最小的子窗口 - * @param : out_rect 矩形 (返回) - * @return: 成功:true - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static bool getSmallestWindowFromCursor(QRect &out_rect); - - /** - * @brief : 获得当前鼠标位置的窗口 - * @param : out_rect 矩形 (返回) - * @return: 成功:true - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static bool getCurrentWindowFromCursor(QRect &out_rect); - -protected: - - /** - * @brief : 更新窗口倍率 - * @author: 陈鲁勇 - * @date : 2017年04月10日 - **/ - static void upWindowSizeMultiplyingPower(void); - - -private: - /// 窗口横向倍率 - static float widthMultiplyingPower_; - /// 窗口纵向倍率 - static float heightMultiplyingPower_; -}; - -#endif /// COMMONHELPER_H +/** + * @author : 陈鲁勇 + * @date : 2017年04月 + * @version: 1.0 + * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; + * 除非遵守本许可,否则您不能使用这个文件。 + * @remarks: 您可以获得该许可的副本: + * http://www.apache.org/licenses/LICENSE-2.0 + * 除非适用法律需要或者书面同意,按本许可分发的软件 + * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 + * 参见按照本许可控制许可权限及限制的特定语言的许可证。 + * + * 你可以获得该代码的最新版本: + * + * https://git.oschina.net/Mr_ChenLuYong/screenshot + * + * 开源社区的所有人都期待与你的共同维护。 + * + * + * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: + * + * 博客地址:http://blog.csdn.net/csnd_ayo + * + * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 + * + * 期待你提交Bug,欢迎Issues。 + * +*/ + + + +#ifndef COMMONHELPER_H +#define COMMONHELPER_H +#include +#include + +class QWidget; + +/** + * @class : OECommonHelper + * @brief : 通用助手 + * @note : 完成一些比较常用又通用的功能 + */ +class OECommonHelper +{ +public: + + /** + * @brief : 设置QSS文件 + * @param : style 文件名 + * @author: 陈鲁勇 + * @date : 2017年04月10日 + * @remark: 如果是qrc路径,请带上 qrc:/ + **/ + static void setStyle(const QString &style); + + /** + * @brief : 设置语言包 + * @param : language 语言包的文件名 + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static void setLanguagePack(const QString& language); + + /** + * @brief : 将窗口移动到中心 + * @param : widget 要移动的窗口 + * @param : parentRect 矩形几何数据 + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static void moveCenter(QWidget* widget, QRect parentRect = {}); + + + /** + * @brief : 获得当前界面与开发时的界面之间的横向倍率 + * @return: float 倍率 + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static const float& getWindowWidthMultiplyingPower(void); + + + /** + * @brief : 获得当前界面与开发时的界面之间的纵向倍率 + * @return: float 倍率 + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static const float& getWindowHeightMultiplyingPower(void); + + + /** + * @brief : 获得当前鼠标位置最小的子窗口 + * @param : out_rect 矩形 (返回) + * @return: 成功:true + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static bool getSmallestWindowFromCursor(QRect &out_rect); + + /** + * @brief : 获得当前鼠标位置的窗口 + * @param : out_rect 矩形 (返回) + * @return: 成功:true + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static bool getCurrentWindowFromCursor(QRect &out_rect); + +protected: + + /** + * @brief : 更新窗口倍率 + * @author: 陈鲁勇 + * @date : 2017年04月10日 + **/ + static void upWindowSizeMultiplyingPower(void); + + +private: + /// 窗口横向倍率 + static float widthMultiplyingPower_; + /// 窗口纵向倍率 + static float heightMultiplyingPower_; +}; + +#endif /// COMMONHELPER_H diff --git a/LedOK/oescreenshot/oemodelview.cpp b/LedOK/oescreenshot/oemodelview.cpp index 0accfc1..3f9f81c 100644 --- a/LedOK/oescreenshot/oemodelview.cpp +++ b/LedOK/oescreenshot/oemodelview.cpp @@ -1,86 +1,86 @@ -#include "oemodelview.h" - -#include -#include -#include -#include -#include -/// @test : 测试变量 -QPoint startPoint_; -QPoint endPoint_; - - -OEModelView::OEModelView(MODEL model, - QWidget *parent) : QWidget(parent), - color_(Qt::red) { - /// 确定画图样式 - switch (model) { - case MODEL::Arrows: - { - drawFunc_ = &OEModelView::drawArrows; - break; - } - default: - { - drawFunc_ = &OEModelView::drawArrows; - } - } -} - - -void OEModelView::paintEvent(QPaintEvent *) { - QPainter paiter(this); - - /// @test : 测试变量 - startPoint_ = QPoint(width(),height()); - endPoint_ = {}; - - /// 绘制图形 - (this->*drawFunc_)(startPoint_, endPoint_, paiter); -} - - -void OEModelView::drawArrows(const QPoint& startPoint, - const QPoint& endPoint, - QPainter &paiter) { - /// 消锯齿 - paiter.setRenderHint(QPainter::Antialiasing, true); - /// 创建画笔,设置画刷 - QPen pen; - pen.setColor(color_); - pen.setWidth(1); - paiter.setPen(pen); - paiter.setBrush(color_); - - - /// 箭头部分三角形的腰长 - double par = 15.0; - double slopy = atan2((endPoint.y() - startPoint.y()), - (endPoint.x() - startPoint.x())); - double cos_y = cos(slopy); - double sin_y = sin(slopy); - QPoint head_point1 = QPoint(endPoint.x() + int(-par*cos_y - (par / 2.0 * sin_y)), - endPoint.y() + int(-par*sin_y + (par / 2.0 * cos_y))); - QPoint head_point2 = QPoint(endPoint.x() + int(-par*cos_y + (par / 2.0 * sin_y)), - endPoint.y() - int(par / 2.0*cos_y + par * sin_y)); - QPoint head_points[3] = { endPoint, head_point1, head_point2 }; - /// 绘制箭头部分 - paiter.drawPolygon(head_points, 3); - - - /// 计算箭身部分 - int offset_x = int(par*sin_y / 3); - int offset_y = int(par*cos_y / 3); - QPoint body_point1, body_point2; - body_point1 = QPoint(endPoint.x() + int(-par*cos_y - (par / 2.0*sin_y)) + - offset_x, endPoint.y() + int(-par*sin_y + (par / 2.0*cos_y)) - offset_y); - body_point2 = QPoint(endPoint.x() + int(-par*cos_y + (par / 2.0*sin_y) - offset_x), - endPoint.y() - int(par / 2.0*cos_y + par*sin_y) + offset_y); - QPoint body_points[3] = { startPoint, body_point1, body_point2 }; - /// 绘制箭身部分 - paiter.drawPolygon(body_points, 3); - -} -void OEModelView::onColor(const QColor &color) { - color_ = color; -} +#include "oemodelview.h" + +#include +#include +#include +#include +#include +/// @test : 测试变量 +QPoint startPoint_; +QPoint endPoint_; + + +OEModelView::OEModelView(MODEL model, + QWidget *parent) : QWidget(parent), + color_(Qt::red) { + /// 确定画图样式 + switch (model) { + case MODEL::Arrows: + { + drawFunc_ = &OEModelView::drawArrows; + break; + } + default: + { + drawFunc_ = &OEModelView::drawArrows; + } + } +} + + +void OEModelView::paintEvent(QPaintEvent *) { + QPainter paiter(this); + + /// @test : 测试变量 + startPoint_ = QPoint(width(),height()); + endPoint_ = {}; + + /// 绘制图形 + (this->*drawFunc_)(startPoint_, endPoint_, paiter); +} + + +void OEModelView::drawArrows(const QPoint& startPoint, + const QPoint& endPoint, + QPainter &paiter) { + /// 消锯齿 + paiter.setRenderHint(QPainter::Antialiasing, true); + /// 创建画笔,设置画刷 + QPen pen; + pen.setColor(color_); + pen.setWidth(1); + paiter.setPen(pen); + paiter.setBrush(color_); + + + /// 箭头部分三角形的腰长 + double par = 15.0; + double slopy = atan2((endPoint.y() - startPoint.y()), + (endPoint.x() - startPoint.x())); + double cos_y = cos(slopy); + double sin_y = sin(slopy); + QPoint head_point1 = QPoint(endPoint.x() + int(-par*cos_y - (par / 2.0 * sin_y)), + endPoint.y() + int(-par*sin_y + (par / 2.0 * cos_y))); + QPoint head_point2 = QPoint(endPoint.x() + int(-par*cos_y + (par / 2.0 * sin_y)), + endPoint.y() - int(par / 2.0*cos_y + par * sin_y)); + QPoint head_points[3] = { endPoint, head_point1, head_point2 }; + /// 绘制箭头部分 + paiter.drawPolygon(head_points, 3); + + + /// 计算箭身部分 + int offset_x = int(par*sin_y / 3); + int offset_y = int(par*cos_y / 3); + QPoint body_point1, body_point2; + body_point1 = QPoint(endPoint.x() + int(-par*cos_y - (par / 2.0*sin_y)) + + offset_x, endPoint.y() + int(-par*sin_y + (par / 2.0*cos_y)) - offset_y); + body_point2 = QPoint(endPoint.x() + int(-par*cos_y + (par / 2.0*sin_y) - offset_x), + endPoint.y() - int(par / 2.0*cos_y + par*sin_y) + offset_y); + QPoint body_points[3] = { startPoint, body_point1, body_point2 }; + /// 绘制箭身部分 + paiter.drawPolygon(body_points, 3); + +} +void OEModelView::onColor(const QColor &color) { + color_ = color; +} diff --git a/LedOK/oescreenshot/oemodelview.h b/LedOK/oescreenshot/oemodelview.h index 6dbbd6a..56eeff9 100644 --- a/LedOK/oescreenshot/oemodelview.h +++ b/LedOK/oescreenshot/oemodelview.h @@ -1,61 +1,61 @@ -#ifndef OEMODELVIEW_H -#define OEMODELVIEW_H - -#include -#include -#include -#include - -class OEModelView : public QWidget -{ - Q_OBJECT - -public: - - /** - * @brief : 模型种类 - */ - enum MODEL{ - Arrows = 0, /// 箭头 - Rectangle = 1, /// 矩形 - Roundness /// 圆形 - }; - -private: - typedef void (OEModelView::*PDRAWFUNC) - (const QPoint &,const QPoint &, QPainter&); - - -signals: - -public: - explicit OEModelView(MODEL model = MODEL::Arrows, - QWidget *parent = 0); - -protected: - - /** - * @brief : 自绘事件 - */ - virtual void paintEvent(QPaintEvent *); - -private: - - void drawArrows(const QPoint &startPoint, - const QPoint &endPoint, - QPainter& paiter); - -public slots: - - void onColor(const QColor &color); - -private: - QColor color_; - PDRAWFUNC drawFunc_; - /// @bug : 莫名,开启此处变量的声明,程序就会崩溃。 -// QPoint ssPoint331_; -// QPoint esoint233_; -}; - - -#endif // OEMODELVIEW_H +#ifndef OEMODELVIEW_H +#define OEMODELVIEW_H + +#include +#include +#include +#include + +class OEModelView : public QWidget +{ + Q_OBJECT + +public: + + /** + * @brief : 模型种类 + */ + enum MODEL{ + Arrows = 0, /// 箭头 + Rectangle = 1, /// 矩形 + Roundness /// 圆形 + }; + +private: + typedef void (OEModelView::*PDRAWFUNC) + (const QPoint &,const QPoint &, QPainter&); + + +signals: + +public: + explicit OEModelView(MODEL model = MODEL::Arrows, + QWidget *parent = 0); + +protected: + + /** + * @brief : 自绘事件 + */ + virtual void paintEvent(QPaintEvent *); + +private: + + void drawArrows(const QPoint &startPoint, + const QPoint &endPoint, + QPainter& paiter); + +public slots: + + void onColor(const QColor &color); + +private: + QColor color_; + PDRAWFUNC drawFunc_; + /// @bug : 莫名,开启此处变量的声明,程序就会崩溃。 +// QPoint ssPoint331_; +// QPoint esoint233_; +}; + + +#endif // OEMODELVIEW_H diff --git a/LedOK/oescreenshot/oescreenshot.cpp b/LedOK/oescreenshot/oescreenshot.cpp index 9b846a5..fdece1e 100644 --- a/LedOK/oescreenshot/oescreenshot.cpp +++ b/LedOK/oescreenshot/oescreenshot.cpp @@ -1,768 +1,768 @@ -/** - * @author : 陈鲁勇 - * @date : 2017年04月 - * @version: 1.0 - * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; - * 除非遵守本许可,否则您不能使用这个文件。 - * @remarks: 您可以获得该许可的副本: - * http://www.apache.org/licenses/LICENSE-2.0 - * 除非适用法律需要或者书面同意,按本许可分发的软件 - * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 - * 参见按照本许可控制许可权限及限制的特定语言的许可证。 - * - * 你可以获得该代码的最新版本: - * - * https://git.oschina.net/Mr_ChenLuYong/screenshot - * - * 开源社区的所有人都期待与你的共同维护。 - * - * - * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: - * - * 博客地址:http://blog.csdn.net/csnd_ayo - * - * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 - * - * 期待你提交Bug,欢迎Issues。 - * -*/ - -#include "oescreenshot.h" - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifndef QT_NO_DEBUG -#include -#endif - -#include - -#include "oeamplifier.h" -#include "oecommonhelper.h" - - -/// 鼠标按钮图片的十六进制数据 -static const unsigned char uc_mouse_image[] = { - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52 - ,0x00, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x2D, 0x08, 0x06, 0x00, 0x00, 0x00, 0x52, 0xE9, 0x60 - ,0xA2, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0B, 0x13, 0x00, 0x00, 0x0B - ,0x13, 0x01, 0x00, 0x9A, 0x9C, 0x18, 0x00, 0x00, 0x01, 0x40, 0x49, 0x44, 0x41, 0x54, 0x58, 0x85 - ,0xED, 0xD5, 0x21, 0x6E, 0xC3, 0x30, 0x14, 0xC6, 0xF1, 0xFF, 0x9B, 0xC6, 0x36, 0x30, 0x38, 0xA9 - ,0x05, 0x01, 0x05, 0x81, 0x05, 0x03, 0x39, 0xCA, 0x60, 0x8F, 0xD2, 0x03, 0xEC, 0x10, 0x3B, 0x46 - ,0xC1, 0xC0, 0xC6, 0x0A, 0x3B, 0x96, 0xB1, 0x80, 0x82, 0xC1, 0x56, 0x2A, 0xFF, 0x06, 0xE2, 0x36 - ,0x75, 0x9A, 0xB4, 0xCA, 0xEC, 0x4E, 0x9A, 0xE4, 0x2F, 0xB2, 0x42, 0x22, 0xFF, 0xF2, 0xFC, 0x9C - ,0x18, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0xFE, 0x55, 0xE4, 0xC6, 0xA0 - ,0xDC, 0xC4, 0x71, 0x87, 0xC1, 0xC1, 0x68, 0x01, 0xCC, 0x06, 0xC2, 0x51, 0xD0, 0x29, 0xB0, 0x18 - ,0x00, 0xDF, 0xC6, 0x40, 0x33, 0x37, 0x84, 0x30, 0x4C, 0x80, 0x85, 0xCE, 0x7B, 0x2E, 0x2A, 0x91 - ,0x84, 0x24, 0xBE, 0x25, 0xDE, 0x25, 0x5E, 0x2F, 0x6E, 0xAE, 0xD0, 0x37, 0x92, 0x10, 0xF0, 0x09 - ,0x54, 0x40, 0xE9, 0xEE, 0x15, 0xC6, 0xA2, 0x77, 0xFE, 0xE0, 0xE5, 0x85, 0x8F, 0x16, 0x58, 0xDF - ,0x35, 0x06, 0x5B, 0xD3, 0xB9, 0xD4, 0x11, 0xD0, 0xA5, 0x8F, 0xDE, 0x57, 0x75, 0x83, 0x73, 0x50 - ,0x06, 0xF6, 0x72, 0x0A, 0x47, 0x40, 0x57, 0x0D, 0x38, 0xDE, 0xC0, 0x04, 0x6F, 0x68, 0x05, 0x36 - ,0xF5, 0xE1, 0x08, 0x3D, 0xCD, 0xEA, 0xEA, 0x5A, 0xD8, 0xBE, 0x5A, 0x46, 0xB0, 0x05, 0x1E, 0xAC - ,0xF1, 0xC2, 0xD1, 0xCC, 0x01, 0x6D, 0x74, 0x02, 0xDB, 0x3B, 0xBF, 0xD3, 0x73, 0x07, 0x87, 0x2F - ,0xEF, 0x53, 0x07, 0x38, 0x82, 0x2F, 0xF6, 0xFB, 0xB8, 0x81, 0x73, 0x41, 0x69, 0x28, 0x3A, 0x7A - ,0x5C, 0xDD, 0x73, 0xCF, 0x3A, 0x86, 0xA3, 0x05, 0x87, 0xEA, 0xCC, 0x60, 0xA1, 0x06, 0x75, 0x89 - ,0xFE, 0x77, 0x92, 0x76, 0x68, 0x23, 0xEF, 0x88, 0xD3, 0x4C, 0xA8, 0x10, 0x7A, 0xD4, 0xEF, 0x8E - ,0xBE, 0x8B, 0x68, 0x79, 0x3A, 0xB1, 0x72, 0xE1, 0xAE, 0xBC, 0x13, 0x0D, 0xDE, 0xBD, 0x3D, 0xF3 - ,0x08, 0x15, 0xD4, 0xDF, 0x4C, 0x06, 0x36, 0xF7, 0x9E, 0x09, 0xED, 0xE9, 0x99, 0x97, 0x3E, 0x42 - ,0xFF, 0x30, 0x42, 0x4B, 0xA1, 0x8D, 0xD8, 0xE9, 0x2A, 0xBD, 0xED, 0x41, 0x25, 0x2A, 0x89, 0x37 - ,0x1F, 0xBD, 0xEA, 0x61, 0x8B, 0x5F, 0xDD, 0xC1, 0xFA, 0x01, 0xD8, 0xA3, 0x8F, 0xFB, 0xCA, 0x70 - ,0x16, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 -}; - - - -OEScreenshot * OEScreenshot::self_ = nullptr; -bool OEScreenshot::isActivity_ = false; -bool OEScreen::isInit_ = false; - -OEScreenshot::OEScreenshot(QWidget *parent) : QWidget(parent), - isLeftPressed_ (false), backgroundScreen_(nullptr), - originPainting_(nullptr), screenTool_(nullptr) { - /// 初始化鼠标 - initCursor(); - /// 截取屏幕信息 - initGlobalScreen(); - /// 初始化鼠标放大器 - initAmplifier(); - /// 初始化大小感知器 - initMeasureWidget(); - /// 全屏窗口 - showFullScreen(); - /// 窗口与显示屏对齐 - setGeometry(getScreenRect()); - /// 霸道置顶 - onEgoistic(); - /// 开启鼠标实时追踪 - setMouseTracking(true); - /// 更新鼠标的位置 - emit cursorPosChange(cursor().pos().x(), cursor().pos().y()); - /// 更新鼠标区域窗口 - updateMouse(); - /// 展示窗口 - show(); -} - -OEScreenshot::~OEScreenshot(void) { -} - -/** - * @brief:窗口实例 - * @return:OEScreenshot - */ -OEScreenshot *OEScreenshot::Instance(void) { - if (!isActivity_ && self_) { - destroy(); - } - static QMutex mutex; - if (!self_) { - QMutexLocker locker(&mutex); - if (!self_) { - isActivity_ = true; - self_ = new OEScreenshot; - } - } - return self_; -} - -void OEScreenshot::destroy(void) { - if (!isActivity_ && self_) { - delete self_; - self_ = nullptr; - } -} - -void OEScreenshot::hideEvent(QHideEvent *) { - isActivity_ = false; -} - - -void OEScreenshot::closeEvent(QCloseEvent *) { - isActivity_ = false; -} - -void OEScreenshot::mouseDoubleClickEvent(QMouseEvent *) { - emit doubleClick(); -} - - -/** - * 初始化放大镜 (色彩采集器) - */ -void OEScreenshot::initAmplifier(std::shared_ptr originPainting) { - std::shared_ptr temp_pm = originPainting; - if (temp_pm == nullptr) { - temp_pm = originPainting_; - } - amplifierTool_.reset(new OEAmplifier(temp_pm, this)); - connect(this,SIGNAL(cursorPosChange(int,int)), - amplifierTool_.get(), SLOT(onPostionChange(int,int))); - amplifierTool_->show(); - amplifierTool_->raise(); -} - -void OEScreenshot::initMeasureWidget(void) -{ - rectTool_.reset(new OERect(this)); - rectTool_->raise(); -} - -/** - * 功能:获得当前屏幕的大小 - */ -const QRect &OEScreenshot::getScreenRect(void) { - if (!desktopRect_.isEmpty()) { - return desktopRect_; - } - /// 获得屏幕个数 - int temp_screen_num = QApplication::screens().size(); - /// 获得屏幕大小 - desktopRect_ = QApplication::desktop()->rect(); - if (temp_screen_num != 1) { - /// 多屏幕策略 - const int& temp = desktopRect_.width() - - (desktopRect_.width() / temp_screen_num); - /// 重新设置矩形 - desktopRect_ = QRect(-temp, 0, - desktopRect_.width(), desktopRect_.height()); - } - return desktopRect_; -} - -std::shared_ptr OEScreenshot::initGlobalScreen(void) { - if (backgroundScreen_.get() != nullptr) { - return backgroundScreen_; - } - /// 获得屏幕原画 - std::shared_ptr temp_screen = getGlobalScreen(); - - /// 制作暗色屏幕背景 - QPixmap temp_dim_pix(temp_screen->width(), temp_screen->height()); - temp_dim_pix.fill((QColor(0, 0, 0, 160))); - backgroundScreen_.reset(new QPixmap(*temp_screen)); - QPainter p(backgroundScreen_.get()); - p.drawPixmap(0, 0, temp_dim_pix); - - return backgroundScreen_; -} - -/* - * 获得屏幕的原画 - * 返回:QPixmap* 指针 - */ -std::shared_ptr OEScreenshot::getGlobalScreen(void) { - if (originPainting_.get() == nullptr) { - /// 截取当前桌面,作为截屏的背景图 - QScreen *screen = QGuiApplication::primaryScreen(); - const QRect& temp_rect = getScreenRect(); - originPainting_.reset(new QPixmap(screen->grabWindow(0, temp_rect.x(), - temp_rect.y(), temp_rect.width(), - temp_rect.height()))); - } - return originPainting_; -} -void OEScreenshot::onEgoistic(void) -{ - /// 窗口置顶 -#ifdef Q_OS_WIN32 - // SetWindowPos(HWND)this->winId(),HWND_TOPMOST,this->pos().x(),this->pos().y(),this->width(),this->height(),SWP_SHOWWINDOW); -#else - Qt::WindowFlags flags = windowFlags(); - flags |= Qt::WindowStaysOnTopHint; - setWindowFlags(flags); -#endif -} - -/* - * 初始化鼠标 - * 参数:_ico 鼠标图片的资源文件 - */ -void OEScreenshot::initCursor(const QString& ico) { - QPixmap pixmap; - if (ico.isEmpty()) { - pixmap.loadFromData(uc_mouse_image, sizeof(uc_mouse_image)); - } - else { - pixmap.load(ico); - } - QCursor cursor; - cursor = QCursor(pixmap, 15, 23); - setCursor(cursor); -} - -std::shared_ptr OEScreenshot::createScreen(const QPoint &pos) { - if (screenTool_.get() == nullptr) { - /// 创建截图器 - screenTool_.reset(new OEScreen(originPainting_, pos, this)); - /// 建立信号连接 - connect (this, SIGNAL(cursorPosChange(int,int)), - screenTool_.get(),SLOT(onMouseChange(int,int))); - /// 建立主界面双击保存信号关联 - connect (this, SIGNAL(doubleClick()), - screenTool_.get(),SLOT(onSaveScreen())); - /// 建立截图器大小关联 - connect(screenTool_.get(), SIGNAL(sizeChange(int,int)), - rectTool_.get(), SLOT(onSizeChange(int,int))); - connect(screenTool_.get(), SIGNAL(sizeChange(int,int)), - amplifierTool_.get(), SLOT(onSizeChange(int,int))); - /// 建立截图器与感知器的位置关联 - connect(screenTool_.get(), SIGNAL(postionChange(int,int)), - rectTool_.get(), SLOT(onPostionChange(int,int))); - - /// 获得截图器当前起始位置 - startPoint_ = pos; - isLeftPressed_ = true; - } - return screenTool_; -} - -void OEScreenshot::destroyScreen() { - if (screenTool_.get() != nullptr) { - /// 断开信号资源 - disconnect (this, SIGNAL(doubleClick()), - screenTool_.get(),SLOT(onSaveScreen())); - disconnect(screenTool_.get(), SIGNAL(sizeChange(int,int)), - rectTool_.get(), SLOT(onSizeChange(int,int))); - disconnect(screenTool_.get(), SIGNAL(postionChange(int,int)), - rectTool_.get(), SLOT(onPostionChange(int,int))); - /// 清理工具 - screenTool_.reset(); - screenTool_ = nullptr; - isLeftPressed_ = false; - update(); - return; - } -} - -void OEScreenshot::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { - createScreen(e->pos()); - return ; - } -} - -void OEScreenshot::mouseReleaseEvent(QMouseEvent *e) { - if (e->button() == Qt::RightButton) { - if (screenTool_.get() != nullptr) { - rectTool_->hide(); - amplifierTool_->onPostionChange(e->x(), e->y()); - amplifierTool_->show(); - return destroyScreen(); - } - close(); - return ; - } - else if (isLeftPressed_ == true - && e->button() == Qt::LeftButton) { - /// 选择窗口选区 - if (startPoint_ == e->pos() - && !windowRect_.isEmpty()) { - screenTool_->setGeometry(windowRect_); - screenTool_->show(); - windowRect_ = {}; - } - /// 断开鼠标移动的信号 - disconnect (this, SIGNAL(cursorPosChange(int,int)), - screenTool_.get(),SLOT(onMouseChange(int,int))); - /// 隐藏放大器 - amplifierTool_->hide(); - /// 断开截图器的大小修改信号 - disconnect (screenTool_.get(), SIGNAL(sizeChange(int,int)), - amplifierTool_.get(),SLOT(onSizeChange(int,int))); - isLeftPressed_ = false; - } - QWidget::mouseReleaseEvent(e); -} - -void OEScreenshot::mouseMoveEvent(QMouseEvent *e) { - emit cursorPosChange(e->x(), e->y()); - if (isLeftPressed_) { - amplifierTool_->raise(); - windowRect_ = {}; - update(); - } - else if (isLeftPressed_ == false - && false == OEScreen::state()){ - /// 霸道置顶 - onEgoistic(); - - /// 更新当前鼠标选中的窗口 - updateMouse(); - } - QWidget::mouseMoveEvent(e); -} - -void OEScreenshot::paintEvent(QPaintEvent *) { - QPainter painter(this); - /// 画全屏图 - painter.drawPixmap(0,0,desktopRect_.width(), - desktopRect_.height(), *backgroundScreen_); - - if (!windowRect_.isEmpty()) { - /// 绘制选区 - QPen pen = painter.pen(); - pen.setColor(QColor(0,175,255)); - pen.setWidth(2); - painter.setPen(pen); - painter.drawRect(windowRect_.x(),windowRect_.y(), - windowRect_.width(),windowRect_.height()); - painter.drawPixmap(QPoint(windowRect_.x(),windowRect_.y()), - *originPainting_, windowRect_); - } -} - -void OEScreenshot::updateMouse(void) { - /// 获取当前鼠标选中的窗口 - ::EnableWindow((HWND)winId(), FALSE); - OECommonHelper::getSmallestWindowFromCursor(windowRect_); - QPoint temp_pt = mapFromGlobal(QPoint(windowRect_.x(), windowRect_.y())); - windowRect_ = QRect(temp_pt.x(), temp_pt.y(), - windowRect_.width(), windowRect_.height()); - ::EnableWindow((HWND)winId(), TRUE); - amplifierTool_->onSizeChange(windowRect_.width(),windowRect_.height()); - emit findChildWind(windowRect_); - update(); -} - -void OEScreenshot::keyPressEvent(QKeyEvent *e) { - /// Esc 键退出截图; - if (e->key() == Qt::Key_Escape) { - close(); - } - else { - e->ignore(); - } - -} - - - -/////////////////////////////////////////////////////////// - - - - -OERect::OERect(QWidget *parent) : QWidget(parent) { - - /// 设置感知器默认大小 - setFixedSize(95 * OECommonHelper::getWindowHeightMultiplyingPower(), - 20 * OECommonHelper::getWindowHeightMultiplyingPower()); - - /// 填充默认背景 - backgroundPixmap_.reset(new QPixmap(width(),height())); - backgroundPixmap_->fill((QColor(8, 8, 8, 160))); - - /// 默认隐藏 - hide(); -} - - -void OERect::paintEvent(QPaintEvent *) { - QPainter painter(this); - painter.drawPixmap(rect(),*backgroundPixmap_); - painter.setPen(QPen(QColor(Qt::white))); - painter.drawText(rect(), Qt::AlignCenter, info_); -} - -void OERect::onPostionChange(int x, int y) { - if (x < 0) x = 0; - if (y < 0) y = 0; - const int& ry = y - height() - 1; - if (ry < 0) { - this->raise(); - } - move(x, ((ry < 0) ? y : ry)); - show(); -} - -void OERect::onSizeChange(int w, int h) { - info_ = QString("%1 × %2").arg(w).arg(h); -} - - - - -/////////////////////////////////////////////////////////// - - - - - -OEScreen::OEScreen(std::shared_ptr originPainting, QPoint pos, QWidget *parent) - : QWidget(parent), direction_(NONE), originPoint_(pos), - isPressed_(false), originPainting_(originPainting) { - menu_ = new QMenu(this); - menu_->addAction("完成截图", this, SLOT(onSaveScreen())); - menu_->addAction("保存", this, SLOT(onSaveScreenOther())); - menu_->addSeparator(); - menu_->addAction("退出截图", this, SLOT(quitScreenshot())); - - /// 双击即完成 - connect(this, SIGNAL(doubleClick()), - this, SLOT(onSaveScreen())); - - /// 开启鼠标实时追踪 - setMouseTracking(true); - /// 默认隐藏 - hide(); -} - -OEScreen::DIRECTION OEScreen::getRegion(const QPoint &cursor) { - if (!isInit_) { - return NONE; - } - OEScreen::DIRECTION ret_dir = NONE; - // left upper - QPoint pt_lu = mapToParent(rect().topLeft()); - // right lower - QPoint pt_rl = mapToParent(rect().bottomRight()); - - int x = cursor.x(); - int y = cursor.y(); - - /// 获得鼠标当前所处窗口的边界方向 - if(pt_lu.x() + PADDING_ >= x - && pt_lu.x() <= x - && pt_lu.y() + PADDING_ >= y - && pt_lu.y() <= y) { - // 左上角 - ret_dir = LEFTUPPER; - this->setCursor(QCursor(Qt::SizeFDiagCursor)); - } else if(x >= pt_rl.x() - PADDING_ - && x <= pt_rl.x() - && y >= pt_rl.y() - PADDING_ - && y <= pt_rl.y()) { - // 右下角 - ret_dir = RIGHTLOWER; - this->setCursor(QCursor(Qt::SizeFDiagCursor)); - } else if(x <= pt_lu.x() + PADDING_ - && x >= pt_lu.x() - && y >= pt_rl.y() - PADDING_ - && y <= pt_rl.y()) { - // 左下角 - ret_dir = LEFTLOWER; - this->setCursor(QCursor(Qt::SizeBDiagCursor)); - } else if(x <= pt_rl.x() - && x >= pt_rl.x() - PADDING_ - && y >= pt_lu.y() - && y <= pt_lu.y() + PADDING_) { - // 右上角 - ret_dir = RIGHTUPPER; - this->setCursor(QCursor(Qt::SizeBDiagCursor)); - } else if(x <= pt_lu.x() + PADDING_ - && x >= pt_lu.x()) { - // 左边 - ret_dir = LEFT; - this->setCursor(QCursor(Qt::SizeHorCursor)); - } else if( x <= pt_rl.x() - && x >= pt_rl.x() - PADDING_) { - // 右边 - ret_dir = RIGHT; - this->setCursor(QCursor(Qt::SizeHorCursor)); - }else if(y >= pt_lu.y() - && y <= pt_lu.y() + PADDING_){ - // 上边 - ret_dir = UPPER; - this->setCursor(QCursor(Qt::SizeVerCursor)); - } else if(y <= pt_rl.y() - && y >= pt_rl.y() - PADDING_) { - // 下边 - ret_dir = LOWER; - this->setCursor(QCursor(Qt::SizeVerCursor)); - }else { - // 默认 - ret_dir = NONE; - this->setCursor(QCursor(Qt::SizeAllCursor)); - } - return ret_dir; -} - - -void OEScreen::contextMenuEvent(QContextMenuEvent *) { - /// 在鼠标位置弹射出菜单栏 - menu_->exec(cursor().pos()); -} - -void OEScreen::mouseDoubleClickEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { - emit doubleClick(); - e->accept(); - } -} - -void OEScreen::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { - isPressed_ = true; - if(direction_ != NONE) { - this->mouseGrabber(); - } - /// @bug :这里可能存在问题, 不应当使用globalPos - movePos_ = e->globalPos() - pos(); - } -} - -void OEScreen::mouseReleaseEvent(QMouseEvent * e) { - if (e->button() == Qt::LeftButton) { - isPressed_ = false; - if(direction_ != NONE) { - setCursor(QCursor(Qt::SizeAllCursor)); - } - } -} - -void OEScreen::mouseMoveEvent(QMouseEvent * e) { - QPoint gloPoint = mapToParent(e->pos()); - // left upper - QPoint pt_lu = mapToParent(rect().topLeft()); - // left lower - QPoint pt_ll = mapToParent(rect().bottomLeft()); - // right lower - QPoint pt_rl = mapToParent(rect().bottomRight()); - // right upper - QPoint pt_ru = mapToParent(rect().topRight()); - if(!isPressed_) { - /// 检查鼠标鼠标方向 - direction_ = getRegion(gloPoint); - - /// 根据方位判断拖拉对应支点 - switch(direction_) { - case NONE: - case RIGHT: - case RIGHTLOWER: - originPoint_ = pt_lu; - break; - case RIGHTUPPER: - originPoint_ = pt_ll; - break; - case LEFT: - case LEFTLOWER: - originPoint_ = pt_ru; - break; - case LEFTUPPER: - case UPPER: - originPoint_ = pt_rl; - break; - case LOWER: - originPoint_ = pt_lu; - break; - } - } - else { - if(direction_ != NONE) { - const int& global_x = gloPoint.x(); - /// 鼠标进行拖拉拽 - switch(direction_) { - case LEFT: - return onMouseChange(global_x, pt_ll.y() + 1); - case RIGHT: - return onMouseChange(global_x, pt_rl.y() + 1); - case UPPER: - return onMouseChange(pt_lu.x(), gloPoint.y()); - case LOWER: - return onMouseChange(pt_rl.x() + 1, gloPoint.y()); - case LEFTUPPER: - case RIGHTUPPER: - case LEFTLOWER: - case RIGHTLOWER: - return onMouseChange(global_x, gloPoint.y()); - default: - break; - } - } - else { - /// 窗口的移动 - /// @bug :这里可能存在问题, 不应当使用globalPos - move(e->globalPos() - movePos_); - movePos_ = e->globalPos() - pos(); - e->accept(); - } - } - currentRect_ = geometry(); -} - -void OEScreen::moveEvent(QMoveEvent *) { - emit postionChange(x(), y()); -} - -void OEScreen::resizeEvent(QResizeEvent *) { - listMarker_.clear(); - - /// 重新计算八个锚点 - // 角点 - listMarker_.push_back(QPoint(0, 0)); - listMarker_.push_back(QPoint(width(), 0)); - listMarker_.push_back(QPoint(0, height())); - listMarker_.push_back(QPoint(width(), height())); - - // 中点 - listMarker_.push_back(QPoint((width() >> 1), 0)); - listMarker_.push_back(QPoint((width() >> 1), height())); - listMarker_.push_back(QPoint(0, (height() >> 1))); - listMarker_.push_back(QPoint(width(), (height() >> 1))); - - emit sizeChange(width(), height()); -} - -void OEScreen::showEvent(QShowEvent *) { - isInit_ = true; -} - -void OEScreen::hideEvent(QHideEvent *) { - currentRect_ = {}; - movePos_ = {}; - originPoint_ = {}; - isInit_ = false; -} - -void OEScreen::enterEvent(QEvent *e) { - setCursor(Qt::SizeAllCursor); - QWidget::enterEvent(e); -} - -void OEScreen::leaveEvent(QEvent *e) { - setCursor(Qt::ArrowCursor); - QWidget::leaveEvent(e); -} - -void OEScreen::closeEvent(QCloseEvent *) -{ - isInit_ = false; -} - -void OEScreen::paintEvent(QPaintEvent *) { - QPainter painter(this); - /// 绘制截屏编辑窗口 - painter.drawPixmap(QPoint(0,0), - *originPainting_, currentRect_); - - /// 绘制边框线 - QPen pen(QColor(0,174,255),2); - painter.setPen(pen); - painter.drawRect(rect()); - - /// 绘制八个点 - //改变点的宽度 - pen.setWidth(4); - pen.setColor(Qt::red); - painter.setPen(pen); - painter.drawPoints(listMarker_); -} - - -const QString OEScreen::getFileName(void) { - QString file_name = QDateTime::currentDateTime().toString("CSDN博客_瓯裔_yyyy-MM-dd-HH-mm-ss"); - return file_name; -} - - -void OEScreen::onSaveScreenOther(void) { - - QString fileName = QFileDialog::getSaveFileName(this, "保存图片", getFileName(), "JPEG Files (*.jpg)"); - if (fileName.length() > 0) { - originPainting_->copy(currentRect_).save(fileName, "jpg"); - quitScreenshot(); - } -} - -void OEScreen::onSaveScreen(void) { - /// 把图片放入剪切板 - QClipboard *board = QApplication::clipboard(); - board->setPixmap(originPainting_->copy(currentRect_)); - /// 退出当前截图工具 - quitScreenshot(); -} - - -void OEScreen::quitScreenshot(void) { - close(); - parentWidget()->close(); -} - -void OEScreen::onMouseChange(int x, int y) { - show(); - if (x < 0 || y < 0) { - return; - } - const int& rx = (x >= originPoint_.x()) ? originPoint_.x() : x; - const int& ry = (y >= originPoint_.y()) ? originPoint_.y() : y; - const int& rw = abs(x - originPoint_.x()); - const int& rh = abs(y - originPoint_.y()); - - /// 改变大小 - currentRect_ = QRect(rx, ry, rw, rh); - - this->setGeometry(currentRect_); - /// 改变大小后更新父窗口,防止父窗口未及时刷新而导致的问题 - parentWidget()->update(); -} +/** + * @author : 陈鲁勇 + * @date : 2017年04月 + * @version: 1.0 + * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; + * 除非遵守本许可,否则您不能使用这个文件。 + * @remarks: 您可以获得该许可的副本: + * http://www.apache.org/licenses/LICENSE-2.0 + * 除非适用法律需要或者书面同意,按本许可分发的软件 + * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 + * 参见按照本许可控制许可权限及限制的特定语言的许可证。 + * + * 你可以获得该代码的最新版本: + * + * https://git.oschina.net/Mr_ChenLuYong/screenshot + * + * 开源社区的所有人都期待与你的共同维护。 + * + * + * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: + * + * 博客地址:http://blog.csdn.net/csnd_ayo + * + * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 + * + * 期待你提交Bug,欢迎Issues。 + * +*/ + +#include "oescreenshot.h" + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef QT_NO_DEBUG +#include +#endif + +#include + +#include "oeamplifier.h" +#include "oecommonhelper.h" + + +/// 鼠标按钮图片的十六进制数据 +static const unsigned char uc_mouse_image[] = { + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52 + ,0x00, 0x00, 0x00, 0x1D, 0x00, 0x00, 0x00, 0x2D, 0x08, 0x06, 0x00, 0x00, 0x00, 0x52, 0xE9, 0x60 + ,0xA2, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0B, 0x13, 0x00, 0x00, 0x0B + ,0x13, 0x01, 0x00, 0x9A, 0x9C, 0x18, 0x00, 0x00, 0x01, 0x40, 0x49, 0x44, 0x41, 0x54, 0x58, 0x85 + ,0xED, 0xD5, 0x21, 0x6E, 0xC3, 0x30, 0x14, 0xC6, 0xF1, 0xFF, 0x9B, 0xC6, 0x36, 0x30, 0x38, 0xA9 + ,0x05, 0x01, 0x05, 0x81, 0x05, 0x03, 0x39, 0xCA, 0x60, 0x8F, 0xD2, 0x03, 0xEC, 0x10, 0x3B, 0x46 + ,0xC1, 0xC0, 0xC6, 0x0A, 0x3B, 0x96, 0xB1, 0x80, 0x82, 0xC1, 0x56, 0x2A, 0xFF, 0x06, 0xE2, 0x36 + ,0x75, 0x9A, 0xB4, 0xCA, 0xEC, 0x4E, 0x9A, 0xE4, 0x2F, 0xB2, 0x42, 0x22, 0xFF, 0xF2, 0xFC, 0x9C + ,0x18, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0x52, 0xFE, 0x55, 0xE4, 0xC6, 0xA0 + ,0xDC, 0xC4, 0x71, 0x87, 0xC1, 0xC1, 0x68, 0x01, 0xCC, 0x06, 0xC2, 0x51, 0xD0, 0x29, 0xB0, 0x18 + ,0x00, 0xDF, 0xC6, 0x40, 0x33, 0x37, 0x84, 0x30, 0x4C, 0x80, 0x85, 0xCE, 0x7B, 0x2E, 0x2A, 0x91 + ,0x84, 0x24, 0xBE, 0x25, 0xDE, 0x25, 0x5E, 0x2F, 0x6E, 0xAE, 0xD0, 0x37, 0x92, 0x10, 0xF0, 0x09 + ,0x54, 0x40, 0xE9, 0xEE, 0x15, 0xC6, 0xA2, 0x77, 0xFE, 0xE0, 0xE5, 0x85, 0x8F, 0x16, 0x58, 0xDF + ,0x35, 0x06, 0x5B, 0xD3, 0xB9, 0xD4, 0x11, 0xD0, 0xA5, 0x8F, 0xDE, 0x57, 0x75, 0x83, 0x73, 0x50 + ,0x06, 0xF6, 0x72, 0x0A, 0x47, 0x40, 0x57, 0x0D, 0x38, 0xDE, 0xC0, 0x04, 0x6F, 0x68, 0x05, 0x36 + ,0xF5, 0xE1, 0x08, 0x3D, 0xCD, 0xEA, 0xEA, 0x5A, 0xD8, 0xBE, 0x5A, 0x46, 0xB0, 0x05, 0x1E, 0xAC + ,0xF1, 0xC2, 0xD1, 0xCC, 0x01, 0x6D, 0x74, 0x02, 0xDB, 0x3B, 0xBF, 0xD3, 0x73, 0x07, 0x87, 0x2F + ,0xEF, 0x53, 0x07, 0x38, 0x82, 0x2F, 0xF6, 0xFB, 0xB8, 0x81, 0x73, 0x41, 0x69, 0x28, 0x3A, 0x7A + ,0x5C, 0xDD, 0x73, 0xCF, 0x3A, 0x86, 0xA3, 0x05, 0x87, 0xEA, 0xCC, 0x60, 0xA1, 0x06, 0x75, 0x89 + ,0xFE, 0x77, 0x92, 0x76, 0x68, 0x23, 0xEF, 0x88, 0xD3, 0x4C, 0xA8, 0x10, 0x7A, 0xD4, 0xEF, 0x8E + ,0xBE, 0x8B, 0x68, 0x79, 0x3A, 0xB1, 0x72, 0xE1, 0xAE, 0xBC, 0x13, 0x0D, 0xDE, 0xBD, 0x3D, 0xF3 + ,0x08, 0x15, 0xD4, 0xDF, 0x4C, 0x06, 0x36, 0xF7, 0x9E, 0x09, 0xED, 0xE9, 0x99, 0x97, 0x3E, 0x42 + ,0xFF, 0x30, 0x42, 0x4B, 0xA1, 0x8D, 0xD8, 0xE9, 0x2A, 0xBD, 0xED, 0x41, 0x25, 0x2A, 0x89, 0x37 + ,0x1F, 0xBD, 0xEA, 0x61, 0x8B, 0x5F, 0xDD, 0xC1, 0xFA, 0x01, 0xD8, 0xA3, 0x8F, 0xFB, 0xCA, 0x70 + ,0x16, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 +}; + + + +OEScreenshot * OEScreenshot::self_ = nullptr; +bool OEScreenshot::isActivity_ = false; +bool OEScreen::isInit_ = false; + +OEScreenshot::OEScreenshot(QWidget *parent) : QWidget(parent), + isLeftPressed_ (false), backgroundScreen_(nullptr), + originPainting_(nullptr), screenTool_(nullptr) { + /// 初始化鼠标 + initCursor(); + /// 截取屏幕信息 + initGlobalScreen(); + /// 初始化鼠标放大器 + initAmplifier(); + /// 初始化大小感知器 + initMeasureWidget(); + /// 全屏窗口 + showFullScreen(); + /// 窗口与显示屏对齐 + setGeometry(getScreenRect()); + /// 霸道置顶 + onEgoistic(); + /// 开启鼠标实时追踪 + setMouseTracking(true); + /// 更新鼠标的位置 + emit cursorPosChange(cursor().pos().x(), cursor().pos().y()); + /// 更新鼠标区域窗口 + updateMouse(); + /// 展示窗口 + show(); +} + +OEScreenshot::~OEScreenshot(void) { +} + +/** + * @brief:窗口实例 + * @return:OEScreenshot + */ +OEScreenshot *OEScreenshot::Instance(void) { + if (!isActivity_ && self_) { + destroy(); + } + static QMutex mutex; + if (!self_) { + QMutexLocker locker(&mutex); + if (!self_) { + isActivity_ = true; + self_ = new OEScreenshot; + } + } + return self_; +} + +void OEScreenshot::destroy(void) { + if (!isActivity_ && self_) { + delete self_; + self_ = nullptr; + } +} + +void OEScreenshot::hideEvent(QHideEvent *) { + isActivity_ = false; +} + + +void OEScreenshot::closeEvent(QCloseEvent *) { + isActivity_ = false; +} + +void OEScreenshot::mouseDoubleClickEvent(QMouseEvent *) { + emit doubleClick(); +} + + +/** + * 初始化放大镜 (色彩采集器) + */ +void OEScreenshot::initAmplifier(std::shared_ptr originPainting) { + std::shared_ptr temp_pm = originPainting; + if (temp_pm == nullptr) { + temp_pm = originPainting_; + } + amplifierTool_.reset(new OEAmplifier(temp_pm, this)); + connect(this,SIGNAL(cursorPosChange(int,int)), + amplifierTool_.get(), SLOT(onPostionChange(int,int))); + amplifierTool_->show(); + amplifierTool_->raise(); +} + +void OEScreenshot::initMeasureWidget(void) +{ + rectTool_.reset(new OERect(this)); + rectTool_->raise(); +} + +/** + * 功能:获得当前屏幕的大小 + */ +const QRect &OEScreenshot::getScreenRect(void) { + if (!desktopRect_.isEmpty()) { + return desktopRect_; + } + /// 获得屏幕个数 + int temp_screen_num = QApplication::screens().size(); + /// 获得屏幕大小 + desktopRect_ = QApplication::desktop()->rect(); + if (temp_screen_num != 1) { + /// 多屏幕策略 + const int& temp = desktopRect_.width() - + (desktopRect_.width() / temp_screen_num); + /// 重新设置矩形 + desktopRect_ = QRect(-temp, 0, + desktopRect_.width(), desktopRect_.height()); + } + return desktopRect_; +} + +std::shared_ptr OEScreenshot::initGlobalScreen(void) { + if (backgroundScreen_.get() != nullptr) { + return backgroundScreen_; + } + /// 获得屏幕原画 + std::shared_ptr temp_screen = getGlobalScreen(); + + /// 制作暗色屏幕背景 + QPixmap temp_dim_pix(temp_screen->width(), temp_screen->height()); + temp_dim_pix.fill((QColor(0, 0, 0, 160))); + backgroundScreen_.reset(new QPixmap(*temp_screen)); + QPainter p(backgroundScreen_.get()); + p.drawPixmap(0, 0, temp_dim_pix); + + return backgroundScreen_; +} + +/* + * 获得屏幕的原画 + * 返回:QPixmap* 指针 + */ +std::shared_ptr OEScreenshot::getGlobalScreen(void) { + if (originPainting_.get() == nullptr) { + /// 截取当前桌面,作为截屏的背景图 + QScreen *screen = QGuiApplication::primaryScreen(); + const QRect& temp_rect = getScreenRect(); + originPainting_.reset(new QPixmap(screen->grabWindow(0, temp_rect.x(), + temp_rect.y(), temp_rect.width(), + temp_rect.height()))); + } + return originPainting_; +} +void OEScreenshot::onEgoistic(void) +{ + /// 窗口置顶 +#ifdef Q_OS_WIN32 + // SetWindowPos(HWND)this->winId(),HWND_TOPMOST,this->pos().x(),this->pos().y(),this->width(),this->height(),SWP_SHOWWINDOW); +#else + Qt::WindowFlags flags = windowFlags(); + flags |= Qt::WindowStaysOnTopHint; + setWindowFlags(flags); +#endif +} + +/* + * 初始化鼠标 + * 参数:_ico 鼠标图片的资源文件 + */ +void OEScreenshot::initCursor(const QString& ico) { + QPixmap pixmap; + if (ico.isEmpty()) { + pixmap.loadFromData(uc_mouse_image, sizeof(uc_mouse_image)); + } + else { + pixmap.load(ico); + } + QCursor cursor; + cursor = QCursor(pixmap, 15, 23); + setCursor(cursor); +} + +std::shared_ptr OEScreenshot::createScreen(const QPoint &pos) { + if (screenTool_.get() == nullptr) { + /// 创建截图器 + screenTool_.reset(new OEScreen(originPainting_, pos, this)); + /// 建立信号连接 + connect (this, SIGNAL(cursorPosChange(int,int)), + screenTool_.get(),SLOT(onMouseChange(int,int))); + /// 建立主界面双击保存信号关联 + connect (this, SIGNAL(doubleClick()), + screenTool_.get(),SLOT(onSaveScreen())); + /// 建立截图器大小关联 + connect(screenTool_.get(), SIGNAL(sizeChange(int,int)), + rectTool_.get(), SLOT(onSizeChange(int,int))); + connect(screenTool_.get(), SIGNAL(sizeChange(int,int)), + amplifierTool_.get(), SLOT(onSizeChange(int,int))); + /// 建立截图器与感知器的位置关联 + connect(screenTool_.get(), SIGNAL(postionChange(int,int)), + rectTool_.get(), SLOT(onPostionChange(int,int))); + + /// 获得截图器当前起始位置 + startPoint_ = pos; + isLeftPressed_ = true; + } + return screenTool_; +} + +void OEScreenshot::destroyScreen() { + if (screenTool_.get() != nullptr) { + /// 断开信号资源 + disconnect (this, SIGNAL(doubleClick()), + screenTool_.get(),SLOT(onSaveScreen())); + disconnect(screenTool_.get(), SIGNAL(sizeChange(int,int)), + rectTool_.get(), SLOT(onSizeChange(int,int))); + disconnect(screenTool_.get(), SIGNAL(postionChange(int,int)), + rectTool_.get(), SLOT(onPostionChange(int,int))); + /// 清理工具 + screenTool_.reset(); + screenTool_ = nullptr; + isLeftPressed_ = false; + update(); + return; + } +} + +void OEScreenshot::mousePressEvent(QMouseEvent *e) { + if (e->button() == Qt::LeftButton) { + createScreen(e->pos()); + return ; + } +} + +void OEScreenshot::mouseReleaseEvent(QMouseEvent *e) { + if (e->button() == Qt::RightButton) { + if (screenTool_.get() != nullptr) { + rectTool_->hide(); + amplifierTool_->onPostionChange(e->x(), e->y()); + amplifierTool_->show(); + return destroyScreen(); + } + close(); + return ; + } + else if (isLeftPressed_ == true + && e->button() == Qt::LeftButton) { + /// 选择窗口选区 + if (startPoint_ == e->pos() + && !windowRect_.isEmpty()) { + screenTool_->setGeometry(windowRect_); + screenTool_->show(); + windowRect_ = {}; + } + /// 断开鼠标移动的信号 + disconnect (this, SIGNAL(cursorPosChange(int,int)), + screenTool_.get(),SLOT(onMouseChange(int,int))); + /// 隐藏放大器 + amplifierTool_->hide(); + /// 断开截图器的大小修改信号 + disconnect (screenTool_.get(), SIGNAL(sizeChange(int,int)), + amplifierTool_.get(),SLOT(onSizeChange(int,int))); + isLeftPressed_ = false; + } + QWidget::mouseReleaseEvent(e); +} + +void OEScreenshot::mouseMoveEvent(QMouseEvent *e) { + emit cursorPosChange(e->x(), e->y()); + if (isLeftPressed_) { + amplifierTool_->raise(); + windowRect_ = {}; + update(); + } + else if (isLeftPressed_ == false + && false == OEScreen::state()){ + /// 霸道置顶 + onEgoistic(); + + /// 更新当前鼠标选中的窗口 + updateMouse(); + } + QWidget::mouseMoveEvent(e); +} + +void OEScreenshot::paintEvent(QPaintEvent *) { + QPainter painter(this); + /// 画全屏图 + painter.drawPixmap(0,0,desktopRect_.width(), + desktopRect_.height(), *backgroundScreen_); + + if (!windowRect_.isEmpty()) { + /// 绘制选区 + QPen pen = painter.pen(); + pen.setColor(QColor(0,175,255)); + pen.setWidth(2); + painter.setPen(pen); + painter.drawRect(windowRect_.x(),windowRect_.y(), + windowRect_.width(),windowRect_.height()); + painter.drawPixmap(QPoint(windowRect_.x(),windowRect_.y()), + *originPainting_, windowRect_); + } +} + +void OEScreenshot::updateMouse(void) { + /// 获取当前鼠标选中的窗口 + ::EnableWindow((HWND)winId(), FALSE); + OECommonHelper::getSmallestWindowFromCursor(windowRect_); + QPoint temp_pt = mapFromGlobal(QPoint(windowRect_.x(), windowRect_.y())); + windowRect_ = QRect(temp_pt.x(), temp_pt.y(), + windowRect_.width(), windowRect_.height()); + ::EnableWindow((HWND)winId(), TRUE); + amplifierTool_->onSizeChange(windowRect_.width(),windowRect_.height()); + emit findChildWind(windowRect_); + update(); +} + +void OEScreenshot::keyPressEvent(QKeyEvent *e) { + /// Esc 键退出截图; + if (e->key() == Qt::Key_Escape) { + close(); + } + else { + e->ignore(); + } + +} + + + +/////////////////////////////////////////////////////////// + + + + +OERect::OERect(QWidget *parent) : QWidget(parent) { + + /// 设置感知器默认大小 + setFixedSize(95 * OECommonHelper::getWindowHeightMultiplyingPower(), + 20 * OECommonHelper::getWindowHeightMultiplyingPower()); + + /// 填充默认背景 + backgroundPixmap_.reset(new QPixmap(width(),height())); + backgroundPixmap_->fill((QColor(8, 8, 8, 160))); + + /// 默认隐藏 + hide(); +} + + +void OERect::paintEvent(QPaintEvent *) { + QPainter painter(this); + painter.drawPixmap(rect(),*backgroundPixmap_); + painter.setPen(QPen(QColor(Qt::white))); + painter.drawText(rect(), Qt::AlignCenter, info_); +} + +void OERect::onPostionChange(int x, int y) { + if (x < 0) x = 0; + if (y < 0) y = 0; + const int& ry = y - height() - 1; + if (ry < 0) { + this->raise(); + } + move(x, ((ry < 0) ? y : ry)); + show(); +} + +void OERect::onSizeChange(int w, int h) { + info_ = QString("%1 × %2").arg(w).arg(h); +} + + + + +/////////////////////////////////////////////////////////// + + + + + +OEScreen::OEScreen(std::shared_ptr originPainting, QPoint pos, QWidget *parent) + : QWidget(parent), direction_(NONE), originPoint_(pos), + isPressed_(false), originPainting_(originPainting) { + menu_ = new QMenu(this); + menu_->addAction("完成截图", this, SLOT(onSaveScreen())); + menu_->addAction("保存", this, SLOT(onSaveScreenOther())); + menu_->addSeparator(); + menu_->addAction("退出截图", this, SLOT(quitScreenshot())); + + /// 双击即完成 + connect(this, SIGNAL(doubleClick()), + this, SLOT(onSaveScreen())); + + /// 开启鼠标实时追踪 + setMouseTracking(true); + /// 默认隐藏 + hide(); +} + +OEScreen::DIRECTION OEScreen::getRegion(const QPoint &cursor) { + if (!isInit_) { + return NONE; + } + OEScreen::DIRECTION ret_dir = NONE; + // left upper + QPoint pt_lu = mapToParent(rect().topLeft()); + // right lower + QPoint pt_rl = mapToParent(rect().bottomRight()); + + int x = cursor.x(); + int y = cursor.y(); + + /// 获得鼠标当前所处窗口的边界方向 + if(pt_lu.x() + PADDING_ >= x + && pt_lu.x() <= x + && pt_lu.y() + PADDING_ >= y + && pt_lu.y() <= y) { + // 左上角 + ret_dir = LEFTUPPER; + this->setCursor(QCursor(Qt::SizeFDiagCursor)); + } else if(x >= pt_rl.x() - PADDING_ + && x <= pt_rl.x() + && y >= pt_rl.y() - PADDING_ + && y <= pt_rl.y()) { + // 右下角 + ret_dir = RIGHTLOWER; + this->setCursor(QCursor(Qt::SizeFDiagCursor)); + } else if(x <= pt_lu.x() + PADDING_ + && x >= pt_lu.x() + && y >= pt_rl.y() - PADDING_ + && y <= pt_rl.y()) { + // 左下角 + ret_dir = LEFTLOWER; + this->setCursor(QCursor(Qt::SizeBDiagCursor)); + } else if(x <= pt_rl.x() + && x >= pt_rl.x() - PADDING_ + && y >= pt_lu.y() + && y <= pt_lu.y() + PADDING_) { + // 右上角 + ret_dir = RIGHTUPPER; + this->setCursor(QCursor(Qt::SizeBDiagCursor)); + } else if(x <= pt_lu.x() + PADDING_ + && x >= pt_lu.x()) { + // 左边 + ret_dir = LEFT; + this->setCursor(QCursor(Qt::SizeHorCursor)); + } else if( x <= pt_rl.x() + && x >= pt_rl.x() - PADDING_) { + // 右边 + ret_dir = RIGHT; + this->setCursor(QCursor(Qt::SizeHorCursor)); + }else if(y >= pt_lu.y() + && y <= pt_lu.y() + PADDING_){ + // 上边 + ret_dir = UPPER; + this->setCursor(QCursor(Qt::SizeVerCursor)); + } else if(y <= pt_rl.y() + && y >= pt_rl.y() - PADDING_) { + // 下边 + ret_dir = LOWER; + this->setCursor(QCursor(Qt::SizeVerCursor)); + }else { + // 默认 + ret_dir = NONE; + this->setCursor(QCursor(Qt::SizeAllCursor)); + } + return ret_dir; +} + + +void OEScreen::contextMenuEvent(QContextMenuEvent *) { + /// 在鼠标位置弹射出菜单栏 + menu_->exec(cursor().pos()); +} + +void OEScreen::mouseDoubleClickEvent(QMouseEvent *e) { + if (e->button() == Qt::LeftButton) { + emit doubleClick(); + e->accept(); + } +} + +void OEScreen::mousePressEvent(QMouseEvent *e) { + if (e->button() == Qt::LeftButton) { + isPressed_ = true; + if(direction_ != NONE) { + this->mouseGrabber(); + } + /// @bug :这里可能存在问题, 不应当使用globalPos + movePos_ = e->globalPos() - pos(); + } +} + +void OEScreen::mouseReleaseEvent(QMouseEvent * e) { + if (e->button() == Qt::LeftButton) { + isPressed_ = false; + if(direction_ != NONE) { + setCursor(QCursor(Qt::SizeAllCursor)); + } + } +} + +void OEScreen::mouseMoveEvent(QMouseEvent * e) { + QPoint gloPoint = mapToParent(e->pos()); + // left upper + QPoint pt_lu = mapToParent(rect().topLeft()); + // left lower + QPoint pt_ll = mapToParent(rect().bottomLeft()); + // right lower + QPoint pt_rl = mapToParent(rect().bottomRight()); + // right upper + QPoint pt_ru = mapToParent(rect().topRight()); + if(!isPressed_) { + /// 检查鼠标鼠标方向 + direction_ = getRegion(gloPoint); + + /// 根据方位判断拖拉对应支点 + switch(direction_) { + case NONE: + case RIGHT: + case RIGHTLOWER: + originPoint_ = pt_lu; + break; + case RIGHTUPPER: + originPoint_ = pt_ll; + break; + case LEFT: + case LEFTLOWER: + originPoint_ = pt_ru; + break; + case LEFTUPPER: + case UPPER: + originPoint_ = pt_rl; + break; + case LOWER: + originPoint_ = pt_lu; + break; + } + } + else { + if(direction_ != NONE) { + const int& global_x = gloPoint.x(); + /// 鼠标进行拖拉拽 + switch(direction_) { + case LEFT: + return onMouseChange(global_x, pt_ll.y() + 1); + case RIGHT: + return onMouseChange(global_x, pt_rl.y() + 1); + case UPPER: + return onMouseChange(pt_lu.x(), gloPoint.y()); + case LOWER: + return onMouseChange(pt_rl.x() + 1, gloPoint.y()); + case LEFTUPPER: + case RIGHTUPPER: + case LEFTLOWER: + case RIGHTLOWER: + return onMouseChange(global_x, gloPoint.y()); + default: + break; + } + } + else { + /// 窗口的移动 + /// @bug :这里可能存在问题, 不应当使用globalPos + move(e->globalPos() - movePos_); + movePos_ = e->globalPos() - pos(); + e->accept(); + } + } + currentRect_ = geometry(); +} + +void OEScreen::moveEvent(QMoveEvent *) { + emit postionChange(x(), y()); +} + +void OEScreen::resizeEvent(QResizeEvent *) { + listMarker_.clear(); + + /// 重新计算八个锚点 + // 角点 + listMarker_.push_back(QPoint(0, 0)); + listMarker_.push_back(QPoint(width(), 0)); + listMarker_.push_back(QPoint(0, height())); + listMarker_.push_back(QPoint(width(), height())); + + // 中点 + listMarker_.push_back(QPoint((width() >> 1), 0)); + listMarker_.push_back(QPoint((width() >> 1), height())); + listMarker_.push_back(QPoint(0, (height() >> 1))); + listMarker_.push_back(QPoint(width(), (height() >> 1))); + + emit sizeChange(width(), height()); +} + +void OEScreen::showEvent(QShowEvent *) { + isInit_ = true; +} + +void OEScreen::hideEvent(QHideEvent *) { + currentRect_ = {}; + movePos_ = {}; + originPoint_ = {}; + isInit_ = false; +} + +void OEScreen::enterEvent(QEvent *e) { + setCursor(Qt::SizeAllCursor); + QWidget::enterEvent(e); +} + +void OEScreen::leaveEvent(QEvent *e) { + setCursor(Qt::ArrowCursor); + QWidget::leaveEvent(e); +} + +void OEScreen::closeEvent(QCloseEvent *) +{ + isInit_ = false; +} + +void OEScreen::paintEvent(QPaintEvent *) { + QPainter painter(this); + /// 绘制截屏编辑窗口 + painter.drawPixmap(QPoint(0,0), + *originPainting_, currentRect_); + + /// 绘制边框线 + QPen pen(QColor(0,174,255),2); + painter.setPen(pen); + painter.drawRect(rect()); + + /// 绘制八个点 + //改变点的宽度 + pen.setWidth(4); + pen.setColor(Qt::red); + painter.setPen(pen); + painter.drawPoints(listMarker_); +} + + +const QString OEScreen::getFileName(void) { + QString file_name = QDateTime::currentDateTime().toString("CSDN博客_瓯裔_yyyy-MM-dd-HH-mm-ss"); + return file_name; +} + + +void OEScreen::onSaveScreenOther(void) { + + QString fileName = QFileDialog::getSaveFileName(this, "保存图片", getFileName(), "JPEG Files (*.jpg)"); + if (fileName.length() > 0) { + originPainting_->copy(currentRect_).save(fileName, "jpg"); + quitScreenshot(); + } +} + +void OEScreen::onSaveScreen(void) { + /// 把图片放入剪切板 + QClipboard *board = QApplication::clipboard(); + board->setPixmap(originPainting_->copy(currentRect_)); + /// 退出当前截图工具 + quitScreenshot(); +} + + +void OEScreen::quitScreenshot(void) { + close(); + parentWidget()->close(); +} + +void OEScreen::onMouseChange(int x, int y) { + show(); + if (x < 0 || y < 0) { + return; + } + const int& rx = (x >= originPoint_.x()) ? originPoint_.x() : x; + const int& ry = (y >= originPoint_.y()) ? originPoint_.y() : y; + const int& rw = abs(x - originPoint_.x()); + const int& rh = abs(y - originPoint_.y()); + + /// 改变大小 + currentRect_ = QRect(rx, ry, rw, rh); + + this->setGeometry(currentRect_); + /// 改变大小后更新父窗口,防止父窗口未及时刷新而导致的问题 + parentWidget()->update(); +} diff --git a/LedOK/oescreenshot/oescreenshot.h b/LedOK/oescreenshot/oescreenshot.h index d686608..0e85fd8 100644 --- a/LedOK/oescreenshot/oescreenshot.h +++ b/LedOK/oescreenshot/oescreenshot.h @@ -1,508 +1,508 @@ -/** - * @author : 陈鲁勇 - * @date : 2017年04月 - * @version: 1.0 - * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; - * 除非遵守本许可,否则您不能使用这个文件。 - * @remarks: 您可以获得该许可的副本: - * http://www.apache.org/licenses/LICENSE-2.0 - * 除非适用法律需要或者书面同意,按本许可分发的软件 - * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 - * 参见按照本许可控制许可权限及限制的特定语言的许可证。 - * - * 你可以获得该代码的最新版本: - * - * https://git.oschina.net/Mr_ChenLuYong/screenshot - * - * 开源社区的所有人都期待与你的共同维护。 - * - * - * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: - * - * 博客地址:http://blog.csdn.net/csnd_ayo - * - * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 - * - * 期待你提交Bug,欢迎Issues。 - * -*/ - - -#ifndef OESCREENSHOT_H -#define OESCREENSHOT_H - -#include -#include -#include - -class OEScreen; -class OERect; -class OEAmplifier; -class QTimer; -class QMenu; - - -/** - * @class : OEScreenshot - * @brief : 截屏功能的主要入口, - * 管理全局热键,资源的回收与释放. - * @remark: 调用示例( OEScreenshot::Instance(); ) -*/ -class OEScreenshot : public QWidget { - Q_OBJECT - -signals: - - /** - * @brief : 鼠标移动(信号) - * @param : int x轴的坐标 - * @param : int y轴的坐标 - * @date : 2017年04月18日 - */ - void cursorPosChange(int, int); - - /** - * @brief : 双击(信号) - * @date : 2017年04月18日 - */ - void doubleClick(void); - - /** - * @brief : 鼠标当前位置最小的子窗口(信号) - * @param : QRect 当前窗口的矩形数据 - * @date : 2017年04月18日 - */ - void findChildWind(QRect); - -public: - /** - * @brief : 构造函数 - * @note : 当前依附的父窗口(一般不给父窗口) - * @date : 2017年04月16日 - */ - explicit OEScreenshot(QWidget *parent = 0); - ~OEScreenshot(void); - - /** - * @brief : 窗口实例 - * @note : 通过这个函数获得截图器的整个实例 - * @return: 返回 OEScreenshot 实例指针 - * @date : 2017年04月15日 - */ - static OEScreenshot *Instance(void); - - /** - * @brief : 摧毁截图窗口 - * @note : 通过这个函数可以摧毁整个截图窗口 - * @date : 2017年04月30日 - */ - static void destroy(void); - -protected: - - /** - * @brief : 隐藏窗口事件 - */ - virtual void hideEvent(QHideEvent *); - /** - * @brief : 关闭窗口事件 - */ - virtual void closeEvent(QCloseEvent *); - /** - * @brief : 双击事件 - */ - virtual void mouseDoubleClickEvent(QMouseEvent*); - /** - * @brief : 鼠标按下事件 - */ - virtual void mousePressEvent(QMouseEvent *); - /** - * @brief : 鼠标释放事件 - */ - virtual void mouseReleaseEvent(QMouseEvent *e); - /** - * @brief : 鼠标移动事件 - */ - virtual void mouseMoveEvent(QMouseEvent *e); - - /** - * @brief : 按键按下事件 - */ - virtual void keyPressEvent(QKeyEvent *e); - /** - * @brief : 自绘事件 - */ - virtual void paintEvent(QPaintEvent *); - - /** - * @brief : 更新当前鼠标选区的窗口 - */ - void updateMouse(void); - -private: - - - /** - * @brief : 初始化放大镜 (色彩采集器) - * @note : 他需要屏幕的原画作为放大器的放大元素 - * @param : originPainting 放大器必要的元素,若为空,则默认用originPainting_原画 - * @date : 2017年04月15日 - * @remark: 需先行调用getGlobalScreen。 - */ - void initAmplifier(std::shared_ptr originPainting = nullptr); - - /** - * @brief : 测量控件 (大小感知器) - * @date : 2017年04月27日 - */ - void initMeasureWidget(void); - - /** - * @brief : 初始化截屏背景 - * @return: QPixmap 经过暗色处理的屏幕图 - * @date : 2017年04月15日 - */ - std::shared_ptr initGlobalScreen(void); - - - /** - * @brief : 初始化鼠标 - * @note : 为鼠标设置默认状态下的图标样式 - * @param : ico 鼠标图片的资源文件路径 - * @date : 2017年04月15日 - * @remark: 若参数未填写,在使用本程序默认的鼠标Logo - */ - void initCursor(const QString& ico = ""); - - /** - * @brief : 创建截图器 - * @note : 若截图器已存在,则返回截图器示例,不会重复创建。 - * @param : pos 截图器的起始位置 (给当前鼠标位置即可) - * @date : 2017年04月16日 - * @remark: 创建截图器前,需要创建相关的组件,(例:大小感知器,放大取色器) - */ - std::shared_ptr createScreen(const QPoint &pos); - - /** - * @brief : 摧毁截图器 - * @note : 若截图器已存在,则摧毁示例,并清理示例创建的连带资源 - * @date : 2017年04月16日 - */ - void destroyScreen(void); - - - /** - * @brief : 获得当前屏幕的大小 - * @note : 这个函数是支持多屏幕的,示例:双屏幕 QRect(-1920, 0, 3840, 1080) - * @return: 返回 QRect 引用 - * @date : 2017年04月15日 - */ - const QRect& getScreenRect(void); - - /** - * @brief : 获得屏幕的原画 - * @note : 他不会重复获得屏幕原画,如果有,则返回原有的原画 - * @return: QPixmap* 指针 - * @date : 2017年04月15日 - * @remark: 若想重新获得屏幕原画,需要清理原有资源 - */ - std::shared_ptr getGlobalScreen(void); - - -private: - - /// 截屏窗口是否已经展示 - bool isLeftPressed_; - /// 用于检测误操作 - QPoint startPoint_; - /// 当前桌面屏幕的矩形数据 - QRect desktopRect_; - /// 屏幕暗色背景图 - std::shared_ptr backgroundScreen_; - /// 屏幕原画 - std::shared_ptr originPainting_; - /// 截图屏幕 - std::shared_ptr screenTool_; - /// 截图器大小感知器 - std::shared_ptr rectTool_; - /// 放大取色器 - std::shared_ptr amplifierTool_; - /// 当前鼠标选区最小的矩形窗口 - QRect windowRect_; - /// 截屏实例对象 - static OEScreenshot *self_; - /// 置顶定时器 - QTimer* egoisticTimer_; - /// 活动窗口 - static bool isActivity_; -private slots: - - /** - * @brief : Window下霸道置顶(唯我独尊) - * @date : 2017年04月28日 - * @remark: 使用该函数时,会终止右键菜单的行为,慎重使用,避免BUG - */ - void onEgoistic(void); -}; - - - - -/** - * @class : OERect - * @brief : 大小感知器 - * @note : 主要关乎截图器左上方的大小感知控件 -*/ -class OERect : public QWidget { - Q_OBJECT - -signals: - - -public: - - explicit OERect(QWidget *parent = 0); - -protected: - - /** - * @brief : 自绘函数 - */ - void paintEvent(QPaintEvent *); - -public slots: - - /** - * @brief : 外部组件位置修改(槽) - * @note : 感知器修改自身位置 - * @param : x 横向位置 - * @param : y 纵向位置 - * @date : 2017年04月15日 - */ - void onPostionChange(int x, int y); - - /** - * @brief : 外部组件大小修改 (槽) - * @note : 感知器修改显示的大小数据 - * @param : w 宽度 - * @param : h 高度 - * @date : 2017年04月15日 - */ - void onSizeChange(int w, int h); - -private: - /// 背景色 - std::shared_ptr backgroundPixmap_; - /// 显示的文字信息 - QString info_; -}; - - -/** - * @class : OEScreen - * @brief : 截图器 - * @note : 主要关乎图片的编辑与保存 -*/ -class OEScreen : public QWidget { - - Q_OBJECT - -signals: - - - /** - * @brief : 截图器大小修改(信号) - * @param : int 宽度 - * @param : int 高度 - * @date : 2017年04月17日 - */ - void sizeChange(int,int); - - /** - * @brief : 截图器窗口的位置(信号) - * @param : int 窗口的横向位置 - * @param : int 窗口的纵向位置 - * @date : 2017年04月17日 - */ - void postionChange(int,int); - - /** - * @brief : 双击 (信号) - * @date : 2017年04月17日 - */ - void doubleClick(void); - -protected: - - /// 内边距,决定拖拽的触发。 - const int PADDING_ = 6; - - /// 方位枚举 - enum DIRECTION { - UPPER=0, - LOWER=1, - LEFT, - RIGHT, - LEFTUPPER, - LEFTLOWER, - RIGHTLOWER, - RIGHTUPPER, - NONE - }; - -public: - - explicit OEScreen(std::shared_ptr originPainting, QPoint pos, QWidget *parent = 0); - - ~OEScreen() { isInit_ = false; } - - /** - * @brief : 获得当前截图器是否存在 - * @return: true : 存在 - * @date : 2017年04月17日 - */ - static bool state(void) { return isInit_; } - -protected: - - /** - * @brief : 获得当前坐标点的边界方位 - * @param : cursor 当前鼠标的位置 - * @return: DIRECTION 鼠标的方位枚举 - * @date : 2017年04月17日 - */ - DIRECTION getRegion(const QPoint &cursor); - - - /** - * @brief : 呼出菜单事件 - */ - virtual void contextMenuEvent(QContextMenuEvent *); - - /** - * @brief : 双击事件 - */ - virtual void mouseDoubleClickEvent(QMouseEvent *e); - - /** - * @brief : 鼠标按下事件 - */ - virtual void mousePressEvent(QMouseEvent *e); - - /** - * @brief : 鼠标释放事件 - */ - virtual void mouseReleaseEvent(QMouseEvent *e); - /** - * @brief : 鼠标移动事件 - */ - virtual void mouseMoveEvent(QMouseEvent *e); - - /** - * @brief : 窗口移动事件 - */ - virtual void moveEvent(QMoveEvent *); - - /** - * @brief : 窗口大小修改事件 - */ - virtual void resizeEvent(QResizeEvent *); - - - /** - * @brief : 窗口显示事件 - */ - virtual void showEvent(QShowEvent *); - - /** - * @brief : 窗口隐藏事件 - */ - virtual void hideEvent(QHideEvent *); - - /** - * @brief : 鼠标进入窗口事件 - */ - virtual void enterEvent(QEvent *e); - - /** - * @brief : 鼠标离开窗口事件 - */ - virtual void leaveEvent(QEvent *e); - - /** - * @brief : 窗口关闭事件 - */ - virtual void closeEvent(QCloseEvent *); - - /** - * @brief : 界面自绘事件 - */ - virtual void paintEvent(QPaintEvent *); - -private: - - /** - * @brief : 获得一个以时间格式命名的文件名 - * @return: QString 文件名 - * @date : 2017年04月16日 - */ - virtual const QString getFileName(void); - -public slots: - - - /** - * @brief : 根据鼠标位置修改窗口大小 - * @param : x 鼠标的横向位置 - * @param : y 鼠标的纵向位置 - * @date : 2017年04月16日 - */ - void onMouseChange(int x,int y); - - /** - * @brief : 保存屏幕到剪切板中 - * @date : 2017年04月16日 - */ - void onSaveScreen(void); - -protected slots: - - /** - * @brief : 保存编辑屏幕到其他路径下 - * @note : 会呼出路径选择的窗口 - * @date : 2017年04月16日 - */ - void onSaveScreenOther(void); - - /** - * @brief : 退出当前截图窗口 - * @date : 2017年04月16日 - */ - void quitScreenshot(void); - -private: - - /// 是否已经设置初始大小 - static bool isInit_; - /// 窗口大小改变时,记录改变方向 - DIRECTION direction_; - /// 起点 - QPoint originPoint_; - /// 鼠标是否按下 - bool isPressed_; - /// 拖动的距离 - QPoint movePos_; - /// 标记锚点 - QPolygon listMarker_; - /// 屏幕原画 - std::shared_ptr originPainting_; - /// 当前窗口几何数据 用于绘制截图区域 - QRect currentRect_; - /// 右键菜单对象 - QMenu *menu_; - -}; - - - -#endif /// OESCREENSHOT_H +/** + * @author : 陈鲁勇 + * @date : 2017年04月 + * @version: 1.0 + * @note : 根据 Apache 许可证 2.0 版(以下简称“许可证”)授权; + * 除非遵守本许可,否则您不能使用这个文件。 + * @remarks: 您可以获得该许可的副本: + * http://www.apache.org/licenses/LICENSE-2.0 + * 除非适用法律需要或者书面同意,按本许可分发的软件 + * 要按“原样”分发,没有任何形式的,明确或隐含的担保条款。 + * 参见按照本许可控制许可权限及限制的特定语言的许可证。 + * + * 你可以获得该代码的最新版本: + * + * https://git.oschina.net/Mr_ChenLuYong/screenshot + * + * 开源社区的所有人都期待与你的共同维护。 + * + * + * 如果你对这些代码还有不理解的地方可以通过最新的文章进行学习: + * + * 博客地址:http://blog.csdn.net/csnd_ayo + * + * 文章地址:http://blog.csdn.net/csnd_ayo/article/details/70197915 + * + * 期待你提交Bug,欢迎Issues。 + * +*/ + + +#ifndef OESCREENSHOT_H +#define OESCREENSHOT_H + +#include +#include +#include + +class OEScreen; +class OERect; +class OEAmplifier; +class QTimer; +class QMenu; + + +/** + * @class : OEScreenshot + * @brief : 截屏功能的主要入口, + * 管理全局热键,资源的回收与释放. + * @remark: 调用示例( OEScreenshot::Instance(); ) +*/ +class OEScreenshot : public QWidget { + Q_OBJECT + +signals: + + /** + * @brief : 鼠标移动(信号) + * @param : int x轴的坐标 + * @param : int y轴的坐标 + * @date : 2017年04月18日 + */ + void cursorPosChange(int, int); + + /** + * @brief : 双击(信号) + * @date : 2017年04月18日 + */ + void doubleClick(void); + + /** + * @brief : 鼠标当前位置最小的子窗口(信号) + * @param : QRect 当前窗口的矩形数据 + * @date : 2017年04月18日 + */ + void findChildWind(QRect); + +public: + /** + * @brief : 构造函数 + * @note : 当前依附的父窗口(一般不给父窗口) + * @date : 2017年04月16日 + */ + explicit OEScreenshot(QWidget *parent = 0); + ~OEScreenshot(void); + + /** + * @brief : 窗口实例 + * @note : 通过这个函数获得截图器的整个实例 + * @return: 返回 OEScreenshot 实例指针 + * @date : 2017年04月15日 + */ + static OEScreenshot *Instance(void); + + /** + * @brief : 摧毁截图窗口 + * @note : 通过这个函数可以摧毁整个截图窗口 + * @date : 2017年04月30日 + */ + static void destroy(void); + +protected: + + /** + * @brief : 隐藏窗口事件 + */ + virtual void hideEvent(QHideEvent *); + /** + * @brief : 关闭窗口事件 + */ + virtual void closeEvent(QCloseEvent *); + /** + * @brief : 双击事件 + */ + virtual void mouseDoubleClickEvent(QMouseEvent*); + /** + * @brief : 鼠标按下事件 + */ + virtual void mousePressEvent(QMouseEvent *); + /** + * @brief : 鼠标释放事件 + */ + virtual void mouseReleaseEvent(QMouseEvent *e); + /** + * @brief : 鼠标移动事件 + */ + virtual void mouseMoveEvent(QMouseEvent *e); + + /** + * @brief : 按键按下事件 + */ + virtual void keyPressEvent(QKeyEvent *e); + /** + * @brief : 自绘事件 + */ + virtual void paintEvent(QPaintEvent *); + + /** + * @brief : 更新当前鼠标选区的窗口 + */ + void updateMouse(void); + +private: + + + /** + * @brief : 初始化放大镜 (色彩采集器) + * @note : 他需要屏幕的原画作为放大器的放大元素 + * @param : originPainting 放大器必要的元素,若为空,则默认用originPainting_原画 + * @date : 2017年04月15日 + * @remark: 需先行调用getGlobalScreen。 + */ + void initAmplifier(std::shared_ptr originPainting = nullptr); + + /** + * @brief : 测量控件 (大小感知器) + * @date : 2017年04月27日 + */ + void initMeasureWidget(void); + + /** + * @brief : 初始化截屏背景 + * @return: QPixmap 经过暗色处理的屏幕图 + * @date : 2017年04月15日 + */ + std::shared_ptr initGlobalScreen(void); + + + /** + * @brief : 初始化鼠标 + * @note : 为鼠标设置默认状态下的图标样式 + * @param : ico 鼠标图片的资源文件路径 + * @date : 2017年04月15日 + * @remark: 若参数未填写,在使用本程序默认的鼠标Logo + */ + void initCursor(const QString& ico = ""); + + /** + * @brief : 创建截图器 + * @note : 若截图器已存在,则返回截图器示例,不会重复创建。 + * @param : pos 截图器的起始位置 (给当前鼠标位置即可) + * @date : 2017年04月16日 + * @remark: 创建截图器前,需要创建相关的组件,(例:大小感知器,放大取色器) + */ + std::shared_ptr createScreen(const QPoint &pos); + + /** + * @brief : 摧毁截图器 + * @note : 若截图器已存在,则摧毁示例,并清理示例创建的连带资源 + * @date : 2017年04月16日 + */ + void destroyScreen(void); + + + /** + * @brief : 获得当前屏幕的大小 + * @note : 这个函数是支持多屏幕的,示例:双屏幕 QRect(-1920, 0, 3840, 1080) + * @return: 返回 QRect 引用 + * @date : 2017年04月15日 + */ + const QRect& getScreenRect(void); + + /** + * @brief : 获得屏幕的原画 + * @note : 他不会重复获得屏幕原画,如果有,则返回原有的原画 + * @return: QPixmap* 指针 + * @date : 2017年04月15日 + * @remark: 若想重新获得屏幕原画,需要清理原有资源 + */ + std::shared_ptr getGlobalScreen(void); + + +private: + + /// 截屏窗口是否已经展示 + bool isLeftPressed_; + /// 用于检测误操作 + QPoint startPoint_; + /// 当前桌面屏幕的矩形数据 + QRect desktopRect_; + /// 屏幕暗色背景图 + std::shared_ptr backgroundScreen_; + /// 屏幕原画 + std::shared_ptr originPainting_; + /// 截图屏幕 + std::shared_ptr screenTool_; + /// 截图器大小感知器 + std::shared_ptr rectTool_; + /// 放大取色器 + std::shared_ptr amplifierTool_; + /// 当前鼠标选区最小的矩形窗口 + QRect windowRect_; + /// 截屏实例对象 + static OEScreenshot *self_; + /// 置顶定时器 + QTimer* egoisticTimer_; + /// 活动窗口 + static bool isActivity_; +private slots: + + /** + * @brief : Window下霸道置顶(唯我独尊) + * @date : 2017年04月28日 + * @remark: 使用该函数时,会终止右键菜单的行为,慎重使用,避免BUG + */ + void onEgoistic(void); +}; + + + + +/** + * @class : OERect + * @brief : 大小感知器 + * @note : 主要关乎截图器左上方的大小感知控件 +*/ +class OERect : public QWidget { + Q_OBJECT + +signals: + + +public: + + explicit OERect(QWidget *parent = 0); + +protected: + + /** + * @brief : 自绘函数 + */ + void paintEvent(QPaintEvent *); + +public slots: + + /** + * @brief : 外部组件位置修改(槽) + * @note : 感知器修改自身位置 + * @param : x 横向位置 + * @param : y 纵向位置 + * @date : 2017年04月15日 + */ + void onPostionChange(int x, int y); + + /** + * @brief : 外部组件大小修改 (槽) + * @note : 感知器修改显示的大小数据 + * @param : w 宽度 + * @param : h 高度 + * @date : 2017年04月15日 + */ + void onSizeChange(int w, int h); + +private: + /// 背景色 + std::shared_ptr backgroundPixmap_; + /// 显示的文字信息 + QString info_; +}; + + +/** + * @class : OEScreen + * @brief : 截图器 + * @note : 主要关乎图片的编辑与保存 +*/ +class OEScreen : public QWidget { + + Q_OBJECT + +signals: + + + /** + * @brief : 截图器大小修改(信号) + * @param : int 宽度 + * @param : int 高度 + * @date : 2017年04月17日 + */ + void sizeChange(int,int); + + /** + * @brief : 截图器窗口的位置(信号) + * @param : int 窗口的横向位置 + * @param : int 窗口的纵向位置 + * @date : 2017年04月17日 + */ + void postionChange(int,int); + + /** + * @brief : 双击 (信号) + * @date : 2017年04月17日 + */ + void doubleClick(void); + +protected: + + /// 内边距,决定拖拽的触发。 + const int PADDING_ = 6; + + /// 方位枚举 + enum DIRECTION { + UPPER=0, + LOWER=1, + LEFT, + RIGHT, + LEFTUPPER, + LEFTLOWER, + RIGHTLOWER, + RIGHTUPPER, + NONE + }; + +public: + + explicit OEScreen(std::shared_ptr originPainting, QPoint pos, QWidget *parent = 0); + + ~OEScreen() { isInit_ = false; } + + /** + * @brief : 获得当前截图器是否存在 + * @return: true : 存在 + * @date : 2017年04月17日 + */ + static bool state(void) { return isInit_; } + +protected: + + /** + * @brief : 获得当前坐标点的边界方位 + * @param : cursor 当前鼠标的位置 + * @return: DIRECTION 鼠标的方位枚举 + * @date : 2017年04月17日 + */ + DIRECTION getRegion(const QPoint &cursor); + + + /** + * @brief : 呼出菜单事件 + */ + virtual void contextMenuEvent(QContextMenuEvent *); + + /** + * @brief : 双击事件 + */ + virtual void mouseDoubleClickEvent(QMouseEvent *e); + + /** + * @brief : 鼠标按下事件 + */ + virtual void mousePressEvent(QMouseEvent *e); + + /** + * @brief : 鼠标释放事件 + */ + virtual void mouseReleaseEvent(QMouseEvent *e); + /** + * @brief : 鼠标移动事件 + */ + virtual void mouseMoveEvent(QMouseEvent *e); + + /** + * @brief : 窗口移动事件 + */ + virtual void moveEvent(QMoveEvent *); + + /** + * @brief : 窗口大小修改事件 + */ + virtual void resizeEvent(QResizeEvent *); + + + /** + * @brief : 窗口显示事件 + */ + virtual void showEvent(QShowEvent *); + + /** + * @brief : 窗口隐藏事件 + */ + virtual void hideEvent(QHideEvent *); + + /** + * @brief : 鼠标进入窗口事件 + */ + virtual void enterEvent(QEvent *e); + + /** + * @brief : 鼠标离开窗口事件 + */ + virtual void leaveEvent(QEvent *e); + + /** + * @brief : 窗口关闭事件 + */ + virtual void closeEvent(QCloseEvent *); + + /** + * @brief : 界面自绘事件 + */ + virtual void paintEvent(QPaintEvent *); + +private: + + /** + * @brief : 获得一个以时间格式命名的文件名 + * @return: QString 文件名 + * @date : 2017年04月16日 + */ + virtual const QString getFileName(void); + +public slots: + + + /** + * @brief : 根据鼠标位置修改窗口大小 + * @param : x 鼠标的横向位置 + * @param : y 鼠标的纵向位置 + * @date : 2017年04月16日 + */ + void onMouseChange(int x,int y); + + /** + * @brief : 保存屏幕到剪切板中 + * @date : 2017年04月16日 + */ + void onSaveScreen(void); + +protected slots: + + /** + * @brief : 保存编辑屏幕到其他路径下 + * @note : 会呼出路径选择的窗口 + * @date : 2017年04月16日 + */ + void onSaveScreenOther(void); + + /** + * @brief : 退出当前截图窗口 + * @date : 2017年04月16日 + */ + void quitScreenshot(void); + +private: + + /// 是否已经设置初始大小 + static bool isInit_; + /// 窗口大小改变时,记录改变方向 + DIRECTION direction_; + /// 起点 + QPoint originPoint_; + /// 鼠标是否按下 + bool isPressed_; + /// 拖动的距离 + QPoint movePos_; + /// 标记锚点 + QPolygon listMarker_; + /// 屏幕原画 + std::shared_ptr originPainting_; + /// 当前窗口几何数据 用于绘制截图区域 + QRect currentRect_; + /// 右键菜单对象 + QMenu *menu_; + +}; + + + +#endif /// OESCREENSHOT_H diff --git a/LedOK/passwordindlg.cpp b/LedOK/passwordindlg.cpp index 989fb37..1a46231 100644 --- a/LedOK/passwordindlg.cpp +++ b/LedOK/passwordindlg.cpp @@ -1,37 +1,37 @@ -#include "passwordindlg.h" -#include "base/changepasswordform.h" -#include -#include -#include - -PasswordInChDlg::PasswordInChDlg(QWidget *parent) : BaseDlg(parent) { - resize(213, 136); - setStyleSheet("QDialog{background-color: #eeeeee;} QLabel{background-color: transparent;}"); - auto vBox = new QVBoxLayout(this); - vBox->addStretch(); - - auto hBox = new QHBoxLayout(); - hBox->addWidget(new QLabel(tr("Input password"))); - - fdPassword = new QLineEdit(); - fdPassword->setEchoMode(QLineEdit::Password); - fdPassword->setFocus(); - hBox->addWidget(fdPassword); - vBox->addLayout(hBox); - - btnChangePassword = new QPushButton(tr("Change Password")); - btnChangePassword->setProperty("ssType", "progManageTool"); - vBox->addWidget(btnChangePassword, 0, Qt::AlignRight); - connect(btnChangePassword, &QPushButton::clicked, this, [this]() { - ChangePasswordForm dlg(this); - dlg.exec(); - }); - vBox->addStretch(); - - btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); - btnBox->button(QDialogButtonBox::Ok)->setProperty("ssType", "progManageTool"); - btnBox->button(QDialogButtonBox::Cancel)->setProperty("ssType", "progManageTool"); - vBox->addWidget(btnBox, 0, Qt::AlignHCenter); - connect(btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - vBox->addStretch(); -} +#include "passwordindlg.h" +#include "base/changepasswordform.h" +#include +#include +#include + +PasswordInChDlg::PasswordInChDlg(QWidget *parent) : BaseDlg(parent) { + resize(213, 136); + setStyleSheet("QDialog{background-color: #eeeeee;} QLabel{background-color: transparent;}"); + auto vBox = new QVBoxLayout(this); + vBox->addStretch(); + + auto hBox = new QHBoxLayout(); + hBox->addWidget(new QLabel(tr("Input password"))); + + fdPassword = new QLineEdit(); + fdPassword->setEchoMode(QLineEdit::Password); + fdPassword->setFocus(); + hBox->addWidget(fdPassword); + vBox->addLayout(hBox); + + btnChangePassword = new QPushButton(tr("Change Password")); + btnChangePassword->setProperty("ssType", "progManageTool"); + vBox->addWidget(btnChangePassword, 0, Qt::AlignRight); + connect(btnChangePassword, &QPushButton::clicked, this, [this]() { + ChangePasswordForm dlg(this); + dlg.exec(); + }); + vBox->addStretch(); + + btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); + btnBox->button(QDialogButtonBox::Ok)->setProperty("ssType", "progManageTool"); + btnBox->button(QDialogButtonBox::Cancel)->setProperty("ssType", "progManageTool"); + vBox->addWidget(btnBox, 0, Qt::AlignHCenter); + connect(btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + vBox->addStretch(); +} diff --git a/LedOK/passwordindlg.h b/LedOK/passwordindlg.h index 380753c..79ec393 100644 --- a/LedOK/passwordindlg.h +++ b/LedOK/passwordindlg.h @@ -1,18 +1,18 @@ -#ifndef PASSWORDINDLG_H -#define PASSWORDINDLG_H - -#include "basedlg.h" -#include -#include - -class PasswordInChDlg : public BaseDlg { - Q_OBJECT -public: - explicit PasswordInChDlg(QWidget *parent = nullptr); - - QLineEdit *fdPassword; - QPushButton *btnChangePassword; - QDialogButtonBox *btnBox; -}; - -#endif // PASSWORDINDLG_H +#ifndef PASSWORDINDLG_H +#define PASSWORDINDLG_H + +#include "basedlg.h" +#include +#include + +class PasswordInChDlg : public BaseDlg { + Q_OBJECT +public: + explicit PasswordInChDlg(QWidget *parent = nullptr); + + QLineEdit *fdPassword; + QPushButton *btnChangePassword; + QDialogButtonBox *btnBox; +}; + +#endif // PASSWORDINDLG_H diff --git a/LedOK/player/digiclock.cpp b/LedOK/player/digiclock.cpp index 40c321b..eb31a53 100644 --- a/LedOK/player/digiclock.cpp +++ b/LedOK/player/digiclock.cpp @@ -1,240 +1,240 @@ -#include "digiclock.h" -#include "gqt.h" -#include -#include -#include - -DigiClock::DigiClock(QString prefix, const QJsonObject &layer, QWidget *parent) : QWidget{parent} { - timeZone = QTimeZone(layer["timezone"].toString().toUtf8()); - auto spaceWidth = layer["spaceWidth"].toDouble(); - QJsonArray pics = layer["arrayPics"].toArray(); - foreach(auto pic, pics) imgs.insert(pic["name"].toString(), QPixmap(prefix+pic["id"].toString())); - int dateStyle = layer["dateStyle"].toInt(); - isSingleMonth = dateStyle==1||dateStyle==2||dateStyle==4||dateStyle==6||dateStyle==8||dateStyle==10||dateStyle==12; - QPixmap& timeSep = imgs["maohao"]; - weekly = layer["weekly"].toBool(); - bool hour12 = layer["hour12"].toBool(); - bool AmPm = hour12 ? layer["AmPm"].toBool() : false; - timeptn = hour12 ? "hhmmssa" : "HHmmss"; - bool hour = layer["hour"].toBool(); - bool min = layer["min"].toBool(); - bool sec = layer["sec"].toBool(); - multiline = layer["multiline"].toBool(); - if(multiline) { - QVBoxLayout *vBox = new QVBoxLayout(this); - vBox->setAlignment(Qt::AlignCenter); - vBox->setContentsMargins(0,0,0,0); - vBox->setSpacing(0); - vBox->addStretch(); - QHBoxLayout *hBox = new QHBoxLayout(); - vBox->addLayout(hBox); - hBox->addStretch(); - addDate(dateStyle, layer, hBox); - hBox->addStretch(); - if(weekly) { - hBox = new QHBoxLayout(); - vBox->addLayout(hBox); - hBox->addStretch(); - hBox->addWidget((QWidget*)weekComp); - hBox->addStretch(); - } - hBox = new QHBoxLayout(); - vBox->addLayout(hBox); - hBox->addStretch(); - if(AmPm) { - hBox->addWidget((QWidget*)ampmComp); - hBox->addSpacing(spaceWidth); - } - if(hour) { - hBox->addWidget((QWidget*)hourComps[0]); - hBox->addWidget((QWidget*)hourComps[1]); - } - if(hour&&min) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); - if(min) { - hBox->addWidget((QWidget*)minComps[0]); - hBox->addWidget((QWidget*)minComps[1]); - } - if(min&&sec) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); - if(sec) { - hBox->addWidget((QWidget*)secComps[0]); - hBox->addWidget((QWidget*)secComps[1]); - } - hBox->addStretch(); - vBox->addStretch(); - } else { - QHBoxLayout *hBox = new QHBoxLayout(this); - hBox->setContentsMargins(0,0,0,0); - hBox->setSpacing(0); - hBox->addStretch(); - addDate(dateStyle, layer, hBox); - if(hBox->count()>1) hBox->addSpacing(spaceWidth*2); - if(weekly) { - hBox->addWidget((QWidget*)weekComp); - hBox->addSpacing(spaceWidth*2); - } - if(AmPm) { - hBox->addWidget((QWidget*)ampmComp); - hBox->addSpacing(spaceWidth); - } - if(hour) { - hBox->addWidget((QWidget*)hourComps[0]); - hBox->addWidget((QWidget*)hourComps[1]); - } - if(hour&&min) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); - if(min) { - hBox->addWidget((QWidget*)minComps[0]); - hBox->addWidget((QWidget*)minComps[1]); - } - if(min&&sec) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); - if(sec) { - hBox->addWidget((QWidget*)secComps[0]); - hBox->addWidget((QWidget*)secComps[1]); - } - hBox->addStretch(); - } -} -void DigiClock::addDate(int dateStyle, QJsonObject layer, QHBoxLayout* tar) { - if(dateStyle==0 || dateStyle==1) { - addYear(layer, tar, imgs["YEAR"]); - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(imgs["MONTH"])); - } - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - tar->addWidget((QWidget*)new ImgWgt(imgs["DAY"])); - } - } else if(dateStyle==2 || dateStyle==3) { - QPixmap sep = imgs["xiegang"]; - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - addYear(layer, tar, QPixmap()); - } else if(dateStyle==4 || dateStyle==5) { - QPixmap sep = imgs["xiegang"]; - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - addYear(layer, tar, QPixmap()); - } else if(dateStyle==6 || dateStyle==7) { - QPixmap sep = imgs["xiegang"]; - addYear(layer, tar, sep); - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - } - } else if(dateStyle==8 || dateStyle==9) { - QPixmap sep = imgs["hengxian"]; - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - addYear(layer, tar, QPixmap()); - } else if(dateStyle==10 || dateStyle==11) { - QPixmap sep = imgs["hengxian"]; - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - addYear(layer, tar, QPixmap()); - } else if(dateStyle==12 || dateStyle==13) { - QPixmap sep = imgs["hengxian"]; - addYear(layer, tar, sep); - if(layer["month"].toBool()) { - tar->addWidget((QWidget*)monthComps[0]); - tar->addWidget((QWidget*)monthComps[1]); - tar->addWidget((QWidget*)new ImgWgt(sep)); - } - if(layer["day"].toBool()) { - tar->addWidget((QWidget*)dayComps[0]); - tar->addWidget((QWidget*)dayComps[1]); - } - } -} -void DigiClock::addYear(QJsonObject layer, QHBoxLayout* tar, QPixmap sep) { - if(layer["year"].toBool()) { - if(layer["fullYear"].toBool()) { - tar->addWidget((QWidget*)yearComps[0]); - tar->addWidget((QWidget*)yearComps[1]); - } - tar->addWidget((QWidget*)yearComps[2]); - tar->addWidget((QWidget*)yearComps[3]); - if(!sep.isNull()) tar->addWidget((QWidget*)new ImgWgt(sep)); - } -} -void DigiClock::cal() { - QDateTime dt = QDateTime::currentDateTime().toTimeZone(timeZone); - QTime time = dt.time(); - QString hms = time.toString(timeptn); - *ampmComp = imgs[time.hour()<12?"AM":"PM"]; - *hourComps[0] = imgs[hms.mid(0,1)]; - *hourComps[1] = imgs[hms.mid(1,1)]; - *minComps[0] = imgs[hms.mid(2,1)]; - *minComps[1] = imgs[hms.mid(3,1)]; - *secComps[0] = imgs[hms.mid(4,1)]; - *secComps[1] = imgs[hms.mid(5,1)]; - if(yearComps[0]->img.isNull() || (time.hour()==0 && time.second()==0)) { - QDate date = dt.date(); - if(weekly) *weekComp = imgs[weeks[date.dayOfWeek()-1]]; - QString ymd = date.toString("yyyyMMdd"); - *yearComps[0] = imgs[ymd.mid(0,1)]; - *yearComps[1] = imgs[ymd.mid(1,1)]; - *yearComps[2] = imgs[ymd.mid(2,1)]; - *yearComps[3] = imgs[ymd.mid(3,1)]; - QChar ch = ymd.at(4); - if(isSingleMonth && ch=='0') *monthComps[0] = QPixmap(); - else *monthComps[0] = imgs[ymd.mid(4,1)]; - *monthComps[1] = imgs[ymd.mid(5,1)]; - *dayComps[0] = imgs[ymd.mid(6,1)]; - *dayComps[1] = imgs[ymd.mid(7,1)]; - } -} -void DigiClock::showEvent(QShowEvent *) { - if(timerId==0) { - timerId = startTimer(1000, Qt::PreciseTimer); - cal(); - } -} - -void DigiClock::timerEvent(QTimerEvent *) { - if(isVisible()) { - cal(); - update(); - } else if(timerId!=0) { - killTimer(timerId); - timerId = 0; - } -} +#include "digiclock.h" +#include "gutil/qgui.h" +#include +#include +#include + +DigiClock::DigiClock(QString prefix, const QJsonObject &layer, QWidget *parent) : QWidget{parent} { + timeZone = QTimeZone(layer["timezone"].toString().toUtf8()); + auto spaceWidth = layer["spaceWidth"].toDouble(); + QJsonArray pics = layer["arrayPics"].toArray(); + foreach(auto pic, pics) imgs.insert(pic["name"].toString(), QPixmap(prefix+pic["id"].toString())); + int dateStyle = layer["dateStyle"].toInt(); + isSingleMonth = dateStyle==1||dateStyle==2||dateStyle==4||dateStyle==6||dateStyle==8||dateStyle==10||dateStyle==12; + QPixmap& timeSep = imgs["maohao"]; + weekly = layer["weekly"].toBool(); + bool hour12 = layer["hour12"].toBool(); + bool AmPm = hour12 ? layer["AmPm"].toBool() : false; + timeptn = hour12 ? "hhmmssa" : "HHmmss"; + bool hour = layer["hour"].toBool(); + bool min = layer["min"].toBool(); + bool sec = layer["sec"].toBool(); + multiline = layer["multiline"].toBool(); + if(multiline) { + QVBoxLayout *vBox = new QVBoxLayout(this); + vBox->setAlignment(Qt::AlignCenter); + vBox->setContentsMargins(0,0,0,0); + vBox->setSpacing(0); + vBox->addStretch(); + QHBoxLayout *hBox = new QHBoxLayout(); + vBox->addLayout(hBox); + hBox->addStretch(); + addDate(dateStyle, layer, hBox); + hBox->addStretch(); + if(weekly) { + hBox = new QHBoxLayout(); + vBox->addLayout(hBox); + hBox->addStretch(); + hBox->addWidget((QWidget*)weekComp); + hBox->addStretch(); + } + hBox = new QHBoxLayout(); + vBox->addLayout(hBox); + hBox->addStretch(); + if(AmPm) { + hBox->addWidget((QWidget*)ampmComp); + hBox->addSpacing(spaceWidth); + } + if(hour) { + hBox->addWidget((QWidget*)hourComps[0]); + hBox->addWidget((QWidget*)hourComps[1]); + } + if(hour&&min) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); + if(min) { + hBox->addWidget((QWidget*)minComps[0]); + hBox->addWidget((QWidget*)minComps[1]); + } + if(min&&sec) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); + if(sec) { + hBox->addWidget((QWidget*)secComps[0]); + hBox->addWidget((QWidget*)secComps[1]); + } + hBox->addStretch(); + vBox->addStretch(); + } else { + QHBoxLayout *hBox = new QHBoxLayout(this); + hBox->setContentsMargins(0,0,0,0); + hBox->setSpacing(0); + hBox->addStretch(); + addDate(dateStyle, layer, hBox); + if(hBox->count()>1) hBox->addSpacing(spaceWidth*2); + if(weekly) { + hBox->addWidget((QWidget*)weekComp); + hBox->addSpacing(spaceWidth*2); + } + if(AmPm) { + hBox->addWidget((QWidget*)ampmComp); + hBox->addSpacing(spaceWidth); + } + if(hour) { + hBox->addWidget((QWidget*)hourComps[0]); + hBox->addWidget((QWidget*)hourComps[1]); + } + if(hour&&min) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); + if(min) { + hBox->addWidget((QWidget*)minComps[0]); + hBox->addWidget((QWidget*)minComps[1]); + } + if(min&&sec) hBox->addWidget((QWidget*)new ImgWgt(timeSep)); + if(sec) { + hBox->addWidget((QWidget*)secComps[0]); + hBox->addWidget((QWidget*)secComps[1]); + } + hBox->addStretch(); + } +} +void DigiClock::addDate(int dateStyle, QJsonObject layer, QHBoxLayout* tar) { + if(dateStyle==0 || dateStyle==1) { + addYear(layer, tar, imgs["YEAR"]); + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(imgs["MONTH"])); + } + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + tar->addWidget((QWidget*)new ImgWgt(imgs["DAY"])); + } + } else if(dateStyle==2 || dateStyle==3) { + QPixmap sep = imgs["xiegang"]; + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + addYear(layer, tar, QPixmap()); + } else if(dateStyle==4 || dateStyle==5) { + QPixmap sep = imgs["xiegang"]; + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + addYear(layer, tar, QPixmap()); + } else if(dateStyle==6 || dateStyle==7) { + QPixmap sep = imgs["xiegang"]; + addYear(layer, tar, sep); + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + } + } else if(dateStyle==8 || dateStyle==9) { + QPixmap sep = imgs["hengxian"]; + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + addYear(layer, tar, QPixmap()); + } else if(dateStyle==10 || dateStyle==11) { + QPixmap sep = imgs["hengxian"]; + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + addYear(layer, tar, QPixmap()); + } else if(dateStyle==12 || dateStyle==13) { + QPixmap sep = imgs["hengxian"]; + addYear(layer, tar, sep); + if(layer["month"].toBool()) { + tar->addWidget((QWidget*)monthComps[0]); + tar->addWidget((QWidget*)monthComps[1]); + tar->addWidget((QWidget*)new ImgWgt(sep)); + } + if(layer["day"].toBool()) { + tar->addWidget((QWidget*)dayComps[0]); + tar->addWidget((QWidget*)dayComps[1]); + } + } +} +void DigiClock::addYear(QJsonObject layer, QHBoxLayout* tar, QPixmap sep) { + if(layer["year"].toBool()) { + if(layer["fullYear"].toBool()) { + tar->addWidget((QWidget*)yearComps[0]); + tar->addWidget((QWidget*)yearComps[1]); + } + tar->addWidget((QWidget*)yearComps[2]); + tar->addWidget((QWidget*)yearComps[3]); + if(!sep.isNull()) tar->addWidget((QWidget*)new ImgWgt(sep)); + } +} +void DigiClock::cal() { + QDateTime dt = QDateTime::currentDateTime().toTimeZone(timeZone); + QTime time = dt.time(); + QString hms = time.toString(timeptn); + *ampmComp = imgs[time.hour()<12?"AM":"PM"]; + *hourComps[0] = imgs[hms.mid(0,1)]; + *hourComps[1] = imgs[hms.mid(1,1)]; + *minComps[0] = imgs[hms.mid(2,1)]; + *minComps[1] = imgs[hms.mid(3,1)]; + *secComps[0] = imgs[hms.mid(4,1)]; + *secComps[1] = imgs[hms.mid(5,1)]; + if(yearComps[0]->img.isNull() || (time.hour()==0 && time.second()==0)) { + QDate date = dt.date(); + if(weekly) *weekComp = imgs[weeks[date.dayOfWeek()-1]]; + QString ymd = date.toString("yyyyMMdd"); + *yearComps[0] = imgs[ymd.mid(0,1)]; + *yearComps[1] = imgs[ymd.mid(1,1)]; + *yearComps[2] = imgs[ymd.mid(2,1)]; + *yearComps[3] = imgs[ymd.mid(3,1)]; + QChar ch = ymd.at(4); + if(isSingleMonth && ch=='0') *monthComps[0] = QPixmap(); + else *monthComps[0] = imgs[ymd.mid(4,1)]; + *monthComps[1] = imgs[ymd.mid(5,1)]; + *dayComps[0] = imgs[ymd.mid(6,1)]; + *dayComps[1] = imgs[ymd.mid(7,1)]; + } +} +void DigiClock::showEvent(QShowEvent *) { + if(timerId==0) { + timerId = startTimer(1000, Qt::PreciseTimer); + cal(); + } +} + +void DigiClock::timerEvent(QTimerEvent *) { + if(isVisible()) { + cal(); + update(); + } else if(timerId!=0) { + killTimer(timerId); + timerId = 0; + } +} diff --git a/LedOK/player/digiclock.h b/LedOK/player/digiclock.h index 6d31453..7eebd42 100644 --- a/LedOK/player/digiclock.h +++ b/LedOK/player/digiclock.h @@ -1,67 +1,67 @@ -#ifndef DIGICLOCK_H -#define DIGICLOCK_H - -#include -#include -#include -#include - -class ImgWgt : public QWidget { -public: - ImgWgt(QWidget *parent = nullptr) : QWidget{parent} {} - ImgWgt(const QPixmap &img) :img(img){ - setFixedSize(this->img.size()); - } - ImgWgt(QPixmap &&img) { - this->img = std::move(img); - setFixedSize(this->img.size()); - } - ImgWgt &operator=(const QPixmap &img) { - this->img = img; - setFixedSize(this->img.size()); - return *this; - } - ImgWgt &operator=(QPixmap &&img) { - this->img = std::move(img); - setFixedSize(this->img.size()); - return *this; - } - QPixmap img; -protected: - virtual void paintEvent(QPaintEvent *) override { - if(img.isNull()) return; - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - painter.drawPixmap(0, 0, width(), height(), img); - } -}; - -const QString weeks[7]{"MON","TUE","WED","THU","FRI","SAT","SUN"}; - -class DigiClock : public QWidget { - Q_OBJECT -public: - DigiClock(QString path, const QJsonObject &layer, QWidget *parent = nullptr); - void cal(); - void addDate(int, QJsonObject, QHBoxLayout*); - void addYear(QJsonObject layer, QHBoxLayout* tar, QPixmap sep); - QTimeZone timeZone; - ImgWgt *yearComps[4] {new ImgWgt(), new ImgWgt(), new ImgWgt(), new ImgWgt()}; - ImgWgt *monthComps[2] {new ImgWgt(), new ImgWgt()}; - ImgWgt *dayComps[2] {new ImgWgt(), new ImgWgt()}; - ImgWgt *weekComp = new ImgWgt(), *ampmComp = new ImgWgt(); - ImgWgt *hourComps[2] {new ImgWgt(), new ImgWgt()}; - ImgWgt *minComps[2] {new ImgWgt(), new ImgWgt()}; - ImgWgt *secComps[2] {new ImgWgt(), new ImgWgt()}; - - QMap imgs; - QString timeptn; - bool multiline, weekly, isSingleMonth; - int timerId = 0; - -protected: - void timerEvent(QTimerEvent *) override; - void showEvent(QShowEvent *) override; -}; - -#endif // DIGICLOCK_H +#ifndef DIGICLOCK_H +#define DIGICLOCK_H + +#include +#include +#include +#include + +class ImgWgt : public QWidget { +public: + ImgWgt(QWidget *parent = nullptr) : QWidget{parent} {} + ImgWgt(const QPixmap &img) :img(img){ + setFixedSize(this->img.size()); + } + ImgWgt(QPixmap &&img) { + this->img = std::move(img); + setFixedSize(this->img.size()); + } + ImgWgt &operator=(const QPixmap &img) { + this->img = img; + setFixedSize(this->img.size()); + return *this; + } + ImgWgt &operator=(QPixmap &&img) { + this->img = std::move(img); + setFixedSize(this->img.size()); + return *this; + } + QPixmap img; +protected: + virtual void paintEvent(QPaintEvent *) override { + if(img.isNull()) return; + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + painter.drawPixmap(0, 0, width(), height(), img); + } +}; + +const QString weeks[7]{"MON","TUE","WED","THU","FRI","SAT","SUN"}; + +class DigiClock : public QWidget { + Q_OBJECT +public: + DigiClock(QString path, const QJsonObject &layer, QWidget *parent = nullptr); + void cal(); + void addDate(int, QJsonObject, QHBoxLayout*); + void addYear(QJsonObject layer, QHBoxLayout* tar, QPixmap sep); + QTimeZone timeZone; + ImgWgt *yearComps[4] {new ImgWgt(), new ImgWgt(), new ImgWgt(), new ImgWgt()}; + ImgWgt *monthComps[2] {new ImgWgt(), new ImgWgt()}; + ImgWgt *dayComps[2] {new ImgWgt(), new ImgWgt()}; + ImgWgt *weekComp = new ImgWgt(), *ampmComp = new ImgWgt(); + ImgWgt *hourComps[2] {new ImgWgt(), new ImgWgt()}; + ImgWgt *minComps[2] {new ImgWgt(), new ImgWgt()}; + ImgWgt *secComps[2] {new ImgWgt(), new ImgWgt()}; + + QMap imgs; + QString timeptn; + bool multiline, weekly, isSingleMonth; + int timerId = 0; + +protected: + void timerEvent(QTimerEvent *) override; + void showEvent(QShowEvent *) override; +}; + +#endif // DIGICLOCK_H diff --git a/LedOK/player/eleanaclock.cpp b/LedOK/player/eleanaclock.cpp index 4a5071a..a3d37cb 100644 --- a/LedOK/player/eleanaclock.cpp +++ b/LedOK/player/eleanaclock.cpp @@ -1,74 +1,82 @@ -#include "eleanaclock.h" -#include -#include -#include - -EleAnaClock::EleAnaClock(QString path, const QJsonObject &layer, QWidget *parent) : QWidget{parent} { - timeZone = QTimeZone(layer["timezone"].toString().toUtf8()); - img.load(path); - pinHourColor = layer["pinHourColor"].toString(); - pinMinColor = layer["pinMinColor"].toString(); - pinSecColor = layer["pinSecColor"].toString(); -} - -void EleAnaClock::cal() { - QTime time = QDateTime::currentDateTime().toTimeZone(timeZone).time(); - double rad = time.second()*M_PI/30; - double rsin = sin(rad); - double rcos = cos(rad); - double sideLen = width(); - if(height() < sideLen) sideLen = height(); - sPath = QPainterPath(QPointF(sideLen*0.55*rsin, sideLen*-0.55*rcos)); - double pinWidth = sideLen/36; - double sx = pinWidth*rcos; - double sy = pinWidth*rsin; - sPath.lineTo(sx, sy); - sPath.lineTo(-sx, -sy); - sPath.closeSubpath(); - - rad = time.minute()*M_PI/30 + rad/60; - rsin = sin(rad); - rcos = cos(rad); - mPath = QPainterPath(QPointF(sideLen*0.45*rsin, sideLen*-0.45*rcos)); - pinWidth = sideLen/30; - sx = pinWidth*rcos; - sy = pinWidth*rsin; - mPath.lineTo(sx, sy); - mPath.lineTo(-sx, -sy); - mPath.closeSubpath(); - - rad = time.hour()*M_PI/6 + rad/12; - rsin = sin(rad); - rcos = cos(rad); - hPath = QPainterPath(QPointF(sideLen*0.3*rsin, sideLen*-0.3*rcos)); - pinWidth = sideLen/18; - sx = pinWidth*rcos; - sy = pinWidth*rsin; - hPath.lineTo(sx, sy); - hPath.lineTo(-sx, -sy); - hPath.closeSubpath(); -} -void EleAnaClock::paintEvent(QPaintEvent *) { - if(timerId==0) { - timerId = startTimer(1000, Qt::PreciseTimer); - cal(); - } - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - if(! img.isNull()) painter.drawPixmap(0, 0, width(), height(), img); - painter.translate(width()/2, height()/2); - painter.fillPath(hPath, QBrush(pinHourColor)); - painter.fillPath(mPath, QBrush(pinMinColor)); - painter.fillPath(sPath, QBrush(pinSecColor)); - painter.translate(-width()/2, -height()/2); -} - -void EleAnaClock::timerEvent(QTimerEvent *) { - if(isVisible()) { - cal(); - repaint(); - } else if(timerId!=0) { - killTimer(timerId); - timerId = 0; - } -} +#include "eleanaclock.h" +#include +#include + +EleAnaClock::EleAnaClock(double w, double h, QString path, const QJsonObject &layer, QWidget *parent) : QWidget{parent} { + timeZone = QTimeZone(layer["timezone"].toString().toUtf8()); + img.load(path); + pinHourColor = layer["pinHourColor"].toString(); + pinMinColor = layer["pinMinColor"].toString(); + pinSecColor = layer["pinSecColor"].toString(); + auto hhLen = layer["pinHourLen"].toInt(); + auto mhLen = layer["pinMinLen"].toInt(); + auto shLen = layer["pinSecLen"].toInt(); + auto hhWidth = layer["pinHourWidth"].toInt(); + auto mhWidth = layer["pinMinWidth"].toInt(); + auto shWidth = layer["pinSecWidth"].toInt(); + showSecHand = layer["showSecond"].toBool(); + auto sideLen = w; + if(h < sideLen) sideLen = h; + auto lineWidth = sideLen/128; + if(lineWidth < 1) lineWidth = 1; + pen.setWidthF(lineWidth); + pen.setJoinStyle(Qt::RoundJoin); + + hPoses[0].rx() = hhWidth*sideLen/400; + hPoses[1].ry() = hhLen*sideLen/-200; + hPoses[2].rx() = -hPoses[0].rx(); + + mPoses[0].rx() = mhWidth*sideLen/400; + mPoses[1].ry() = mhLen*sideLen/-200; + mPoses[2].rx() = -mPoses[0].rx(); + + sPoses[0].rx() = shWidth*sideLen/400; + sPoses[1].ry() = shLen*sideLen/-200; + sPoses[2].rx() = -sPoses[0].rx(); +} + +void EleAnaClock::cal() { + auto time = QDateTime::currentDateTime().toTimeZone(timeZone).time(); + sAngle = time.second() * 6; + mAngle = time.minute() * 6 + sAngle/60; + hAngle = time.hour() * 30 + mAngle/12; +} +void EleAnaClock::paintEvent(QPaintEvent *) { + if(timerId==0) { + timerId = startTimer(500, Qt::PreciseTimer); + cal(); + } + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + if(! img.isNull()) painter.drawPixmap(0, 0, width(), height(), img); + painter.translate(width()/2, height()/2); + + pen.setColor(pinHourColor); + painter.setPen(pen); + painter.setBrush(pen.brush()); + painter.rotate(hAngle); + painter.drawPolygon(hPoses, 3); + + pen.setColor(pinMinColor); + painter.setPen(pen); + painter.setBrush(pen.brush()); + painter.rotate(mAngle-hAngle); + painter.drawPolygon(mPoses, 3); + if(showSecHand) { + pen.setColor(pinSecColor); + painter.setPen(pen); + painter.setBrush(pen.brush()); + painter.rotate(sAngle-mAngle); + painter.drawPolygon(sPoses, 3); + } +} + +void EleAnaClock::timerEvent(QTimerEvent *) { + if(isVisible()) { + cal(); + update(); + } else if(timerId!=0) { + killTimer(timerId); + timerId = 0; + } +} diff --git a/LedOK/player/eleanaclock.h b/LedOK/player/eleanaclock.h index b33cec6..71e94d2 100644 --- a/LedOK/player/eleanaclock.h +++ b/LedOK/player/eleanaclock.h @@ -1,24 +1,27 @@ -#ifndef ELEANACLOCK_H -#define ELEANACLOCK_H - -#include -#include -#include - -class EleAnaClock : public QWidget { - Q_OBJECT -public: - explicit EleAnaClock(QString path, const QJsonObject &layer, QWidget *parent = nullptr); - void cal(); - QTimeZone timeZone; - QPixmap img; - QColor pinHourColor, pinMinColor, pinSecColor; - QPainterPath sPath, mPath, hPath; - int timerId = 0; - -protected: - void paintEvent(QPaintEvent *) override; - void timerEvent(QTimerEvent *) override; -}; - -#endif // ELEANACLOCK_H +#ifndef ELEANACLOCK_H +#define ELEANACLOCK_H + +#include +#include +#include + +class EleAnaClock : public QWidget { + Q_OBJECT +public: + explicit EleAnaClock(double w, double h, QString path, const QJsonObject &layer, QWidget *parent = nullptr); + void cal(); + QTimeZone timeZone; + QPixmap img; + QColor pinHourColor, pinMinColor, pinSecColor; + QPointF hPoses[3]{}, mPoses[3]{}, sPoses[3]{}; + double hAngle, mAngle, sAngle; + QPen pen; + int timerId{0}; + bool showSecHand{true}; + +protected: + void paintEvent(QPaintEvent *) override; + void timerEvent(QTimerEvent *) override; +}; + +#endif // ELEANACLOCK_H diff --git a/LedOK/player/elebase.cpp b/LedOK/player/elebase.cpp index ca8907d..37cb708 100644 --- a/LedOK/player/elebase.cpp +++ b/LedOK/player/elebase.cpp @@ -1 +1 @@ -//#include "elebase.h" +//#include "elebase.h" diff --git a/LedOK/player/elebase.h b/LedOK/player/elebase.h index a92c4af..654992a 100644 --- a/LedOK/player/elebase.h +++ b/LedOK/player/elebase.h @@ -1,20 +1,20 @@ -#ifndef ELEBASE_H -#define ELEBASE_H -#include - -class EleBase { -public: - QString id; - QString type; - int x; - int y; - int w; - int h; - int startTime; - int timeSpan; - int endTime; - - QWidget* wgt = nullptr; -}; - -#endif // ELEBASE_H +#ifndef ELEBASE_H +#define ELEBASE_H +#include + +class EleBase { +public: + QString id; + QString type; + int x; + int y; + int w; + int h; + int startTime; + int endTime; + bool repeat; + + QWidget *wgt{0}; +}; + +#endif // ELEBASE_H diff --git a/LedOK/player/eleborder.cpp b/LedOK/player/eleborder.cpp index aaf9e35..01df0d3 100644 --- a/LedOK/player/eleborder.cpp +++ b/LedOK/player/eleborder.cpp @@ -1,76 +1,76 @@ -#include "eleborder.h" -#include -#include -#include -#include - -EleBorder::EleBorder(QString path, QString eff, int speed, QWidget *parent) : QWidget{parent}, speed(speed) { - img.load(path); - if(eff.startsWith("ro")) this->eff = 'r'; - else if(eff.startsWith("bl")) this->eff = 'b'; -} - -void EleBorder::paintEvent(QPaintEvent *) { - if(eff=='b' && off > 0) return; - if(timerId==0) { - if(eff=='r') timerId = startTimer(speed==1 ? 66 : (speed==2 ? 33 : 16), Qt::PreciseTimer); - else if(eff=='b') timerId = startTimer(speed==1 ? 500 : (speed==2 ? 250 : 66)); - } - int bdWidth = img.height(); - int halfBdWidth = (bdWidth+1)/2; - QBrush brush(img); - QTransform transTop = QTransform::fromTranslate(halfBdWidth+off, 0); - QTransform transRight = QTransform::fromTranslate(width() - bdWidth, halfBdWidth*3-width()+off); - transRight.rotate(90); - QTransform transBottom = QTransform::fromTranslate(halfBdWidth*3-height()-off, height() - bdWidth); - transBottom.rotate(180); - QTransform transLeft = QTransform::fromTranslate(0, halfBdWidth-off); - transLeft.rotate(270); - - QPainter painter(this); - brush.setTransform(transTop); - QPainterPath path(QPointF(0, 0)); - path.lineTo(width(), 0); - path.lineTo(width() - bdWidth, bdWidth); - path.lineTo(bdWidth, bdWidth); - path.closeSubpath(); - painter.fillPath(path, brush); - - brush.setTransform(transRight); - path = QPainterPath(QPointF(width(), 0)); - path.lineTo(width(), height()); - path.lineTo(width() - bdWidth, height() - bdWidth); - path.lineTo(width() - bdWidth, bdWidth); - path.closeSubpath(); - painter.fillPath(path, brush); - - brush.setTransform(transBottom); - path = QPainterPath(QPointF(width(), height())); - path.lineTo(0, height()); - path.lineTo(bdWidth, height() - bdWidth); - path.lineTo(width() - bdWidth, height() - bdWidth); - path.closeSubpath(); - painter.fillPath(path, brush); - - brush.setTransform(transLeft); - path = QPainterPath(QPointF(0, height())); - path.lineTo(0, 0); - path.lineTo(bdWidth, bdWidth); - path.lineTo(bdWidth, height() - bdWidth); - path.closeSubpath(); - painter.fillPath(path, brush); - -} - -void EleBorder::timerEvent(QTimerEvent *) { - if(isVisible()) { - if(eff=='r') { - if(off >= img.width() - 1) off = 0; - else off++; - } else off = off==0 ? 1 : 0; - update(); - } else if(timerId!=0) { - killTimer(timerId); - timerId = 0; - } -} +#include "eleborder.h" +#include +#include +#include +#include + +EleBorder::EleBorder(QString path, QString eff, int speed, QWidget *parent) : QWidget{parent}, speed(speed) { + img.load(path); + if(eff.startsWith("ro")) this->eff = 'r'; + else if(eff.startsWith("bl")) this->eff = 'b'; +} + +void EleBorder::paintEvent(QPaintEvent *) { + if(eff=='b' && off > 0) return; + if(timerId==0) { + if(eff=='r') timerId = startTimer(speed==1 ? 66 : (speed==2 ? 33 : 16), Qt::PreciseTimer); + else if(eff=='b') timerId = startTimer(speed==1 ? 500 : (speed==2 ? 250 : 66)); + } + int bdWidth = img.height(); + int halfBdWidth = (bdWidth+1)/2; + QBrush brush(img); + QTransform transTop = QTransform::fromTranslate(halfBdWidth+off, 0); + QTransform transRight = QTransform::fromTranslate(width() - bdWidth, halfBdWidth*3-width()+off); + transRight.rotate(90); + QTransform transBottom = QTransform::fromTranslate(halfBdWidth*3-height()-off, height() - bdWidth); + transBottom.rotate(180); + QTransform transLeft = QTransform::fromTranslate(0, halfBdWidth-off); + transLeft.rotate(270); + + QPainter painter(this); + brush.setTransform(transTop); + QPainterPath path(QPointF(0, 0)); + path.lineTo(width(), 0); + path.lineTo(width() - bdWidth, bdWidth); + path.lineTo(bdWidth, bdWidth); + path.closeSubpath(); + painter.fillPath(path, brush); + + brush.setTransform(transRight); + path = QPainterPath(QPointF(width(), 0)); + path.lineTo(width(), height()); + path.lineTo(width() - bdWidth, height() - bdWidth); + path.lineTo(width() - bdWidth, bdWidth); + path.closeSubpath(); + painter.fillPath(path, brush); + + brush.setTransform(transBottom); + path = QPainterPath(QPointF(width(), height())); + path.lineTo(0, height()); + path.lineTo(bdWidth, height() - bdWidth); + path.lineTo(width() - bdWidth, height() - bdWidth); + path.closeSubpath(); + painter.fillPath(path, brush); + + brush.setTransform(transLeft); + path = QPainterPath(QPointF(0, height())); + path.lineTo(0, 0); + path.lineTo(bdWidth, bdWidth); + path.lineTo(bdWidth, height() - bdWidth); + path.closeSubpath(); + painter.fillPath(path, brush); + +} + +void EleBorder::timerEvent(QTimerEvent *) { + if(isVisible()) { + if(eff=='r') { + if(off >= img.width() - 1) off = 0; + else off++; + } else off = off==0 ? 1 : 0; + update(); + } else if(timerId!=0) { + killTimer(timerId); + timerId = 0; + } +} diff --git a/LedOK/player/eleborder.h b/LedOK/player/eleborder.h index 1ff0730..aee62bc 100644 --- a/LedOK/player/eleborder.h +++ b/LedOK/player/eleborder.h @@ -1,19 +1,19 @@ -#ifndef ELEBORDER_H -#define ELEBORDER_H - -#include - -class EleBorder : public QWidget { - Q_OBJECT -public: - explicit EleBorder(QString, QString, int, QWidget *parent = nullptr); - QPixmap img; - char eff = 0; - int speed = 2, off = 0; - int timerId = 0; -protected: - void paintEvent(QPaintEvent *) override; - void timerEvent(QTimerEvent *) override; -}; - -#endif +#ifndef ELEBORDER_H +#define ELEBORDER_H + +#include + +class EleBorder : public QWidget { + Q_OBJECT +public: + explicit EleBorder(QString, QString, int, QWidget *parent = nullptr); + QPixmap img; + char eff = 0; + int speed = 2, off = 0; + int timerId = 0; +protected: + void paintEvent(QPaintEvent *) override; + void timerEvent(QTimerEvent *) override; +}; + +#endif diff --git a/LedOK/player/elegif.cpp b/LedOK/player/elegif.cpp index eb08c6c..0702d39 100644 --- a/LedOK/player/elegif.cpp +++ b/LedOK/player/elegif.cpp @@ -1,32 +1,32 @@ -#include "elegif.h" -#include -#include - -EleGif::EleGif(QString path, QWidget *parent) : QWidget{parent} { - movie = new QMovie(path, QByteArray(), this); - movie->setCacheMode(QMovie::CacheAll); - movie->jumpToFrame(0); -} - -void EleGif::paintEvent(QPaintEvent *){ - QPainter painter(this); - if(movie!=nullptr) { - painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - painter.drawPixmap(0, 0, width(), height(), movie->currentPixmap()); - if(timer==nullptr) { - timer = new SyncTimer(movie->nextFrameDelay()); - connect(timer, &SyncTimer::timeout, this, &EleGif::sltNext, Qt::BlockingQueuedConnection); - timer->start(); - } - } -} -void EleGif::sltNext(){ - if(isVisible()) { - movie->jumpToNextFrame(); - timer->inter = movie->nextFrameDelay(); - repaint(); - } else if(timer!=nullptr) { - timer->stop(); - timer = nullptr; - } -} +#include "elegif.h" +#include +#include + +EleGif::EleGif(QString path, QWidget *parent) : QWidget{parent} { + movie = new QMovie(path, QByteArray(), this); + movie->setCacheMode(QMovie::CacheAll); + movie->jumpToFrame(0); +} + +void EleGif::paintEvent(QPaintEvent *){ + QPainter painter(this); + if(movie!=nullptr) { + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + painter.drawPixmap(0, 0, width(), height(), movie->currentPixmap()); + if(timer==nullptr) { + timer = new SyncTimer(movie->nextFrameDelay()); + connect(timer, &SyncTimer::timeout, this, &EleGif::sltNext, Qt::BlockingQueuedConnection); + timer->start(); + } + } +} +void EleGif::sltNext(){ + if(isVisible()) { + movie->jumpToNextFrame(); + timer->inter = movie->nextFrameDelay(); + update(); + } else if(timer!=nullptr) { + timer->stop(); + timer = nullptr; + } +} diff --git a/LedOK/player/elegif.h b/LedOK/player/elegif.h index 7d2771e..0a71ab0 100644 --- a/LedOK/player/elegif.h +++ b/LedOK/player/elegif.h @@ -1,21 +1,21 @@ -#ifndef ELEGIF_H -#define ELEGIF_H -#include "synctimer.h" -#include - -class EleGif : public QWidget { - Q_OBJECT -public: - explicit EleGif(QString path, QWidget *parent = nullptr); - - QMovie* movie = nullptr; - SyncTimer* timer = nullptr; - -public slots: - void sltNext(); - -protected: - void paintEvent(QPaintEvent *) override; -}; - -#endif // ELEGIF_H +#ifndef ELEGIF_H +#define ELEGIF_H +#include "synctimer.h" +#include + +class EleGif : public QWidget { + Q_OBJECT +public: + explicit EleGif(QString path, QWidget *parent = nullptr); + + QMovie* movie = nullptr; + SyncTimer* timer = nullptr; + +public slots: + void sltNext(); + +protected: + void paintEvent(QPaintEvent *) override; +}; + +#endif // ELEGIF_H diff --git a/LedOK/player/eleimg.cpp b/LedOK/player/eleimg.cpp index 4b250e7..dc91b4c 100644 --- a/LedOK/player/eleimg.cpp +++ b/LedOK/player/eleimg.cpp @@ -1,14 +1,14 @@ -#include "eleimg.h" -#include -#include - -EleImg::EleImg(QString path, QWidget *parent) : QWidget{parent} { - img.load(path); -} - -void EleImg::paintEvent(QPaintEvent *){ - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - if(! img.isNull()) painter.drawPixmap(0, 0, width(), height(), img); -} - +#include "eleimg.h" +#include +#include + +EleImg::EleImg(QString path, QWidget *parent) : QWidget{parent} { + img.load(path); +} + +void EleImg::paintEvent(QPaintEvent *){ + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + if(! img.isNull()) painter.drawPixmap(0, 0, width(), height(), img); +} + diff --git a/LedOK/player/eleimg.h b/LedOK/player/eleimg.h index b96d3cb..3f8e93e 100644 --- a/LedOK/player/eleimg.h +++ b/LedOK/player/eleimg.h @@ -1,15 +1,15 @@ -#ifndef ELEIMG_H -#define ELEIMG_H - -#include - -class EleImg : public QWidget { - Q_OBJECT -public: - explicit EleImg(QString, QWidget *parent = nullptr); - QPixmap img; -protected: - void paintEvent(QPaintEvent *) override; -}; - -#endif // ELEIMG_H +#ifndef ELEIMG_H +#define ELEIMG_H + +#include + +class EleImg : public QWidget { + Q_OBJECT +public: + explicit EleImg(QString, QWidget *parent = nullptr); + QPixmap img; +protected: + void paintEvent(QPaintEvent *) override; +}; + +#endif // ELEIMG_H diff --git a/LedOK/player/elemultipng.cpp b/LedOK/player/elemultipng.cpp index 3e6bd60..6ceb671 100644 --- a/LedOK/player/elemultipng.cpp +++ b/LedOK/player/elemultipng.cpp @@ -1,98 +1,104 @@ -#include "elemultipng.h" -#include -#include -#include -#include -const QChar effTypes[] = {'l', 't', 'r', 'b'}; - -EleMultiPng::EleMultiPng(QString dirPre, QJsonArray maps, QWidget *parent) : QWidget{parent} { - QJsonObject map = maps[0].toObject(); - EffDur = map["effectSpeed"].toInt()*1000; - if(EffDur==0) return; - picDur = map["picDuration"].toInt()*1000; - if(picDur==0) picDur = EffDur; - foreach(auto map, maps) imgs.append(QPixmap(dirPre+map["id"].toString())); - QString effStr = map["effect"].toString(); - if(effStr.isEmpty() || effStr=="no") EffDur = 0; - else if(effStr.endsWith("left")) effType = 'l'; - else if(effStr.endsWith("top")) effType = 't'; - else if(effStr.endsWith("right")) effType = 'r'; - else if(effStr.endsWith("bottom")) effType = 'b'; - else if(effStr == "random") needRand = true; - else EffDur = 0; -} - -void EleMultiPng::startMove() { - if(EffDur==0) return; - if(needRand) effType = effTypes[rand.generate() % 4]; - double effDurD = EffDur; - if(effType=='l') { - imgx = width(); - imgy = 0; - effDurD /= width(); - } else if(effType=='r') { - imgx = -width(); - imgy = 0; - effDurD /= width(); - } else if(effType=='t') { - imgx = 0; - imgy = height(); - effDurD /= height(); - } else if(effType=='b') { - imgx = 0; - imgy = -height(); - effDurD /= height(); - } else return; - movePx = ceil(17/effDurD); - moveInter = effDurD*movePx; - moveTimerId = startTimer(moveInter, Qt::PreciseTimer); -} - -void EleMultiPng::paintEvent(QPaintEvent *) { - if(timerId==0 && (EffDur!=0 || imgs.size()>1)) { - timerId = startTimer(picDur, Qt::PreciseTimer); - startMove(); - } - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - painter.drawPixmap(imgx, imgy, imgs[imgc]); -} - -void EleMultiPng::timerEvent(QTimerEvent *e) { - if(isVisible()) { - int id = e->timerId(); - if(id==timerId){ - if(imgc+2 > imgs.size()) imgc = 0; - else imgc++; - startMove(); - } else if(id==moveTimerId){ - if(effType=='l') { - imgx -= movePx; - if(imgx < 0) imgx = 0; - } else if(effType=='t') { - imgy -= movePx; - if(imgy < 0) imgy = 0; - } else if(effType=='r') { - imgx += movePx; - if(imgx > 0) imgx = 0; - } else if(effType=='b') { - imgy += movePx; - if(imgy > 0) imgy = 0; - } - if(imgx==0 && imgy==0) { - killTimer(moveTimerId); - moveTimerId = 0; - } - } - update(); - } else { - if(timerId!=0) { - killTimer(timerId); - timerId = 0; - } - if(moveTimerId!=0) { - killTimer(moveTimerId); - moveTimerId = 0; - } - } -} +#include "elemultipng.h" +#include +#include +#include +#include +const QChar effTypes[] = {'l', 't', 'r', 'b'}; + +EleMultiPng::EleMultiPng(QString dirPre, QJsonArray maps, QWidget *parent) : QWidget{parent} { + QJsonObject map = maps[0].toObject(); + picDur = map["picDuration"].toInt()*1000; + if(picDur==0) return; + EffDur = map["effectSpeed"].toInt()*1000; + foreach(auto map, maps) imgs.append(QPixmap(dirPre+map["id"].toString())); + QString effStr = map["effect"].toString(); + if(effStr.isEmpty() || effStr=="no") EffDur = 0; + else if(effStr.endsWith("left")) effType = 'l'; + else if(effStr.endsWith("top")) effType = 't'; + else if(effStr.endsWith("right")) effType = 'r'; + else if(effStr.endsWith("bottom")) effType = 'b'; + else if(effStr == "random") needRand = true; + else EffDur = 0; +} + +void EleMultiPng::startMove() { + if(EffDur==0) return; + if(needRand) effType = effTypes[rand.generate() % 4]; + double effDurD = EffDur; + if(effType=='l') { + imgx = width(); + imgy = 0; + effDurD /= width(); + } else if(effType=='r') { + imgx = -width(); + imgy = 0; + effDurD /= width(); + } else if(effType=='t') { + imgx = 0; + imgy = height(); + effDurD /= height(); + } else if(effType=='b') { + imgx = 0; + imgy = -height(); + effDurD /= height(); + } else return; + movePx = ceil(17/effDurD); + moveInter = effDurD*movePx; + moveTimerId = startTimer(moveInter, Qt::PreciseTimer); +} + +void EleMultiPng::paintEvent(QPaintEvent *) { + if(timerId==0 && (EffDur!=0 || imgs.size()>1)) { + timerId = startTimer(picDur, Qt::PreciseTimer); + startMove(); + } + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + painter.drawPixmap(imgx, imgy, imgs[imgc]); +} + +void EleMultiPng::timerEvent(QTimerEvent *e) { + if(isVisible()) { + int id = e->timerId(); + if(id==timerId){ + if(imgc+2 > imgs.size()) imgc = 0; + else imgc++; + startMove(); + } else if(id==moveTimerId){ + if(effType=='l') { + imgx -= movePx; + if(imgx < 0) imgx = 0; + } else if(effType=='t') { + imgy -= movePx; + if(imgy < 0) imgy = 0; + } else if(effType=='r') { + imgx += movePx; + if(imgx > 0) imgx = 0; + } else if(effType=='b') { + imgy += movePx; + if(imgy > 0) imgy = 0; + } + if(imgx==0 && imgy==0) { + killTimer(moveTimerId); + moveTimerId = 0; + } + } + update(); + foreach(auto split, splits) split->update(); + } else { + if(timerId!=0) { + killTimer(timerId); + timerId = 0; + } + if(moveTimerId!=0) { + killTimer(moveTimerId); + moveTimerId = 0; + } + } +} + +void EleSplitPng::paintEvent(QPaintEvent *) { + QPainter painter(this); + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + painter.drawPixmap(multiPng->imgx, multiPng->imgy, multiPng->imgs[multiPng->imgc]); +} diff --git a/LedOK/player/elemultipng.h b/LedOK/player/elemultipng.h index c658d71..2191b3e 100644 --- a/LedOK/player/elemultipng.h +++ b/LedOK/player/elemultipng.h @@ -1,24 +1,37 @@ -#ifndef ELEMULTIPNG_H -#define ELEMULTIPNG_H - -#include -#include - -class EleMultiPng : public QWidget { - Q_OBJECT -public: - explicit EleMultiPng(QString, QJsonArray, QWidget *parent = nullptr); - void startMove(); - - QVector imgs; - int timerId = 0, moveTimerId = 0; - int picDur = 0, EffDur = 0, moveInter = 0, movePx = 0, imgc = 0, imgx = 0, imgy = 0; - QChar effType = 0; - QRandomGenerator rand; - bool needRand = false; -protected: - void paintEvent(QPaintEvent *) override; - void timerEvent(QTimerEvent *) override; -}; - -#endif // ELEMULTIPNG_H +#ifndef ELEMULTIPNG_H +#define ELEMULTIPNG_H + +#include +#include +class EleSplitPng; +class EleMultiPng : public QWidget { + Q_OBJECT +public: + explicit EleMultiPng(QString, QJsonArray, QWidget *parent = nullptr); + void startMove(); + + QVector imgs; + int timerId = 0, moveTimerId = 0; + int picDur = 0, EffDur = 0, moveInter = 0, movePx = 0, imgc = 0, imgx = 0, imgy = 0; + QChar effType = 0; + QRandomGenerator rand; + bool needRand = false; + QList splits; + +protected: + void paintEvent(QPaintEvent *) override; + void timerEvent(QTimerEvent *) override; +}; + +class EleSplitPng : public QWidget { + Q_OBJECT +public: + explicit EleSplitPng(EleMultiPng *multiPng, QWidget *parent) : QWidget{parent}, multiPng(multiPng) {} + +protected: + void paintEvent(QPaintEvent *) override; + + EleMultiPng *multiPng; +}; + +#endif // ELEMULTIPNG_H diff --git a/LedOK/player/elescroll.cpp b/LedOK/player/elescroll.cpp index f29e3e4..b827bfb 100644 --- a/LedOK/player/elescroll.cpp +++ b/LedOK/player/elescroll.cpp @@ -1,72 +1,80 @@ -#include "elescroll.h" -#include -#include -#include - -EleScroll::EleScroll(QWidget *parent, QString dirPre, QJsonObject map) : QWidget{parent} { - img.load(dirPre + map["id"].toString()); - QString effStr = map["effect"].toString(); - if(effStr.isNull() || effStr=="no") return; - double effDurD = map["effectSpeed"].toInt()/2; - if(effDurD==0) return; - int idx = effStr.lastIndexOf(' '); - if(idx > -1) { - effect = effStr.at(idx+1).toLatin1(); - if(effect=='l') end = -(img.width()-1); - else if(effect=='r') end = img.width()-1; - else if(effect=='t') end = -(img.height()-1); - else if(effect=='b') end = img.height()-1; - } - interval = ceil(effDurD/16.666666)*16.666666; - curAdd = ceil(interval/effDurD); -} -EleScroll::EleScroll(QWidget *parent, QString imgPath, char effect, double effDur) : QWidget{parent}, effect(effect) { - img.load(imgPath); - if(effect==0) return; - if(effDur==0) return; - if(effect=='l') end = -(img.width()-1); - else if(effect=='r') end = img.width()-1; - else if(effect=='t') end = -(img.height()-1); - else if(effect=='b') end = img.height()-1; - interval = ceil(effDur/16.666666)*16.666666; - curAdd = ceil(interval/effDur); -} - -void EleScroll::paintEvent(QPaintEvent *) { - if(img.isNull()) return; - if(timerId==0 && effect!=0 && interval!=0) { - cur = 0; - timerId = startTimer(interval, Qt::PreciseTimer); - } - QPainter painter(this); - painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - if(effect=='l') { - painter.drawPixmap(cur, 0, img); - painter.drawPixmap(cur+img.width(), 0, img); - } else if(effect=='r') { - painter.drawPixmap(cur, 0, img); - painter.drawPixmap(cur-img.width(), 0, img); - } else if(effect=='t') { - painter.drawPixmap(0, cur, img); - painter.drawPixmap(0, cur+img.height(), img); - } else if(effect=='b') { - painter.drawPixmap(0, cur, img); - painter.drawPixmap(0, cur-img.height(), img); - } else painter.drawPixmap(0, 0, img); -} - -void EleScroll::timerEvent(QTimerEvent *) { - if(isVisible()) { - if(effect=='t' || effect=='l') { - if(cur <= end) cur = 0; - else cur-=curAdd; - } else if(effect=='b' || effect=='r') { - if(cur >= end) cur = 0; - else cur+=curAdd; - } - update(); - } else if(timerId!=0) { - killTimer(timerId); - timerId = 0; - } -} +#include "elescroll.h" +#include +#include +#include + +EleScroll::EleScroll(QWidget *parent, QString dirPre, QJsonObject map) : QWidget{parent} { + img.load(dirPre + map["id"].toString()); + QString effStr = map["effect"].toString(); + if(effStr.isNull() || effStr=="no") return; + double effDurD = map["effectSpeed"].toInt()/2; + if(effDurD==0) return; + int idx = effStr.lastIndexOf(' '); + if(idx > -1) { + effect = effStr.at(idx+1).toLatin1(); + if(effect=='l') end = -(img.width()-1); + else if(effect=='r') end = img.width()-1; + else if(effect=='t') end = -(img.height()-1); + else if(effect=='b') end = img.height()-1; + } + interval = ceil(effDurD/16.666666)*16.666666; + curAdd = ceil(interval/effDurD); +} +EleScroll::EleScroll(QWidget *parent, QString imgPath, char effect, double effDur) : QWidget{parent}, effect(effect) { + img.load(imgPath); + if(effect==0) return; + if(effDur==0) return; + if(effect=='l') end = -(img.width()-1); + else if(effect=='r') end = img.width()-1; + else if(effect=='t') end = -(img.height()-1); + else if(effect=='b') end = img.height()-1; + interval = ceil(effDur/16.666666)*16.666666; + curAdd = ceil(interval/effDur); +} + +void EleScroll::paintEvent(QPaintEvent *) { + paint(this); +} +void EleScroll::paint(QPaintDevice *that) { + if(img.isNull()) return; + if(timerId==0 && effect!=0 && interval!=0) { + cur = 0; + timerId = startTimer(interval, Qt::PreciseTimer); + } + QPainter painter(that); + painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); + if(effect=='l') { + painter.drawPixmap(cur, 0, img); + painter.drawPixmap(cur+img.width(), 0, img); + } else if(effect=='r') { + painter.drawPixmap(cur, 0, img); + painter.drawPixmap(cur-img.width(), 0, img); + } else if(effect=='t') { + painter.drawPixmap(0, cur, img); + painter.drawPixmap(0, cur+img.height(), img); + } else if(effect=='b') { + painter.drawPixmap(0, cur, img); + painter.drawPixmap(0, cur-img.height(), img); + } else painter.drawPixmap(0, 0, img); +} + +void EleScroll::timerEvent(QTimerEvent *) { + if(isVisible()) { + if(effect=='t' || effect=='l') { + if(cur <= end) cur = 0; + else cur-=curAdd; + } else if(effect=='b' || effect=='r') { + if(cur >= end) cur = 0; + else cur+=curAdd; + } + update(); + foreach(auto split, splits) split->update(); + } else if(timerId!=0) { + killTimer(timerId); + timerId = 0; + } +} + +void EleSplitScroll::paintEvent(QPaintEvent *) { + scroll->paint(this); +} diff --git a/LedOK/player/elescroll.h b/LedOK/player/elescroll.h index 2941d32..b1be9bf 100644 --- a/LedOK/player/elescroll.h +++ b/LedOK/player/elescroll.h @@ -1,20 +1,31 @@ -#ifndef ELESCROLL_H -#define ELESCROLL_H - -#include - -class EleScroll : public QWidget { - Q_OBJECT -public: - explicit EleScroll(QWidget *, QString, QJsonObject); - explicit EleScroll(QWidget *, QString, char effect = 0, double effDur = 0.0); - QPixmap img; - char effect = 0; - int interval = 0, timerId = 0, cur = 0, end = 0, curAdd = 1; - -protected: - void paintEvent(QPaintEvent *) override; - void timerEvent(QTimerEvent *) override; -}; - -#endif // ELESCROLL_H +#ifndef ELESCROLL_H +#define ELESCROLL_H + +#include +class EleSplitScroll; +class EleScroll : public QWidget { + Q_OBJECT +public: + explicit EleScroll(QWidget *, QString, QJsonObject); + explicit EleScroll(QWidget *, QString, char effect = 0, double effDur = 0.0); + QPixmap img; + char effect = 0; + int interval = 0, timerId = 0, cur = 0, end = 0, curAdd = 1; + QList splits; + void paint(QPaintDevice *); +protected: + void paintEvent(QPaintEvent *) override; + void timerEvent(QTimerEvent *) override; +}; + +class EleSplitScroll : public QWidget { + Q_OBJECT +public: + explicit EleSplitScroll(QWidget *parent, EleScroll *scroll) : QWidget{parent}, scroll(scroll) {}; + +protected: + void paintEvent(QPaintEvent *) override; + + EleScroll *scroll; +}; +#endif // ELESCROLL_H diff --git a/LedOK/player/eletimer.cpp b/LedOK/player/eletimer.cpp index f878ee2..056e0f0 100644 --- a/LedOK/player/eletimer.cpp +++ b/LedOK/player/eletimer.cpp @@ -1,65 +1,65 @@ -#include "eletimer.h" -#include "tools.h" -#include "globaldefine.h" -#include -#include - -EleTimer::EleTimer(const QJsonObject &json, QWidget *parent) : QWidget{parent} { - isDown = json["isDown"].toBool(); - targetTime = QDateTime::fromString(json["targetTime"].toString(), "yyyy-MM-dd HH:mm:ss"); - hasDay = json["hasDay"].toBool(); - hasHour = json["hasHour"].toBool(); - hasMin = json["hasMin"].toBool(); - hasSec = json["hasSec"].toBool(); - text = json["text"].toString(); - isMultiline = json["isMultiline"].toBool(); - font = json["font"].toString(); - fontSize = json["fontSize"].toInt(); - fontBold = json["fontBold"].toBool(); - fontItalic = json["fontItalic"].toBool(); - fontUnderline = json["fontUnderline"].toBool(); - textColor = json["textColor"].toString(); - auto color = json["backColor"].toString(); - backColor = color.isEmpty() ? QColor(0,0,0,0) : color; - connect(Tools::getInstance(), &Tools::sTick, this, [this]() { - QDateTime cDateTime = QDateTime::currentDateTime(); - qint64 ofs = isDown ? cDateTime.secsTo(targetTime) : targetTime.secsTo(cDateTime); - if(ofs < 0) ofs = 0; - secs = ofs; - update(); - }); -} - -void EleTimer::paintEvent(QPaintEvent *){ - QString text; - if(! this->text.isEmpty()) { - text += this->text; - if(isMultiline) text += '\n'; - else text += " "; - } - int secs = this->secs; - if(hasDay) { - text.append(QString::number(secs/86400)).append(" ").append(tr("day")).append(" "); - secs %= 86400; - } - if(hasHour) { - text.append(QString::asprintf("%02d ", secs/3600)).append(tr("hour")).append(" "); - secs %= 3600; - } - if(hasMin) { - text.append(QString::asprintf("%02d ", secs/60)).append(tr("min")).append(" "); - secs %= 60; - } - if(hasSec) text.append(QString::asprintf("%02d ", secs)).append(tr("sec")).append(" "); - text = text.trimmed(); - QFont font(this->font, fontSize); - font.setBold(fontBold); - font.setItalic(fontItalic); - font.setUnderline(fontUnderline); - font.setStyleStrategy(gTextAntialiasing ? QFont::PreferAntialias : QFont::NoAntialias); - QPainter painter(this); - if(backColor.alpha() != 0) painter.fillRect(rect(), backColor); - painter.setFont(font); - painter.setPen(textColor); - painter.drawText(rect(), text, QTextOption(Qt::AlignCenter)); -} +#include "eletimer.h" +#include "tools.h" +#include "globaldefine.h" +#include +#include + +EleTimer::EleTimer(const QJsonObject &json, QWidget *parent) : QWidget{parent} { + isDown = json["isDown"].toBool(); + targetTime = QDateTime::fromString(json["targetTime"].toString(), "yyyy-MM-dd HH:mm:ss"); + hasDay = json["hasDay"].toBool(); + hasHour = json["hasHour"].toBool(); + hasMin = json["hasMin"].toBool(); + hasSec = json["hasSec"].toBool(); + text = json["text"].toString(); + isMultiline = json["isMultiline"].toBool(); + font = json["font"].toString(); + fontSize = json["fontSize"].toInt(); + fontBold = json["fontBold"].toBool(); + fontItalic = json["fontItalic"].toBool(); + fontUnderline = json["fontUnderline"].toBool(); + textColor = json["textColor"].toString(); + auto color = json["backColor"].toString(); + backColor = color.isEmpty() ? QColor(0,0,0,0) : color; + connect(Tools::getInstance(), &Tools::sTick, this, [this]() { + QDateTime cDateTime = QDateTime::currentDateTime(); + qint64 ofs = isDown ? cDateTime.secsTo(targetTime) : targetTime.secsTo(cDateTime); + if(ofs < 0) ofs = 0; + secs = ofs; + update(); + }); +} + +void EleTimer::paintEvent(QPaintEvent *){ + QString text; + if(! this->text.isEmpty()) { + text += this->text; + if(isMultiline) text += '\n'; + else text += " "; + } + int secs = this->secs; + if(hasDay) { + text.append(QString::number(secs/86400)).append(" ").append(tr("day")).append(" "); + secs %= 86400; + } + if(hasHour) { + text.append(QString::asprintf("%02d ", secs/3600)).append(tr("hour")).append(" "); + secs %= 3600; + } + if(hasMin) { + text.append(QString::asprintf("%02d ", secs/60)).append(tr("min")).append(" "); + secs %= 60; + } + if(hasSec) text.append(QString::asprintf("%02d ", secs)).append(tr("sec")).append(" "); + text = text.trimmed(); + QFont font(this->font, fontSize); + font.setBold(fontBold); + font.setItalic(fontItalic); + font.setUnderline(fontUnderline); + font.setStyleStrategy(gTextAntialiasing ? QFont::PreferAntialias : QFont::NoAntialias); + QPainter painter(this); + if(backColor.alpha() != 0) painter.fillRect(rect(), backColor); + painter.setFont(font); + painter.setPen(textColor); + painter.drawText(rect(), text, QTextOption(Qt::AlignCenter)); +} diff --git a/LedOK/player/eletimer.h b/LedOK/player/eletimer.h index 22ca696..ae9b3d1 100644 --- a/LedOK/player/eletimer.h +++ b/LedOK/player/eletimer.h @@ -1,31 +1,31 @@ -#ifndef ELETIMER_H -#define ELETIMER_H - -#include -#include - -class EleTimer : public QWidget { - Q_OBJECT -public: - explicit EleTimer(const QJsonObject&, QWidget *parent = nullptr); - QDateTime targetTime; - QString text; - QColor textColor; - QColor backColor; - QString font; - int fontSize; - bool fontBold; - bool fontItalic; - bool fontUnderline; - bool isDown; - bool isMultiline; - bool hasDay; - bool hasHour; - bool hasMin; - bool hasSec; - int secs = 0; -protected: - void paintEvent(QPaintEvent *) override; -}; - -#endif // ELETIMER_H +#ifndef ELETIMER_H +#define ELETIMER_H + +#include +#include + +class EleTimer : public QWidget { + Q_OBJECT +public: + explicit EleTimer(const QJsonObject&, QWidget *parent = nullptr); + QDateTime targetTime; + QString text; + QColor textColor; + QColor backColor; + QString font; + int fontSize; + bool fontBold; + bool fontItalic; + bool fontUnderline; + bool isDown; + bool isMultiline; + bool hasDay; + bool hasHour; + bool hasMin; + bool hasSec; + int secs = 0; +protected: + void paintEvent(QPaintEvent *) override; +}; + +#endif // ELETIMER_H diff --git a/LedOK/player/elevideo - qt.cpp b/LedOK/player/elevideo - qt.cpp index 4122b20..1aa05da 100644 --- a/LedOK/player/elevideo - qt.cpp +++ b/LedOK/player/elevideo - qt.cpp @@ -1,38 +1,38 @@ -#include "elevideo.h" -#include "tools.h" -#include -#include -#include -#include -#include -#include -#include - -EleVideo::EleVideo(QString path, int w, int h, QWidget *parent) : QGraphicsView{parent} { - setFrameStyle(QFrame::NoFrame); - setScene(new QGraphicsScene(this)); - setBackgroundBrush(QColor(0,0,0)); - auto videoItem = new QGraphicsVideoItem(); - videoItem->setSize(QSize(w,h)); - videoItem->setAspectRatioMode(Qt::IgnoreAspectRatio); - scene()->addItem(videoItem); - player = new QMediaPlayer(videoItem); - player->setVideoOutput(videoItem); - connect(player, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status){ - if(status==QMediaPlayer::EndOfMedia) { - if(player->state() != QMediaPlayer::PlayingState && isVisible()) player->play(); - } - }); - void(QMediaPlayer::*player_error)(QMediaPlayer::Error) = &QMediaPlayer::error; - connect(player, player_error, this, [this](QMediaPlayer::Error error){ - QMessageBox::critical(this, "Video Error", Tools::playerErrStr(error)+": "+player->errorString()); - }); - player->setMedia(QUrl::fromLocalFile(path)); -} - -void EleVideo::showEvent(QShowEvent *) { - if(player!=nullptr && player->state() != QMediaPlayer::PlayingState) player->play(); -} -void EleVideo::hideEvent(QHideEvent *) { - if(player!=nullptr) player->stop(); -} +#include "elevideo.h" +#include "tools.h" +#include +#include +#include +#include +#include +#include +#include + +EleVideo::EleVideo(QString path, int w, int h, QWidget *parent) : QGraphicsView{parent} { + setFrameStyle(QFrame::NoFrame); + setScene(new QGraphicsScene(this)); + setBackgroundBrush(QColor(0,0,0)); + auto videoItem = new QGraphicsVideoItem(); + videoItem->setSize(QSize(w,h)); + videoItem->setAspectRatioMode(Qt::IgnoreAspectRatio); + scene()->addItem(videoItem); + player = new QMediaPlayer(videoItem); + player->setVideoOutput(videoItem); + connect(player, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status){ + if(status==QMediaPlayer::EndOfMedia) { + if(player->state() != QMediaPlayer::PlayingState && isVisible()) player->play(); + } + }); + void(QMediaPlayer::*player_error)(QMediaPlayer::Error) = &QMediaPlayer::error; + connect(player, player_error, this, [this](QMediaPlayer::Error error){ + QMessageBox::critical(this, "Video Error", Tools::playerErrStr(error)+": "+player->errorString()); + }); + player->setMedia(QUrl::fromLocalFile(path)); +} + +void EleVideo::showEvent(QShowEvent *) { + if(player!=nullptr && player->state() != QMediaPlayer::PlayingState) player->play(); +} +void EleVideo::hideEvent(QHideEvent *) { + if(player!=nullptr) player->stop(); +} diff --git a/LedOK/player/elevideo - qt.h b/LedOK/player/elevideo - qt.h index 3eff40a..af73591 100644 --- a/LedOK/player/elevideo - qt.h +++ b/LedOK/player/elevideo - qt.h @@ -1,16 +1,16 @@ -#ifndef ELEVIDEO_H -#define ELEVIDEO_H -#include -#include - -class EleVideo : public QGraphicsView { - Q_OBJECT -public: - explicit EleVideo(QString path, int, int, QWidget *parent = nullptr); - QMediaPlayer *player = nullptr; -protected: - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; -}; - -#endif // ELEVIDEO_H +#ifndef ELEVIDEO_H +#define ELEVIDEO_H +#include +#include + +class EleVideo : public QGraphicsView { + Q_OBJECT +public: + explicit EleVideo(QString path, int, int, QWidget *parent = nullptr); + QMediaPlayer *player = nullptr; +protected: + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; +}; + +#endif // ELEVIDEO_H diff --git a/LedOK/player/elevideo - vlc.cpp b/LedOK/player/elevideo - vlc.cpp index f7d7462..c5aa60a 100644 --- a/LedOK/player/elevideo - vlc.cpp +++ b/LedOK/player/elevideo - vlc.cpp @@ -1,61 +1,61 @@ -#include "elevideo.h" -#include "tools.h" -#include -#include -#include - -static void *lock(void *opaque, void **planes) { - auto that = (EleVideo *) opaque; - that->imgRaw = QImage(that->mWidth, that->mHeight, QImage::Format_RGB32); - *planes = that->imgRaw.bits(); /*tell VLC to put decoded data to this buffer*/ - return 0; /* picture identifier, not needed here */ -} -static void unlock(void *opaque, void *picture, void *const *planes) { -} - -static void display(void *opaque, void *picture) { - auto that = (EleVideo *) opaque; - that->emDisplay(that->imgRaw); -} - -EleVideo::EleVideo(QString path, QWidget *parent) : QWidget{parent} { - vlc = libvlc_new(0, NULL); - auto pathChars = path.replace("/","\\").toUtf8(); - auto media = libvlc_media_new_path(vlc, pathChars.data()); - qDebug()<<"media"<img; -// qDebug()<<"viCurTime"<viCurTime; -// qDebug()<<"viSize"<viSize; -//} -void EleVideo::showEvent(QShowEvent *) { - if(player!=nullptr) libvlc_media_player_play(player); -} -void EleVideo::hideEvent(QHideEvent *) { - if(player!=nullptr) libvlc_media_player_stop(player); -} - -void EleVideo::paintEvent(QPaintEvent *e) { - QWidget::paintEvent(e); - QPainter painter(this); - painter.drawImage(QRectF(0, 0, width(), height()), img); -} +#include "elevideo.h" +#include "tools.h" +#include +#include +#include + +static void *lock(void *opaque, void **planes) { + auto that = (EleVideo *) opaque; + that->imgRaw = QImage(that->mWidth, that->mHeight, QImage::Format_RGB32); + *planes = that->imgRaw.bits(); /*tell VLC to put decoded data to this buffer*/ + return 0; /* picture identifier, not needed here */ +} +static void unlock(void *opaque, void *picture, void *const *planes) { +} + +static void display(void *opaque, void *picture) { + auto that = (EleVideo *) opaque; + that->emDisplay(that->imgRaw); +} + +EleVideo::EleVideo(QString path, QWidget *parent) : QWidget{parent} { + vlc = libvlc_new(0, NULL); + auto pathChars = path.replace("/","\\").toUtf8(); + auto media = libvlc_media_new_path(vlc, pathChars.data()); + qDebug()<<"media"<img; +// qDebug()<<"viCurTime"<viCurTime; +// qDebug()<<"viSize"<viSize; +//} +void EleVideo::showEvent(QShowEvent *) { + if(player!=nullptr) libvlc_media_player_play(player); +} +void EleVideo::hideEvent(QHideEvent *) { + if(player!=nullptr) libvlc_media_player_stop(player); +} + +void EleVideo::paintEvent(QPaintEvent *e) { + QWidget::paintEvent(e); + QPainter painter(this); + painter.drawImage(QRectF(0, 0, width(), height()), img); +} diff --git a/LedOK/player/elevideo - vlc.h b/LedOK/player/elevideo - vlc.h index d40ab40..5447e0b 100644 --- a/LedOK/player/elevideo - vlc.h +++ b/LedOK/player/elevideo - vlc.h @@ -1,29 +1,29 @@ -#ifndef ELEVIDEO_H -#define ELEVIDEO_H - -#include -#include - -class EleVideo : public QWidget { - Q_OBJECT -public: - explicit EleVideo(QString path, QWidget *parent = nullptr); - ~EleVideo() { - if(vlc) libvlc_release(vlc); - if(player) libvlc_media_player_release(player); - } - - unsigned mWidth{0}, mHeight{0}; - QImage imgRaw; - QImage img; - libvlc_instance_t *vlc{0}; - libvlc_media_player_t *player{0}; -protected: - void paintEvent(QPaintEvent *) override; - void showEvent(QShowEvent *) override; - void hideEvent(QHideEvent *) override; -signals: - void emDisplay(QImage img); -}; - -#endif // ELEVIDEO_H +#ifndef ELEVIDEO_H +#define ELEVIDEO_H + +#include +#include + +class EleVideo : public QWidget { + Q_OBJECT +public: + explicit EleVideo(QString path, QWidget *parent = nullptr); + ~EleVideo() { + if(vlc) libvlc_release(vlc); + if(player) libvlc_media_player_release(player); + } + + unsigned mWidth{0}, mHeight{0}; + QImage imgRaw; + QImage img; + libvlc_instance_t *vlc{0}; + libvlc_media_player_t *player{0}; +protected: + void paintEvent(QPaintEvent *) override; + void showEvent(QShowEvent *) override; + void hideEvent(QHideEvent *) override; +signals: + void emDisplay(QImage img); +}; + +#endif // ELEVIDEO_H diff --git a/LedOK/player/elevideo.cpp b/LedOK/player/elevideo.cpp index 9a072a8..b77272c 100644 --- a/LedOK/player/elevideo.cpp +++ b/LedOK/player/elevideo.cpp @@ -1,45 +1,45 @@ -#include "elevideo.h" -#include "tools.h" -#include -#include -#include - -class GL : public QOpenGLWidget { -public: - explicit GL(QWidget *parent) : QOpenGLWidget{parent} { - setGeometry(-1,-1,1,1); - connect(this, &QOpenGLWidget::frameSwapped, this, (void(QOpenGLWidget::*)())&QOpenGLWidget::update, Qt::QueuedConnection); - } -}; - -EleVideo::EleVideo(QString path, QWidget *parent) : QWidget{parent} { - player = new FFPlayer(); - connect(new GL(this), &QOpenGLWidget::frameSwapped, player, &FFPlayer::updFrame, Qt::QueuedConnection); - connect(player, &FFPlayer::emUpd, this, [this](QImage img) { - this->img = img; - update(); - }); - connect(player, &FFPlayer::emError, this, [this](QString err) { - QMessageBox::critical(this, "Video Error", err); - }); - player->open(path.toUtf8()); -} - -//void EleVideo::mouseDoubleClickEvent(QMouseEvent *) { -// qDebug()<<"img"<img; -// qDebug()<<"viCurTime"<viCurTime; -// qDebug()<<"viSize"<viSize; -//} -void EleVideo::showEvent(QShowEvent *) { - if(player!=nullptr) player->play(); -} -void EleVideo::hideEvent(QHideEvent *) { - if(player!=nullptr) player->stop(); -} - -void EleVideo::paintEvent(QPaintEvent *e) { - QWidget::paintEvent(e); - QPainter painter(this); - painter.drawImage(QRectF(0, 0, width(), height()), img); -} +#include "elevideo.h" +#include "tools.h" +#include +#include +#include + +class GL : public QOpenGLWidget { +public: + explicit GL(QWidget *parent) : QOpenGLWidget{parent} { + setGeometry(-1,-1,1,1); + connect(this, &QOpenGLWidget::frameSwapped, this, (void(QOpenGLWidget::*)())&QOpenGLWidget::update, Qt::QueuedConnection); + } +}; + +EleVideo::EleVideo(QString path, QWidget *parent) : QWidget{parent} { + player = new FFPlayer(); + connect(new GL(this), &QOpenGLWidget::frameSwapped, player, &FFPlayer::updFrame, Qt::QueuedConnection); + connect(player, &FFPlayer::emUpd, this, [this](QImage img) { + this->img = img; + update(); + }); + connect(player, &FFPlayer::emError, this, [this](QString err) { + QMessageBox::critical(this, "Video Error", err); + }); + player->open(path.toUtf8()); +} + +//void EleVideo::mouseDoubleClickEvent(QMouseEvent *) { +// qDebug()<<"img"<img; +// qDebug()<<"viCurTime"<viCurTime; +// qDebug()<<"viSize"<viSize; +//} +void EleVideo::showEvent(QShowEvent *) { + if(player) player->play(); +} +void EleVideo::hideEvent(QHideEvent *) { + if(player) player->stop(); +} + +void EleVideo::paintEvent(QPaintEvent *e) { + QWidget::paintEvent(e); + QPainter painter(this); + painter.drawImage(QRectF(0, 0, width(), height()), img); +} diff --git a/LedOK/player/elevideo.h b/LedOK/player/elevideo.h index 23fad59..638033d 100644 --- a/LedOK/player/elevideo.h +++ b/LedOK/player/elevideo.h @@ -1,20 +1,20 @@ -#ifndef ELEVIDEO_H -#define ELEVIDEO_H - -#include "ffplayer.h" -#include - -class EleVideo : public QWidget { - Q_OBJECT -public: - explicit EleVideo(QString path, QWidget *parent = nullptr); - ~EleVideo() {if(player!=0) player->quit(); } - FFPlayer *player = nullptr; - QImage img; -protected: - void paintEvent(QPaintEvent *) override; - void showEvent(QShowEvent *) override; - void hideEvent(QHideEvent *) override; -}; - -#endif // ELEVIDEO_H +#ifndef ELEVIDEO_H +#define ELEVIDEO_H + +#include "ffplayer.h" +#include + +class EleVideo : public QWidget { + Q_OBJECT +public: + explicit EleVideo(QString path, QWidget *parent = nullptr); + ~EleVideo() {if(player!=0) player->quit(); } + FFPlayer *player = nullptr; + QImage img; +protected: + void paintEvent(QPaintEvent *) override; + void showEvent(QShowEvent *) override; + void hideEvent(QHideEvent *) override; +}; + +#endif // ELEVIDEO_H diff --git a/LedOK/player/playwin.cpp b/LedOK/player/playwin.cpp index 4d6f77a..dfea6eb 100644 --- a/LedOK/player/playwin.cpp +++ b/LedOK/player/playwin.cpp @@ -1,228 +1,259 @@ -#include "playwin.h" -#include "digiclock.h" -#include "eleanaclock.h" -#include "eleborder.h" -#include "elegif.h" -#include "eleimg.h" -#include "elemultipng.h" -#include "elescroll.h" -#include "eletimer.h" -#include "elevideo.h" -#include "gqt.h" -#include "posdlg.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -PlayWin* PlayWin::self = nullptr; -QPoint gPlayPos{0, 0}; - -Page::Page(QWidget *parent) : QWidget{parent} { - -} - -PlayWin *PlayWin::newIns(int width, int height, QString dir, const QJsonObject &aprog, QWidget *parent) { - if(! gPlayPos.isNull() && QGuiApplication::screenAt(QPoint(gPlayPos.x()+width/2, gPlayPos.y()+height/2))==0) gPlayPos = QPoint(); - return new PlayWin(gPlayPos.x(), gPlayPos.y(), width, height, dir, aprog, parent); -} - -PlayWin::PlayWin(int x, int y, int width, int height, QString dir, const QJsonObject &aprog, QWidget *parent) : QWidget(parent) { - setAttribute(Qt::WA_DeleteOnClose); - setAttribute(Qt::WA_QuitOnClose, false); - setWindowFlag(Qt::FramelessWindowHint); - setWindowFlag(Qt::WindowStaysOnTopHint); - setGeometry(x, y, width, height); - QPalette plt = palette(); - plt.setColor(QPalette::Window, QColor(0,0,0)); - setPalette(plt); - connect(this, &PlayWin::sigSetVisible, this, &PlayWin::sltSetVisible); - - QJsonObject prog = aprog["task"].toObject(); - QJsonArray pageMaps = prog["items"].toArray(); - int pageCnt = pageMaps.size(); - EleBase ele; Page *page; - for(int p=0; psetGeometry(0, 0, width, height); - page->setVisible(false); - for(int ll=layers.size()-1; ll>=0; ll--) { - QJsonObject layer = layers[ll].toObject(); - QJsonArray srcMaps = layer["sources"].toArray(); - QJsonValue border = layer["border"]; - EleBorder *bdEle = nullptr; - int bdWidth = 0, startTime = 0xffff, endTime = 0; - if(! border.isNull()) { - bdEle = new EleBorder(dir+"/"+border["img"].toString(), border["eff"].toString(), border["speed"].toInt(), page); - bdWidth = bdEle->img.height(); - } - foreach(auto srcMap, srcMaps) { - ele.type = srcMap["_type"].toString(); - if(ele.type.isEmpty()) continue; - ele.timeSpan = srcMap["timeSpan"].toInt()*1000; - if(ele.timeSpan==0) continue; - ele.x = srcMap["left"].toInt()+bdWidth; - ele.y = srcMap["top"].toInt()+bdWidth; - ele.w = srcMap["width"].toInt()-bdWidth-bdWidth; - ele.h = srcMap["height"].toInt()-bdWidth-bdWidth; - bool notAudio = ele.type!="Audio"; - if((ele.w<=0 || ele.h<=0) && notAudio) continue; - ele.startTime = srcMap["playTime"].toInt()*1000; - if(startTime > ele.startTime) startTime = ele.startTime; - ele.endTime = ele.startTime + ele.timeSpan; - if(endTime < ele.endTime) endTime = ele.endTime; - if(ele.endTime > page->timeSpan && notAudio) page->timeSpan = ele.endTime; - ele.id = srcMap["id"].toString(); - ele.wgt = nullptr; - if(ele.type=="Image") { - if(srcMap["mime"].toString().endsWith("gif")) ele.wgt = new EleGif(dir+"/"+ele.id, page); - else ele.wgt = new EleImg(dir+"/"+ele.id, page); - } else if(ele.type.startsWith("Environ")) { - QJsonValue arrayPics = srcMap["arrayPics"]; - for(int i=arrayPics.toArray().size()-1; i>=0; i--) if(arrayPics[i]["name"].toString() == "previewTmp") { - if(srcMap["bSingleScroll"].toBool()) ele.wgt = new EleScroll(page, dir+"/" + arrayPics[i]["id"].toString(), 'l', srcMap["iScrollSpeed"].toDouble()); - else ele.wgt = new EleScroll(page, dir+"/"+arrayPics[i]["id"].toString()); - break; - } - } else if(ele.type=="MultiPng") { - QJsonArray imgs = srcMap["arrayPics"].toArray(); - if(imgs.isEmpty()) continue; - if(imgs.size()==1 && imgs.at(0)["picDuration"].toInt()==0) ele.wgt = new EleScroll(page, dir+"/", imgs[0].toObject()); - else ele.wgt = new EleMultiPng(dir+"/", imgs, page); - } else if(ele.type=="DigitalClockNew") ele.wgt = new DigiClock(dir+"/", srcMap.toObject(), page); - else if(ele.type=="AnalogClock") ele.wgt = new EleAnaClock(dir+"/"+ele.id, srcMap.toObject(), page); - else if(ele.type=="Video" || ele.type=="Audio") { - auto video = new EleVideo(dir+"/"+ele.id, page); - auto vol = srcMap["vol"].toInt(100); - if(vol<100) video->player->setVol(vol/100.0); - ele.wgt = video; - } else if(ele.type=="WebURL") { - auto web = new QWebEngineView(page); - web->load(QUrl(srcMap["url"].toString())); - ele.wgt = web; - } - else if(ele.type=="Timer") ele.wgt = new EleTimer(srcMap.toObject(), page); - else continue; - if(ele.wgt==nullptr) continue; - if(ele.startTime>0) ele.wgt->setVisible(false); - ele.wgt->setGeometry(ele.x, ele.y, ele.w, ele.h); - page->eles.append(ele); - } - if(bdEle!=nullptr && srcMaps.size()>0) { - QJsonArray geometry = border["geometry"].toArray(); - ele.x = geometry[0].toInt(); - ele.y = geometry[1].toInt(); - ele.w = geometry[2].toInt(); - ele.h = geometry[3].toInt(); - ele.startTime = startTime; - ele.endTime = endTime; - ele.timeSpan = endTime - startTime; - ele.wgt = bdEle; - if(ele.startTime>0) ele.wgt->setVisible(false); - ele.wgt->setGeometry(ele.x, ele.y, ele.w, ele.h); - page->eles.append(ele); - } - } - if(page->timeSpan>0) pages.append(page); - } - setVisible(true); - if(! pages.isEmpty()) { - Page* page0 = pages[0]; - EleBase* eleptr; - for(int ee=0; eeeles.size(); ee++) if((eleptr = &page0->eles[ee])->startTime > 0 || eleptr->endTime < page0->timeSpan) { - if(eleptr->startTime > 0) timerMap.insert(startTimer(eleptr->startTime), TimerValue(eleptr->wgt, true)); - timerMap.insert(startTimer(eleptr->endTime), TimerValue(eleptr->wgt, false)); - } - } - - menu = new QMenu(this); - auto act = menu->addAction(tr("Move to Top Left")); - connect(act, &QAction::triggered, this, [this] { - move(0,0); - }); - act = menu->addAction(tr("Set Position")); - connect(act, &QAction::triggered, this, [this] { - PosDlg dlg(this); - dlg.exec(); - }); - act = menu->addAction(tr("Close")); - connect(act, &QAction::triggered, this, [this] { - if(self==this) self = nullptr; - close(); - }); -} -void PlayWin::sltNext() { - if(isVisible()) { - pages[cur]->setVisible(false); - if(cur+2 > pages.size()) cur = 0; - else cur++; - Page* page = pages[cur]; - if(timer!=nullptr) timer->inter = page->timeSpan; - EleBase* ele; - for(int ee=0; eeeles.size(); ee++) if((ele = &page->eles[ee])->startTime > 0 || ele->endTime < page->timeSpan) { - if(ele->startTime > 0) timerMap.insert(startTimer(ele->startTime), TimerValue(ele->wgt, true)); - else ele->wgt->setVisible(true); - timerMap.insert(startTimer(ele->endTime), TimerValue(ele->wgt, false)); - } - page->setVisible(true); - } else if(timer!=nullptr) { - timer->stop(); - timer = nullptr; - } -} -void PlayWin::timerEvent(QTimerEvent *e){ - int id = e->timerId(); - killTimer(id); - TimerValue value = timerMap[id]; - if(value.ele!=nullptr){ - timerMap.remove(id); - value.ele->setVisible(value.visible); - } -} -void PlayWin::paintEvent(QPaintEvent *e){ - if(timer==nullptr && isVisible() && ! pages.isEmpty()) { - if(cur!=0) { - pages[cur]->setVisible(false); - cur = 0; - } - pages[cur]->setVisible(true); - timer = new SyncTimer(pages[cur]->timeSpan); - connect(timer, &SyncTimer::timeout, this, &PlayWin::sltNext, Qt::BlockingQueuedConnection); - timer->start(); - } - QWidget::paintEvent(e); -} - -void PlayWin::mousePressEvent(QMouseEvent *e) { - if(e->button() == Qt::LeftButton) { - mPressRel = pos() - e->globalPos(); - } -} -void PlayWin::mouseReleaseEvent(QMouseEvent *e) { - if(e->button() == Qt::LeftButton) mPressRel.setX(INT_MAX); -} -void PlayWin::mouseMoveEvent(QMouseEvent *e) { - if(e->buttons() & Qt::LeftButton) { - if(mPressRel.x()==INT_MAX) return; - move(mPressRel + e->globalPos()); - } -} -void PlayWin::leaveEvent(QEvent *) { - mPressRel.setX(INT_MAX); -} - -void PlayWin::contextMenuEvent(QContextMenuEvent *event){ - menu->exec(event->globalPos()); -} -void PlayWin::closeEvent(QCloseEvent *) { - if(self==this) self = nullptr; - gPlayPos = pos(); -} +#include "playwin.h" +#include "digiclock.h" +#include "eleanaclock.h" +#include "eleborder.h" +#include "elegif.h" +#include "eleimg.h" +#include "elemultipng.h" +#include "elescroll.h" +#include "eletimer.h" +#include "elevideo.h" +#include "gutil/qgui.h" +#include "posdlg.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +PlayWin* PlayWin::self = nullptr; +QPoint gPlayPos{0, 0}; + +Page::Page(QWidget *parent) : QWidget{parent} { + +} + +PlayWin *PlayWin::newIns(int width, int height, QString dir, const QJsonObject &aprog, QWidget *parent) { + if(! gPlayPos.isNull() && QGuiApplication::screenAt(QPoint(gPlayPos.x()+width/2, gPlayPos.y()+height/2))==0) gPlayPos = QPoint(); + return new PlayWin(gPlayPos.x(), gPlayPos.y(), width, height, dir, aprog, parent); +} + +PlayWin::PlayWin(int x, int y, int width, int height, QString dir, const QJsonObject &aprog, QWidget *parent) : QWidget(parent) { + setAttribute(Qt::WA_DeleteOnClose); + setAttribute(Qt::WA_QuitOnClose, false); + setWindowFlag(Qt::FramelessWindowHint); + setWindowFlag(Qt::WindowStaysOnTopHint); + setGeometry(x, y, width, height); + QPalette plt = palette(); + plt.setColor(QPalette::Window, QColor(0,0,0)); + setPalette(plt); + connect(this, &PlayWin::sigSetVisible, this, &PlayWin::sltSetVisible); + + const auto pageMaps = aprog["task"]["items"].toArray(); + int pageCnt = pageMaps.size(); + EleBase ele; Page *page; + for(int p=0; psetGeometry(0, 0, width, height); + page->setVisible(false); + for(int ll=layers.size()-1; ll>=0; ll--) { + QJsonObject layer = layers[ll].toObject(); + auto repeat = layer["repeat"].toBool(); + QJsonArray srcMaps = layer["sources"].toArray(); + QJsonValue border = layer["border"]; + EleBorder *bdEle = nullptr; + int bdWidth = 0, bdStart = 0xffff, bdEnd = 0; + if(! border.isNull()) { + bdEle = new EleBorder(dir+"/"+border["img"].toString(), border["eff"].toString(), border["speed"].toInt(), page); + bdWidth = bdEle->img.height(); + } + foreach(auto srcMap, srcMaps) { + ele.type = srcMap["_type"].toString(); + if(ele.type.isEmpty()) continue; + auto timeSpan = srcMap["timeSpan"].toInt()*1000; + if(timeSpan==0) continue; + ele.x = srcMap["left"].toInt()+bdWidth; + ele.y = srcMap["top"].toInt()+bdWidth; + ele.w = srcMap["width"].toInt()-bdWidth-bdWidth; + ele.h = srcMap["height"].toInt()-bdWidth-bdWidth; + bool notAudio = ele.type!="Audio"; + if((ele.w<=0 || ele.h<=0) && notAudio) continue; + ele.repeat = repeat; + ele.startTime = srcMap["playTime"].toInt()*1000; + if(bdStart > ele.startTime) bdStart = ele.startTime; + ele.endTime = ele.startTime + timeSpan; + if(bdEnd < ele.endTime) bdEnd = ele.endTime; + if(page->timeSpan < ele.endTime && notAudio) page->timeSpan = ele.endTime; + ele.id = srcMap["id"].toString(); + ele.wgt = 0; + if(ele.type=="Image") { + if(srcMap["mime"].toString().endsWith("gif")) ele.wgt = new EleGif(dir+"/"+ele.id, page); + else ele.wgt = new EleImg(dir+"/"+ele.id, page); + } else if(ele.type.startsWith("Environ")) { + QJsonValue arrayPics = srcMap["arrayPics"]; + for(int i=arrayPics.toArray().size()-1; i>=0; i--) if(arrayPics[i]["name"].toString() == "previewTmp") { + if(srcMap["bSingleScroll"].toBool()) ele.wgt = new EleScroll(page, dir+"/" + arrayPics[i]["id"].toString(), 'l', srcMap["iScrollSpeed"].toDouble()); + else ele.wgt = new EleScroll(page, dir+"/"+arrayPics[i]["id"].toString()); + break; + } + } else if(ele.type=="MultiPng") { + QJsonArray imgs = srcMap["arrayPics"].toArray(); + if(imgs.isEmpty()) continue; + if(imgs.size()==1 && imgs.at(0)["picDuration"].toInt()==0) ele.wgt = new EleScroll(page, dir+"/", imgs[0].toObject()); + else ele.wgt = new EleMultiPng(dir+"/", imgs, page); + } else if(ele.type=="SplitText") { + QJsonArray imgs = srcMap["arrayPics"].toArray(); + if(imgs.isEmpty()) continue; + ele.wgt = new QWidget(page); + ele.wgt->setGeometry(0, 0, width, height); + auto height = _program["height"].toInt(); + if(imgs.size()==1 && imgs.at(0)["picDuration"].toInt()==0) { + auto wgt = new EleScroll(ele.wgt, dir+"/", imgs[0].toObject()); + wgt->setGeometry(ele.x, ele.y, ele.w, ele.h); + for(int i=1; isetGeometry(ele.x, ele.y, splitWidths[i].toInt()-ele.x, ele.h); + wgt->splits.append(split); + } + } else { + auto wgt = new EleMultiPng(dir+"/", imgs, ele.wgt); + wgt->setGeometry(ele.x, ele.y, ele.w, ele.h); + for(int i=1; isetGeometry(ele.x, ele.y, splitWidths[i].toInt()-ele.x, ele.h); + wgt->splits.append(split); + } + } + ele.w = 0; + } else if(ele.type=="DigitalClockNew") ele.wgt = new DigiClock(dir+"/", srcMap.toObject(), page); + else if(ele.type=="AnalogClock") ele.wgt = new EleAnaClock(ele.w, ele.h, dir+"/"+ele.id, srcMap.toObject(), page); + else if(ele.type=="Video" || ele.type=="Audio") { + auto video = new EleVideo(dir+"/"+ele.id, page); + auto vol = srcMap["vol"].toInt(100); + if(vol<100) video->player->setVol(vol/100.0); + ele.wgt = video; + } else if(ele.type=="WebURL") { + auto web = new QWebEngineView(page); + web->load(QUrl(srcMap["url"].toString())); + ele.wgt = web; + } + else if(ele.type=="Timer") ele.wgt = new EleTimer(srcMap.toObject(), page); + else continue; + if(ele.wgt==0) continue; + if(ele.startTime>0) ele.wgt->setVisible(false); + if(ele.w) ele.wgt->setGeometry(ele.x, ele.y, ele.w, ele.h); + page->eles.append(ele); + } + if(bdEle && ! srcMaps.isEmpty()) { + QJsonArray geometry = border["geometry"].toArray(); + ele.x = geometry[0].toInt(); + ele.y = geometry[1].toInt(); + ele.w = geometry[2].toInt(); + ele.h = geometry[3].toInt(); + ele.startTime = bdStart; + ele.endTime = bdEnd; + ele.wgt = bdEle; + if(ele.startTime>0) ele.wgt->setVisible(false); + ele.wgt->setGeometry(ele.x, ele.y, ele.w, ele.h); + page->eles.append(ele); + } + } + if(page->timeSpan==0) continue; + for(int i=0; ieles.size(); i++) if(page->eles[i].repeat) page->eles[i].endTime = page->timeSpan; + pages.append(page); + } + setVisible(true); + if(! pages.isEmpty()) { + Page* page0 = pages[0]; + EleBase* eleptr; + for(int ee=0; eeeles.size(); ee++) if((eleptr = &page0->eles[ee])->startTime > 0 || eleptr->endTime < page0->timeSpan) { + if(eleptr->startTime > 0) timerMap.insert(startTimer(eleptr->startTime), TimerValue(eleptr->wgt, true)); + timerMap.insert(startTimer(eleptr->endTime), TimerValue(eleptr->wgt, false)); + } + } + + menu = new QMenu(this); + auto act = menu->addAction(tr("Move to Top Left")); + connect(act, &QAction::triggered, this, [this] { + move(0,0); + }); + act = menu->addAction(tr("Set Position")); + connect(act, &QAction::triggered, this, [this] { + PosDlg dlg(this); + dlg.exec(); + }); + act = menu->addAction(tr("Close")); + connect(act, &QAction::triggered, this, [this] { + if(self==this) self = nullptr; + close(); + }); +} +void PlayWin::sltNext() { + if(isVisible()) { + pages[cur]->setVisible(false); + if(cur+2 > pages.size()) cur = 0; + else cur++; + Page* page = pages[cur]; + if(timer) timer->inter = page->timeSpan; + EleBase* ele; + for(int ee=0; eeeles.size(); ee++) if((ele = &page->eles[ee])->startTime > 0 || ele->endTime < page->timeSpan) { + if(ele->startTime > 0) timerMap.insert(startTimer(ele->startTime), TimerValue(ele->wgt, true)); + else ele->wgt->setVisible(true); + timerMap.insert(startTimer(ele->endTime), TimerValue(ele->wgt, false)); + } + page->setVisible(true); + } else if(timer) { + timer->stop(); + timer = 0; + } +} +void PlayWin::timerEvent(QTimerEvent *e){ + int id = e->timerId(); + killTimer(id); + TimerValue value = timerMap[id]; + if(value.ele) { + timerMap.remove(id); + value.ele->setVisible(value.visible); + } +} +void PlayWin::paintEvent(QPaintEvent *e){ + if(timer==0 && isVisible() && ! pages.isEmpty()) { + if(cur!=0) { + pages[cur]->setVisible(false); + cur = 0; + } + pages[cur]->setVisible(true); + timer = new SyncTimer(pages[cur]->timeSpan); + connect(timer, &SyncTimer::timeout, this, &PlayWin::sltNext, Qt::BlockingQueuedConnection); + timer->start(); + } + QWidget::paintEvent(e); +} + +void PlayWin::mousePressEvent(QMouseEvent *e) { + if(e->button() == Qt::LeftButton) { + mPressRel = pos() - e->globalPos(); + } +} +void PlayWin::mouseReleaseEvent(QMouseEvent *e) { + if(e->button() == Qt::LeftButton) mPressRel.setX(INT_MAX); +} +void PlayWin::mouseMoveEvent(QMouseEvent *e) { + if(e->buttons() & Qt::LeftButton) { + if(mPressRel.x()==INT_MAX) return; + move(mPressRel + e->globalPos()); + } +} +void PlayWin::leaveEvent(QEvent *) { + mPressRel.setX(INT_MAX); +} + +void PlayWin::contextMenuEvent(QContextMenuEvent *event){ + menu->exec(event->globalPos()); +} +void PlayWin::closeEvent(QCloseEvent *) { + if(self==this) self = nullptr; + gPlayPos = pos(); +} diff --git a/LedOK/player/playwin.h b/LedOK/player/playwin.h index 9caa8f1..01296bf 100644 --- a/LedOK/player/playwin.h +++ b/LedOK/player/playwin.h @@ -1,56 +1,56 @@ -#ifndef PLAYWIN_H -#define PLAYWIN_H -#include "elebase.h" -#include "synctimer.h" -#include -#include -#include -#include - -class Page : public QWidget { -public: - explicit Page(QWidget *parent = nullptr); - int timeSpan = 0; - QVector eles; -}; - -class TimerValue{ -public: - TimerValue(QWidget *ele = nullptr, bool visible = false): ele(ele), visible(visible){} - QWidget* ele; - bool visible; -}; - -class PlayWin : public QWidget { - Q_OBJECT -public: - static PlayWin *self; - static PlayWin *newIns(int width, int height, QString dir, const QJsonObject &prog, QWidget *parent = nullptr); - PlayWin(int x, int y, int width, int height, QString dir, const QJsonObject &prog, QWidget *parent = nullptr); - - SyncTimer* timer = nullptr; - int cur = 0; - QVector pages; - QMap timerMap; - QPoint mPressRel; - QMenu *menu; - -public slots: - void sltNext(); - void sltSetVisible(QWidget *wgt, bool visible){ - wgt->setVisible(visible); - } -signals: - void sigSetVisible(QWidget *, bool); -protected: - void paintEvent(QPaintEvent *) override; - void timerEvent(QTimerEvent *) override; - void mousePressEvent(QMouseEvent *) override; - void mouseReleaseEvent(QMouseEvent *) override; - void mouseMoveEvent(QMouseEvent *) override; - void leaveEvent(QEvent *) override; - void contextMenuEvent(QContextMenuEvent *) override; - void closeEvent(QCloseEvent *) override; -}; - -#endif // PLAYWIN_H +#ifndef PLAYWIN_H +#define PLAYWIN_H +#include "elebase.h" +#include "synctimer.h" +#include +#include +#include +#include + +class Page : public QWidget { +public: + explicit Page(QWidget *parent = nullptr); + int timeSpan{0}; + QVector eles; +}; + +class TimerValue{ +public: + TimerValue(QWidget *ele = nullptr, bool visible = false): ele(ele), visible(visible){} + QWidget* ele; + bool visible; +}; + +class PlayWin : public QWidget { + Q_OBJECT +public: + static PlayWin *self; + static PlayWin *newIns(int width, int height, QString dir, const QJsonObject &prog, QWidget *parent = nullptr); + PlayWin(int x, int y, int width, int height, QString dir, const QJsonObject &prog, QWidget *parent = nullptr); + + SyncTimer* timer = 0; + int cur = 0; + QVector pages; + QMap timerMap; + QPoint mPressRel; + QMenu *menu; + +public slots: + void sltNext(); + void sltSetVisible(QWidget *wgt, bool visible){ + wgt->setVisible(visible); + } +signals: + void sigSetVisible(QWidget *, bool); +protected: + void paintEvent(QPaintEvent *) override; + void timerEvent(QTimerEvent *) override; + void mousePressEvent(QMouseEvent *) override; + void mouseReleaseEvent(QMouseEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void leaveEvent(QEvent *) override; + void contextMenuEvent(QContextMenuEvent *) override; + void closeEvent(QCloseEvent *) override; +}; + +#endif // PLAYWIN_H diff --git a/LedOK/player/posdlg.cpp b/LedOK/player/posdlg.cpp index 38f3e1b..c083ee0 100644 --- a/LedOK/player/posdlg.cpp +++ b/LedOK/player/posdlg.cpp @@ -1,43 +1,43 @@ -#include "posdlg.h" -#include -#include -#include -#include - -PosDlg::PosDlg(QWidget *parent) : QDialog{parent} { - setWindowTitle(tr("Set Position")); - setWindowFlag(Qt::WindowContextHelpButtonHint, false); - - auto vBox = new QVBoxLayout(this); - auto hBox = new QHBoxLayout(); - hBox->addStretch(); - hBox->addWidget(new QLabel("X")); - auto fdX = new QLineEdit(QString::number(parent->x())); - fdX->setMaximumWidth(80); - hBox->addWidget(fdX); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - hBox->addWidget(new QLabel("Y")); - auto fdY = new QLineEdit(QString::number(parent->y())); - fdY->setMaximumWidth(80); - hBox->addWidget(fdY); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - - auto btnOk = new QPushButton(tr("OK")); - connect(btnOk, &QPushButton::clicked, this, [parent, fdX, fdY] { - parent->move(fdX->text().toInt(), fdY->text().toInt()); - }); - hBox->addWidget(btnOk); - hBox->addStretch(); - - vBox->addLayout(hBox); -} +#include "posdlg.h" +#include +#include +#include +#include + +PosDlg::PosDlg(QWidget *parent) : QDialog{parent} { + setWindowTitle(tr("Set Position")); + setWindowFlag(Qt::WindowContextHelpButtonHint, false); + + auto vBox = new QVBoxLayout(this); + auto hBox = new QHBoxLayout(); + hBox->addStretch(); + hBox->addWidget(new QLabel("X")); + auto fdX = new QLineEdit(QString::number(parent->x())); + fdX->setMaximumWidth(80); + hBox->addWidget(fdX); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + hBox->addStretch(); + hBox->addWidget(new QLabel("Y")); + auto fdY = new QLineEdit(QString::number(parent->y())); + fdY->setMaximumWidth(80); + hBox->addWidget(fdY); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + hBox->addStretch(); + + auto btnOk = new QPushButton(tr("OK")); + connect(btnOk, &QPushButton::clicked, this, [parent, fdX, fdY] { + parent->move(fdX->text().toInt(), fdY->text().toInt()); + }); + hBox->addWidget(btnOk); + hBox->addStretch(); + + vBox->addLayout(hBox); +} diff --git a/LedOK/player/posdlg.h b/LedOK/player/posdlg.h index 2940168..f7bc7a5 100644 --- a/LedOK/player/posdlg.h +++ b/LedOK/player/posdlg.h @@ -1,13 +1,13 @@ -#ifndef POSDLG_H -#define POSDLG_H - -#include - -class PosDlg : public QDialog { - Q_OBJECT -public: - explicit PosDlg(QWidget *parent = nullptr); - -}; - -#endif // POSDLG_H +#ifndef POSDLG_H +#define POSDLG_H + +#include + +class PosDlg : public QDialog { + Q_OBJECT +public: + explicit PosDlg(QWidget *parent = nullptr); + +}; + +#endif // POSDLG_H diff --git a/LedOK/progpanel.cpp b/LedOK/progpanel.cpp index 0025b93..541fd9a 100644 --- a/LedOK/progpanel.cpp +++ b/LedOK/progpanel.cpp @@ -1,12 +1,17 @@ #include "progpanel.h" #include "globaldefine.h" #include "tools.h" +#include "gutil/qgui.h" +#include "cfg.h" #include "player/playwin.h" -#include "tipdialog.h" +#include "program/progcreatedlg.h" +#include "program/progeditorwin.h" +#include "program/copydirthread.h" #include #include #include -#include +#include +#include ProgPanel::ProgPanel(QSettings &settings, QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_DeleteOnClose); @@ -28,10 +33,27 @@ ProgPanel::ProgPanel(QSettings &settings, QWidget *parent) : QWidget(parent) { bnNew->setProperty("ssType", "progManageTool"); hBox->addWidget(bnNew); connect(bnNew, &QPushButton::clicked, this, [this] { - ProgCreateDlg dlg(QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"), 512, 512, "", this); + ProgCreateDlg dlg("", 512, 256, "", "", this); if(dlg.exec() != QDialog::Accepted) return; if(checkIfNameRepeated(dlg.fdName->text())) return; - auto item = new ProgItem(mProgsDir, dlg.fdName->text(), dlg.fdWidth->value(), dlg.fdHeight->value(), dlg.fdRemark->toPlainText(), dlg.fdSplitWidth->value(), mProgTree, this); + auto splitWidths = dlg.fdSplitWidths->text().split(" ", Qt::SkipEmptyParts); + QList widths; int max = 0, ttl = 0; + foreach(auto splitWidth, splitWidths) { + int val = splitWidth.toInt(); + if(val==0) continue; + if(max < val) max = val; + ttl += val; + widths.append(val); + } + auto width = dlg.fdWidth->value(); + if(max) { + while(ttl < width) { + widths.append(max); + ttl += max; + } + if(ttl > width) widths.last() -= ttl - width; + } + auto item = new ProgItem(mProgsDir, dlg.fdName->text(), width, dlg.fdHeight->value(), dlg.fdRemark->toPlainText(), widths, max, mProgTree, this); item->save();//保存pro.json mProgTree->adjustCheckState(); auto editor = new ProgEditorWin(item, gMainWin); @@ -53,13 +75,60 @@ ProgPanel::ProgPanel(QSettings &settings, QWidget *parent) : QWidget(parent) { connect(bnDelete, SIGNAL(clicked(bool)), this, SLOT(onDeleteClicked(bool))); bnImport = new QPushButton(tr("Import")); - bnImport->setFixedSize(QSize(88, 38)); + bnImport->setFixedSize(88, 38); bnImport->setProperty("ssType", "progManageTool"); hBox->addWidget(bnImport); connect(bnImport, &QPushButton::clicked, this, [this] { - auto dlg = new TipDialog(this, ENUM_IMPORT_DLG); - connect(dlg, SIGNAL(sigAcceptData(QString,QString)), this, SLOT(onImportProgram(QString,QString))); - dlg->exec(); + QString dir = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + if(dir.isEmpty()) return; + QString progsDir = programsDir(); + if(dir.contains(progsDir, Qt::CaseInsensitive)) { + QMessageBox::warning(this, tr("Tip"), tr("The imported directory is already in the working directory, so there is no need to import it again!")); + return; + } + QStringList progDirs; + if(QFileInfo::exists(dir + "/pro.json")) progDirs.append(dir); + else { + QStringList subdirNames = QDir(dir).entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); + foreach(QString subdirName, subdirNames) { + auto subdir = dir + "/" + subdirName; + if(! QFileInfo::exists(subdir + "/pro.json")) continue; + if(QFileInfo::exists(progsDir + "/" + subdirName)) { + auto res = QMessageBox::information(gMainWin, tr("Tip Info"), subdirName + tr(":solution(s) already exist.are you sure you want to overwrite the existing solution(s)?"), QMessageBox::Yes, QMessageBox::No); + if(res == QMessageBox::No) continue; + } + progDirs.append(subdir); + } + if(progDirs.isEmpty()) return; + } + ProgPortDlg dlg(this, tr("Import")); + dlg.table->setRowCount(progDirs.count()); + for(int i=0; isetItem(i, 0, new QTableWidgetItem(QFileInfo(progDirs[i]).fileName())); + dlg.table->setCellWidget(i, 1, new QProgressBar); + } + connect(dlg.bnOK, &QPushButton::clicked, this, [=, &dlg] { + for(int i=0; icellWidget(i, 1))->setMaximum(dirFileSize(progDirs[i])); + auto thread = new CopyDirThread(); + thread->dirSrcs = progDirs; + thread->dirDst = progsDir; + connect(thread, &CopyDirThread::sigProgress, &dlg, [&dlg](int i, int value) { + ((QProgressBar*)dlg.table->cellWidget(i, 1))->setValue(value); + }); + thread->start(); + }); + dlg.exec(); + + mProgTree->clear(); + QStringList progNames = QDir(mProgsDir).entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); + foreach(QString pro_name, progNames) { + QFile jFile(mProgsDir + "/" + pro_name + "/pro.json"); + if(! jFile.exists()) continue; + if(! jFile.open(QIODevice::ReadOnly)) continue; + auto data = jFile.readAll(); + jFile.close(); + m_pwPorgramItemList.append(new ProgItem(mProgsDir, QJsonDocument::fromJson(data).object(), mProgTree,this)); + } }); bnExport = new QPushButton(tr("Export")); @@ -67,7 +136,36 @@ ProgPanel::ProgPanel(QSettings &settings, QWidget *parent) : QWidget(parent) { bnExport->setEnabled(false); bnExport->setProperty("ssType", "progManageTool"); hBox->addWidget(bnExport); - connect(bnExport, SIGNAL(clicked(bool)), this, SLOT(onExportClicked(bool))); + connect(bnExport, &QPushButton::clicked, this, [=] { + int cnt = mProgTree->topLevelItemCount(); + QStringList progNames; + for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) progNames.append(static_cast(mProgTree->topLevelItem(i))->mName); + if(progNames.isEmpty()) return; + + ProgPortDlg dlg(this, tr("Export")); + dlg.table->setRowCount(progNames.count()); + for(int i=0; isetItem(i, 0, new QTableWidgetItem(progNames[i])); + dlg.table->setCellWidget(i, 1, new QProgressBar); + } + connect(dlg.bnOK, &QPushButton::clicked, this, [=, &dlg] { + QString dirDst = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + if(dirDst.isEmpty()) return; + auto progsDir = programsDir(); + auto thread = new CopyDirThread(); + for(int i=0; icellWidget(i, 1))->setMaximum(dirFileSize(dir)); + thread->dirSrcs.append(dir); + } + thread->dirDst = dirDst; + connect(thread, &CopyDirThread::sigProgress, &dlg, [&dlg](int i, int value) { + ((QProgressBar*)dlg.table->cellWidget(i, 1))->setValue(value); + }); + thread->start(); + }); + dlg.exec(); + }); bnSend = new QPushButton(tr("Send")); bnSend->setFixedSize(QSize(88, 38)); @@ -95,11 +193,8 @@ ProgPanel::ProgPanel(QSettings &settings, QWidget *parent) : QWidget(parent) { QJsonObject prog = QJsonDocument::fromJson(value.toUtf8(), &jsErr).object(); if(jsErr.error) return; if(PlayWin::self!=nullptr) PlayWin::self->close(); - if(item->mSplitWidth==0) PlayWin::self = PlayWin::newIns(item->mWidth, item->mHeight, dir, prog); - else { - int cnt = (item->mWidth+item->mSplitWidth-1) / item->mSplitWidth; - PlayWin::self = PlayWin::newIns(item->mSplitWidth, item->mHeight*cnt, dir, prog); - } + if(item->mSplitWidths.isEmpty()) PlayWin::self = PlayWin::newIns(item->mWidth, item->mHeight, dir, prog); + else PlayWin::self = PlayWin::newIns(item->mMaxWidth, item->mHeight * item->mSplitWidths.size(), dir, prog); break; } } @@ -111,7 +206,7 @@ ProgPanel::ProgPanel(QSettings &settings, QWidget *parent) : QWidget(parent) { auto txtSearch = new QLineEdit(this); txtSearch->setFixedSize(QSize(240, 36)); QAction *search = new QAction(txtSearch); - search->setIcon(QIcon(":/res/ProgramManager/bnSearch.png")); + search->setIcon(QIcon(":/res/program/bnSearch.png")); txtSearch->addAction(search, QLineEdit::LeadingPosition); txtSearch->setClearButtonEnabled(true); txtSearch->setStyleSheet("border: 2px solid #aaaaaa;"); @@ -252,10 +347,10 @@ bool ProgPanel::checkIfNameRepeated(const QString &name, QTreeWidgetItem *skip){ } return false; } -void ProgPanel::onCreateNewProgramOnOpenEditProgramWidget(QString name, QSize res, QString remarks, int sp) +void ProgPanel::onCreateNewProgramOnOpenEditProgramWidget(QString name, QSize res, QString remarks, QList &splitWidths, int max) { if(checkIfNameRepeated(name)) return; - auto item = new ProgItem(mProgsDir, name, res.width(), res.height(), remarks, sp, mProgTree, this); + auto item = new ProgItem(mProgsDir, name, res.width(), res.height(), remarks, splitWidths, max, mProgTree, this); item->save();//保存pro.json mProgTree->adjustCheckState(); auto editor = new ProgEditorWin(item, gMainWin); @@ -281,40 +376,6 @@ void ProgPanel::onDeleteClicked(bool){ } } -void ProgPanel::onImportProgram(QString strImportDir, QString){ - if(!strImportDir.isEmpty()){ - mProgTree->clear(); - //查找根路径下的项目文件夹,查找文件夹下的节目pro.json信息,包括节目名称,大小,像素,备注等信息 - if(!mProgsDir.isEmpty()) { - QDir root_dir(mProgsDir); - QStringList pro_list = root_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); - foreach(QString pro_name, pro_list) { - QDir pro_dir(mProgsDir + MACRO_FENGEFU + pro_name); - if(pro_dir.exists("pro.json")) { - QFile fPro(pro_dir.path() + MACRO_FENGEFU+"pro.json"); - fPro.open(QIODevice::ReadOnly); - QJsonDocument pro = QJsonDocument::fromJson(fPro.readAll()); - fPro.close(); - m_pwPorgramItemList.append(new ProgItem(mProgsDir, pro.object(), mProgTree,this)); - } - } - } - } -} - -void ProgPanel::onExportClicked(bool){ - int cnt = mProgTree->topLevelItemCount(); - QStringList selectProgramlist; - for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) { - QString string =static_cast(mProgTree->topLevelItem(i))->m_bnName->text(); - selectProgramlist.append(string); - } - } - TipDialog *dlg = new TipDialog(this,ENUM_EXPORT_DLG,&selectProgramlist,0); - dlg->exec(); -} - void ProgPanel::FilterProgram(const QString &strtemp){ if (strtemp.isEmpty()) //显示全部 { @@ -358,3 +419,47 @@ void ProgPanel::FilterProgram(const QString &strtemp){ } +ProgPortDlg::ProgPortDlg(QWidget *parent, QString title) : BaseDlg(parent) { + resize(600, 400); + + auto vBox = new VBox(this); + auto hBox = new HBox(vBox); + hBox->setContentsMargins(0, 0, 0, 0); + hBox->addStretch(); + + auto fdTitle = new QLabel(title); + fdTitle->setStyleSheet("QLabel{font-size:16px;}"); + hBox->addWidget(fdTitle); + hBox->addStretch(); + + bnClose = new QPushButton("X"); + bnClose->setFixedSize(30, 24); + connect(bnClose, &QPushButton::clicked, this, &BaseDlg::close); + hBox->addWidget(bnClose); + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + vBox->addWidget(line); + + + table = new QTableWidget(0, 2); + table->setSelectionMode(QTableWidget::NoSelection); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setAlternatingRowColors(true); + table->horizontalHeader()->setBackgroundRole(QPalette::Window); + table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); + table->horizontalHeader()->resizeSection(1, 200); + table->setHorizontalHeaderLabels({tr("Solution Name"), tr("Progress")}); + vBox->addWidget(table); + + hBox = new HBox(vBox); + hBox->addStretch(); + + bnOK = new QPushButton(title); + hBox->addWidget(bnOK); + + auto bnDone = new QPushButton(tr("Done")); + connect(bnDone, &QPushButton::clicked, this, &BaseDlg::accept); + hBox->addWidget(bnDone); +} diff --git a/LedOK/progpanel.h b/LedOK/progpanel.h index 3ba4116..52d1b24 100644 --- a/LedOK/progpanel.h +++ b/LedOK/progpanel.h @@ -1,31 +1,12 @@ #ifndef PROGPANEL_H #define PROGPANEL_H -#include -#include -#include -#include -#include -#include -#include +#include "base/loqtreewidget.h" +#include "program/progitem.h" +#include "basedlg.h" #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include - -#include "cfg.h" -#include -#include -#include -#include "wProgramManager/progitem.h" +#include class ProgPanel : public QWidget { Q_OBJECT @@ -42,9 +23,7 @@ protected: public slots: void onEditClicked(bool f); void onDeleteClicked(bool f); - void onExportClicked(bool f); - void onCreateNewProgramOnOpenEditProgramWidget(QString name, QSize res, QString remarks, int); - void onImportProgram(QString strImportDir,QString strTip1); + void onCreateNewProgramOnOpenEditProgramWidget(QString name, QSize res, QString remarks, QList &, int); void FilterProgram(const QString &strtemp); private slots: @@ -60,4 +39,13 @@ private: QPushButton *bnSend, *btnPlay; }; +class ProgPortDlg : public BaseDlg { + Q_OBJECT +public: + ProgPortDlg(QWidget *parent, QString title); + + QTableWidget *table{0}; + QPushButton *bnOK, *bnClose; +}; + #endif // PROGPANEL_H diff --git a/LedOK/program/copydirthread.cpp b/LedOK/program/copydirthread.cpp new file mode 100644 index 0000000..ad308a0 --- /dev/null +++ b/LedOK/program/copydirthread.cpp @@ -0,0 +1,32 @@ +#include "copydirthread.h" +#include + +CopyDirThread::CopyDirThread() { + connect(this, &CopyDirThread::finished, this, &CopyDirThread::deleteLater); +} + +void CopyDirThread::run() { + for(; i + +class CopyDirThread : public QThread { + Q_OBJECT +public: + CopyDirThread(); + QStringList dirSrcs; + QString dirDst; +protected: + void run(); + bool copyDir(const QString &fromDir, const QString &toDir, bool coverFileIfExist); + + int i{0}; + int copiedSize = 0; +signals: + void sigProgress(int, int); +}; +#endif // COPYDIRTHREAD_H diff --git a/LedOK/wProgramManager/eaclock.cpp b/LedOK/program/eaclock.cpp similarity index 63% rename from LedOK/wProgramManager/eaclock.cpp rename to LedOK/program/eaclock.cpp index 14718cc..413e2e2 100644 --- a/LedOK/wProgramManager/eaclock.cpp +++ b/LedOK/program/eaclock.cpp @@ -1,39 +1,34 @@ #include "eaclock.h" #include "cfg.h" #include "globaldefine.h" +#include "gutil/qgui.h" #include "tools.h" +#include "base/locolorselector.h" +#include #include #include #include #include -#include +#include +#include +#include -eAClock::eAClock(EBase *multiWin) : EBase(multiWin) { +EAClock::EAClock(EBase *multiWin) : EBase(multiWin) { mType = EBase::AClock; - m_attr.timeZoneId = QTimeZone::systemTimeZoneId(); - m_attr.hourMark = 0; - m_attr.hourMarkSize = 5; - m_attr.hourMarkColor = Qt::green; - m_attr.minMark = 1; - m_attr.minMarkSize = 2; - m_attr.minMarkColor = Qt::yellow; - m_attr.hourHandColor = Qt::yellow; - m_attr.minHandColor = Qt::green; - m_attr.secHandColor = Qt::red; - m_attr.textFont = QFont("Arial", 9); - m_attr.textColor = Qt::red; - m_attr.playDuration = 10; - m_attr.hasDialImg = false; - init(); + m_attr.timeZone = QTimeZone::systemTimeZone(); + m_attr.hourHandColor = Qt::yellow; + m_attr.minHandColor = Qt::green; + m_attr.secHandColor = Qt::red; + m_attr.textColor = Qt::red; } -eAClock::eAClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { +EAClock::EAClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { mType = EBase::AClock; setBaseAttr(json); auto widget = json["widget"]; - m_attr.timeZoneId = QByteArray().append(widget["timeZone"].toString().toUtf8()); - m_attr.hourMark = widget["hourMark"].toInt(); - m_attr.hourMarkSize = widget["hourMarkSize"].toInt(); + m_attr.timeZone = QTimeZone(widget["timeZone"].toString().toUtf8()); + m_attr.hourMark = widget["hourMark"].toInt(); + m_attr.hourMarkSize = widget["hourMarkSize"].toInt(); auto color = widget["hourMarkColor"]; m_attr.hourMarkColor = color.isString() ? QColor(color.toString()) : Tools::int2Color(color.toInt()); m_attr.minMark = widget["minMark"].toInt(); @@ -53,6 +48,13 @@ eAClock::eAClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { m_attr.textFont.setBold(widget["textFontBold"].toBool()); m_attr.textFont.setItalic(widget["textFontItalics"].toBool()); m_attr.textFont.setUnderline(widget["textFontUnderline"].toBool()); + m_attr.hhLen = widget["hhLen"].toInt(m_attr.hhLen); + m_attr.mhLen = widget["mhLen"].toInt(m_attr.mhLen); + m_attr.shLen = widget["shLen"].toInt(m_attr.shLen); + m_attr.hhWidth = widget["hhWidth"].toInt(m_attr.hhWidth); + m_attr.mhWidth = widget["mhWidth"].toInt(m_attr.mhWidth); + m_attr.shWidth = widget["shWidth"].toInt(m_attr.shWidth); + m_attr.showSecHand = widget["showSecHand"].toBool(true); m_attr.playDuration = json["play"]["duration"].toInt(); m_attr.path = widget["path"].toString(); m_attr.name = widget["name"].toString(); @@ -61,27 +63,24 @@ eAClock::eAClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { if(! m_attr.hasDialImg) m_attr.selfCreateDialName = QString("%1%2%3%4%5.png").arg((int)zValue()).arg((int)x()).arg((int)y()).arg((int)mWidth).arg((int)mHeight); else dial_img.load(m_attr.path+"/"+m_attr.name); - init(); } -void eAClock::init() { - connect(Tools::getInstance(), &Tools::sTick, this, [this]() { - time = QDateTime::currentDateTime().toTimeZone(QTimeZone(m_attr.timeZoneId)).time(); +void EAClock::timerEvent(QTimerEvent *) { + if(isVisible()) { + cal(); update(); - }); + } else if(timerId) { + killTimer(timerId); + timerId = 0; + } } - -qreal eAClock::radiusHour() const { - qreal r = (rect().width() < rect().height() ? rect().width() : rect().height()) / 2; - return r - m_attr.hourMarkSize / 2; +void EAClock::cal() { + auto time = QDateTime::currentDateTime().toTimeZone(m_attr.timeZone).time(); + sAngle = time.second() * 6; + mAngle = time.minute() * 6 + sAngle/60; + hAngle = time.hour() * 30 + mAngle/12; } - -qreal eAClock::radiusMin() const { - qreal r = (rect().width() < rect().height() ? rect().width() : rect().height()) / 2; - return r - m_attr.minMarkSize / 2; -} - -void eAClock::paintDial(QPainter *painter) { +void EAClock::paintDial(QPainter *painter) { if(! m_attr.hasDialImg || dial_img.isNull()) { auto inner = innerRect(); qreal r = radius(); @@ -150,7 +149,7 @@ void eAClock::paintDial(QPainter *painter) { } } -void eAClock::drawMarkCircular(QPainter *painter, const QPointF &pos, const QColor &color, qreal diameter) { +void EAClock::drawMarkCircular(QPainter *painter, const QPointF &pos, const QColor &color, qreal diameter) { QPointF cp(pos.x(), pos.y()); qreal r = diameter / 2; painter->save(); @@ -161,7 +160,7 @@ void eAClock::drawMarkCircular(QPainter *painter, const QPointF &pos, const QCol painter->restore(); } -void eAClock::drawMarkRectangle(QPainter *painter, const QPointF &pos, const QColor &color, qreal len, qreal angle) +void EAClock::drawMarkRectangle(QPainter *painter, const QPointF &pos, const QColor &color, qreal len, qreal angle) { QPointF cp(pos.x(), pos.y()); QRectF rect(-len/2, -len/2, len, len); @@ -175,7 +174,7 @@ void eAClock::drawMarkRectangle(QPainter *painter, const QPointF &pos, const QCo painter->restore(); } -void eAClock::drawMarkNumber(QPainter *painter, const QPointF &pos, const QColor &color, qreal len, int num) +void EAClock::drawMarkNumber(QPainter *painter, const QPointF &pos, const QColor &color, qreal len, int num) { QRectF rect(pos.x()-len/2, pos.y()-len/2, len, len); QFont font("Arial"); @@ -192,61 +191,72 @@ void eAClock::drawMarkNumber(QPainter *painter, const QPointF &pos, const QColor painter->restore(); } -void eAClock::drawHand(QPainter *painter, qreal angle, const QColor &color, qreal len, qreal base) { - auto inner = innerRect(); - qreal cx = inner.width() / 2; - qreal cy = inner.height() / 2; - QPointF points[3] = { - QPointF(-base, 0), - QPointF( base, 0), - QPointF( 0, -len), - }; - painter->save(); - painter->setBrush(color); - painter->setPen(color); - painter->translate(cx, cy); - painter->rotate(angle); - painter->setRenderHint(QPainter::Antialiasing); - painter->drawPolygon(points, 3); - painter->restore(); -} - -void eAClock::paintText(QPainter *painter){ +void EAClock::paintText(QPainter *painter){ if(m_attr.text.isNull() || m_attr.text.isEmpty()) return; - QRectF r(0, rect().height()/6, rect().width(), rect().height()/4); - QTextOption opt; - opt.setAlignment(Qt::AlignCenter); - painter->save(); + auto inner = innerRect(); painter->setPen(m_attr.textColor); m_attr.textFont.setStyleStrategy(gTextAntialiasing ? QFont::PreferAntialias : QFont::NoAntialias); painter->setFont(m_attr.textFont); - painter->drawText(r, m_attr.text, opt); - painter->restore(); + painter->drawText(QRectF(0, inner.height()/6, inner.width(), inner.height()/4), m_attr.text, QTextOption(Qt::AlignCenter)); } -void eAClock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { +void EAClock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { + if(timerId==0) { + timerId = startTimer(500, Qt::PreciseTimer); + cal(); + } painter->save(); + painter->setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); auto inner = innerRect(); + auto sideLen = qMin(inner.width(), inner.height()); + auto lineWidth = sideLen/128; + if(lineWidth < 1) lineWidth = 1; painter->translate(inner.x(), inner.y()); paintDial(painter); paintText(painter); - drawHand(painter, time.hour() * 30.0, m_attr.hourHandColor, radius()/2, radius() / 20); - drawHand(painter, time.minute() * 6.0, m_attr.minHandColor, radius()*3/4, radius() / 30); - drawHand(painter, time.second() * 6.0, m_attr.secHandColor, radius(), radius() / 40); + painter->translate(inner.width() / 2, inner.height() / 2); + + QPen pen(m_attr.hourHandColor, lineWidth); + pen.setJoinStyle(Qt::RoundJoin); + painter->setPen(pen); + painter->setBrush(pen.brush()); + painter->rotate(hAngle); + QPointF poses[3]{{m_attr.hhWidth*sideLen/400, 0}, {0, m_attr.hhLen*sideLen/-200}}; + poses[2].rx() = -poses[0].rx(); + painter->drawPolygon(poses, 3); + + pen.setColor(m_attr.minHandColor); + painter->setPen(pen); + painter->setBrush(pen.brush()); + painter->rotate(mAngle-hAngle); + poses[0].rx() = m_attr.mhWidth*sideLen/400; + poses[1].ry() = m_attr.mhLen*sideLen/-200; + poses[2].rx() = -poses[0].rx(); + painter->drawPolygon(poses, 3); + if(m_attr.showSecHand) { + pen.setColor(m_attr.secHandColor); + painter->setPen(pen); + painter->setBrush(pen.brush()); + painter->rotate(sAngle-mAngle); + poses[0].rx() = m_attr.shWidth*sideLen/400; + poses[1].ry() = m_attr.shLen*sideLen/-200; + poses[2].rx() = -poses[0].rx(); + painter->drawPolygon(poses, 3); + } painter->restore(); EBase::paint(painter, option, widget); } -QWidget* eAClock::attrWgt() { +QWidget* EAClock::attrWgt() { auto wgtAttr = new QWidget(); - auto vBox = new QVBoxLayout(wgtAttr); + auto vBox = new VBox(wgtAttr); vBox->setContentsMargins(6, 0, 6, 0); - if(mMultiWin!=nullptr) vBox->setSpacing(3); + if(mMultiWin) vBox->setSpacing(3); addBaseAttrWgt(vBox); - auto hBox = new QHBoxLayout(); + auto hBox = new HBox(vBox); hBox->addWidget(new QLabel(tr("Basic Properties"))); auto line = new QFrame(); @@ -254,26 +264,24 @@ QWidget* eAClock::attrWgt() { line->setFrameShadow(QFrame::Sunken); hBox->addWidget(line, 1); - vBox->addLayout(hBox); - hBox = new QHBoxLayout(); + hBox = new HBox(vBox); hBox->addSpacing(6); hBox->addWidget(new QLabel(tr("Time Zone"))); auto wTimeZone = new QComboBox(); QList ids = QTimeZone::availableTimeZoneIds(); foreach(QByteArray id, ids) wTimeZone->addItem(QString::fromUtf8(id)); - wTimeZone->setCurrentText(m_attr.timeZoneId); + wTimeZone->setCurrentText(m_attr.timeZone.id()); connect(wTimeZone, &QComboBox::currentTextChanged, this, [this](const QString &text) { - m_attr.timeZoneId = text.toUtf8(); + m_attr.timeZone = QTimeZone(text.toUtf8()); update(); }); hBox->addWidget(wTimeZone); hBox->addStretch(); - vBox->addLayout(hBox); - hBox = new QHBoxLayout(); + hBox = new HBox(vBox); auto fdHasDialImg = new QCheckBox(tr("Custom Dial")); fdHasDialImg->setChecked(m_attr.hasDialImg); hBox->addWidget(fdHasDialImg); @@ -283,11 +291,10 @@ QWidget* eAClock::attrWgt() { line->setFrameShadow(QFrame::Sunken); hBox->addWidget(line, 1); - vBox->addLayout(hBox); auto wgtDial = new QWidget(); if(! m_attr.hasDialImg) wgtDial->setVisible(false); - hBox = new QHBoxLayout(wgtDial); + hBox = new HBox(wgtDial); hBox->setContentsMargins(0, 0, 0, 0); hBox->addSpacing(6); auto fdDialImg = new QLineEdit(); @@ -334,10 +341,10 @@ QWidget* eAClock::attrWgt() { update(); }); - auto vbMarks = new QVBoxLayout(wgtMarks); + auto vbMarks = new VBox(wgtMarks); vbMarks->setContentsMargins(0, 0, 0, 0); - hBox = new QHBoxLayout(); + hBox = new HBox(vbMarks); hBox->addSpacing(6); hBox->addWidget(new QLabel(tr("Hour Mark"))); @@ -370,9 +377,8 @@ QWidget* eAClock::attrWgt() { hBox->addWidget(fdHourMarkColor); hBox->addStretch(); - vbMarks->addLayout(hBox); - hBox = new QHBoxLayout(); + hBox = new HBox(vbMarks); hBox->addSpacing(6); hBox->addWidget(new QLabel(tr("Min Mark"))); @@ -404,40 +410,108 @@ QWidget* eAClock::attrWgt() { hBox->addWidget(fdMinMarkColor); hBox->addStretch(); - vbMarks->addLayout(hBox); - vBox->addWidget(wgtMarks); - hBox = new QHBoxLayout(); - hBox->addSpacing(6); - hBox->addWidget(new QLabel(tr("Hand Color"))); + auto grid = new QGridLayout; + grid->setColumnStretch(4, 1); + vBox->addLayout(grid); - auto fdHourHandColor = new LoColorSelector(tr("H"), m_attr.hourHandColor); + grid->addWidget(new QLabel(tr("Color")), 0, 1); + grid->addWidget(new QLabel(tr("Length")+" (%)"), 0, 2); + grid->addWidget(new QLabel(tr("Width")+" (%)"), 0, 3); + + grid->addWidget(new QLabel(tr("Hour Hand")), 1, 0, Qt::AlignRight); + + auto fdHourHandColor = new LoColorSelector("", m_attr.hourHandColor); fdHourHandColor->setFixedWidth(30); connect(fdHourHandColor, &LoColorSelector::sColorChanged, this, [this](const QColor &color) { m_attr.hourHandColor = color; update(); }); - hBox->addWidget(fdHourHandColor); + grid->addWidget(fdHourHandColor, 1, 1); - auto fdMinHandColor = new LoColorSelector(tr("M"), m_attr.minHandColor); + auto hhLen = new QSpinBox; + hhLen->setRange(0, 999); + hhLen->setValue(m_attr.hhLen); + connect(hhLen, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.hhLen = value; + update(); + }); + grid->addWidget(hhLen, 1, 2); + + auto hhWidth = new QSpinBox; + hhWidth->setRange(0, 999); + hhWidth->setValue(m_attr.hhWidth); + connect(hhWidth, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.hhWidth = value; + update(); + }); + grid->addWidget(hhWidth, 1, 3); + + grid->addWidget(new QLabel(tr("Min Hand")), 2, 0, Qt::AlignRight); + + auto fdMinHandColor = new LoColorSelector("", m_attr.minHandColor); fdMinHandColor->setFixedWidth(30); connect(fdMinHandColor, &LoColorSelector::sColorChanged, this, [this](const QColor &color) { m_attr.minHandColor = color; update(); }); - hBox->addWidget(fdMinHandColor); + grid->addWidget(fdMinHandColor, 2, 1); - auto fdSecHandColor = new LoColorSelector(tr("S"), m_attr.secHandColor); + auto mhLen = new QSpinBox; + mhLen->setRange(0, 999); + mhLen->setValue(m_attr.mhLen); + connect(mhLen, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.mhLen = value; + update(); + }); + grid->addWidget(mhLen, 2, 2); + + auto mhWidth = new QSpinBox; + mhWidth->setRange(0, 999); + mhWidth->setValue(m_attr.mhWidth); + connect(mhWidth, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.mhWidth = value; + update(); + }); + grid->addWidget(mhWidth, 2, 3); + + grid->addWidget(new QLabel(tr("Sec Hand")), 3, 0, Qt::AlignRight); + + auto fdSecHandColor = new LoColorSelector("", m_attr.secHandColor); fdSecHandColor->setFixedWidth(30); connect(fdSecHandColor, &LoColorSelector::sColorChanged, this, [this](const QColor &color) { m_attr.secHandColor = color; update(); }); - hBox->addWidget(fdSecHandColor); - hBox->addStretch(); + grid->addWidget(fdSecHandColor, 3, 1); + + auto shLen = new QSpinBox; + shLen->setRange(0, 999); + shLen->setValue(m_attr.shLen); + connect(shLen, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.shLen = value; + update(); + }); + grid->addWidget(shLen, 3, 2); + + auto shWidth = new QSpinBox; + shWidth->setRange(0, 999); + shWidth->setValue(m_attr.shWidth); + connect(shWidth, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.shWidth = value; + update(); + }); + grid->addWidget(shWidth, 3, 3); + + auto fdShowSecHand = new QCheckBox(tr("Show")); + fdShowSecHand->setChecked(m_attr.showSecHand); + connect(fdShowSecHand, &QCheckBox::toggled, this, [this](bool checked) { + m_attr.showSecHand = checked; + update(); + }); + grid->addWidget(fdShowSecHand, 3, 4); - vBox->addLayout(hBox); line = new QFrame(); line->setFrameShape(QFrame::HLine); @@ -452,7 +526,7 @@ QWidget* eAClock::attrWgt() { }); vBox->addWidget(fdText); - hBox = new QHBoxLayout(); + hBox = new HBox(vBox); hBox->addSpacing(6); auto fdFontFamily = new QFontComboBox(); @@ -478,20 +552,14 @@ QWidget* eAClock::attrWgt() { hBox->addWidget(fdFontSize); hBox->addStretch(); - vBox->addLayout(hBox); - hBox = new QHBoxLayout(); + hBox = new HBox(vBox); hBox->addSpacing(6); - auto fdBold = new QPushButton(); + auto fdBold = new QPushButton("B"); + fdBold->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-weight: bold;} QPushButton:checked{background: #29c; color: #fff;}"); fdBold->setFixedSize(30, 30); - QIcon icon; - icon.addFile(":/res/ProgramManager/EditProgram/FontBold_u.png", QSize(), QIcon::Normal, QIcon::Off); - icon.addFile(":/res/ProgramManager/EditProgram/FontBold_s.png", QSize(), QIcon::Normal, QIcon::On); - fdBold->setIcon(icon); - fdBold->setIconSize(QSize(30, 30)); fdBold->setCheckable(true); - fdBold->setFlat(true); fdBold->setChecked(m_attr.textFont.bold()); connect(fdBold, &QPushButton::toggled, this, [this](bool checked) { m_attr.textFont.setBold(checked); @@ -499,15 +567,10 @@ QWidget* eAClock::attrWgt() { }); hBox->addWidget(fdBold); - auto fdItalic = new QPushButton(); + auto fdItalic = new QPushButton("I"); + fdItalic->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-style: italic;} QPushButton:checked{background: #29c; color: #fff;}"); fdItalic->setFixedSize(30, 30); - QIcon icon1; - icon1.addFile(":/res/ProgramManager/EditProgram/FontItalics_u.png", QSize(), QIcon::Normal, QIcon::Off); - icon1.addFile(":/res/ProgramManager/EditProgram/FontItalics_s.png", QSize(), QIcon::Normal, QIcon::On); - fdItalic->setIcon(icon1); - fdItalic->setIconSize(QSize(30, 30)); fdItalic->setCheckable(true); - fdItalic->setFlat(true); fdItalic->setChecked(m_attr.textFont.italic()); connect(fdItalic, &QPushButton::toggled, this, [this](bool checked) { m_attr.textFont.setItalic(checked); @@ -515,15 +578,10 @@ QWidget* eAClock::attrWgt() { }); hBox->addWidget(fdItalic); - auto fdUnderline = new QPushButton(); + auto fdUnderline = new QPushButton("U"); + fdUnderline->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; text-decoration: underline;} QPushButton:checked{background: #29c; color: #fff;}"); fdUnderline->setFixedSize(30, 30); - QIcon icon2; - icon2.addFile(":/res/ProgramManager/EditProgram/FontUnderline_u.png", QSize(), QIcon::Normal, QIcon::Off); - icon2.addFile(":/res/ProgramManager/EditProgram/FontUnderline_s.png", QSize(), QIcon::Normal, QIcon::On); - fdUnderline->setIcon(icon2); - fdUnderline->setIconSize(QSize(30, 30)); fdUnderline->setCheckable(true); - fdUnderline->setFlat(true); fdUnderline->setChecked(m_attr.textFont.underline()); connect(fdUnderline, &QPushButton::toggled, this, [this](bool checked) { m_attr.textFont.setUnderline(checked); @@ -541,9 +599,8 @@ QWidget* eAClock::attrWgt() { hBox->addStretch(); - vBox->addLayout(hBox); - hBox = new QHBoxLayout(); + hBox = new HBox(vBox); hBox->addWidget(new QLabel(tr("Play Properties"))); line = new QFrame(); @@ -551,9 +608,8 @@ QWidget* eAClock::attrWgt() { line->setFrameShadow(QFrame::Sunken); hBox->addWidget(line, 1); - vBox->addLayout(hBox); - hBox = new QHBoxLayout(); + hBox = new HBox(vBox); hBox->addSpacing(6); hBox->addWidget(new QLabel(tr("Play Duration"))); @@ -568,12 +624,11 @@ QWidget* eAClock::attrWgt() { hBox->addWidget(new QLabel(tr("s"))); hBox->addStretch(); - vBox->addLayout(hBox); vBox->addStretch(); return wgtAttr; } -bool eAClock::save(const QString &pRoot){ +bool EAClock::save(const QString &pRoot){ if(m_attr.hasDialImg) { QString file0 = m_attr.path + PAGEDEL_SUFFIX + "/" + m_attr.name; QString file1 = m_attr.path + "/" + m_attr.name; @@ -595,45 +650,50 @@ bool eAClock::save(const QString &pRoot){ m_attr.selfCreateDialName = QString("%1%2%3%4%5.png").arg((int)zValue()).arg((int)x()).arg((int)y()).arg((int)mWidth).arg((int)mHeight); m_attr.path = pRoot; QRectF inner = innerRect(); - QPixmap *tempPixamp = new QPixmap(inner.width(), inner.height()); - tempPixamp->fill(Qt::transparent); - QPainter painter; - painter.begin(tempPixamp); - this->paintDial(&painter); - this->paintText(&painter); - painter.end(); - tempPixamp->save(pRoot+"/"+m_attr.selfCreateDialName, "PNG"); - delete tempPixamp; - //生成表盘背景图 + QImage img(inner.width(), inner.height(), QImage::Format_ARGB32); + img.fill(Qt::transparent); + { + QPainter painter(&img); + paintDial(&painter); + paintText(&painter); + } + img.save(pRoot+"/"+m_attr.selfCreateDialName, "PNG"); return true; } -QJsonObject eAClock::attrJson() const { - QJsonObject oRoot; - addBaseAttr(oRoot); - oRoot["elementType"] = "AClock"; - QJsonObject oWidget; - oWidget["timeZone"] = QString::fromUtf8(m_attr.timeZoneId); - oWidget["hourMark"] = m_attr.hourMark; - oWidget["hourMarkSize"] = m_attr.hourMarkSize; - oWidget["hourMarkColor"] = m_attr.hourMarkColor.name(); - oWidget["minMark"] = m_attr.minMark; - oWidget["minMarkSize"] = m_attr.minMarkSize; - oWidget["minMarkColor"] = m_attr.minMarkColor.name(); - oWidget["hourHandColor"] = m_attr.hourHandColor.name(); - oWidget["minHandColor"] = m_attr.minHandColor.name(); - oWidget["secHandColor"] = m_attr.secHandColor.name(); - oWidget["text"] = m_attr.text; - oWidget["textFontFamily"] = m_attr.textFont.family(); - oWidget["textFontSize"] = m_attr.textFont.pointSize(); - oWidget["textFontBold"] = m_attr.textFont.bold(); - oWidget["textFontItalics"] = m_attr.textFont.italic(); - oWidget["textFontUnderline"] = m_attr.textFont.underline(); - oWidget["textColor"] = m_attr.textColor.name(); - oWidget["path"] = m_attr.path; - oWidget["name"] = m_attr.name; - oWidget["selfCreateDialName"] = m_attr.selfCreateDialName; - oWidget["bCustomDial"] = m_attr.hasDialImg; - oRoot["widget"] = oWidget; - oRoot["play"] = QJsonObject{{"duration", m_attr.playDuration}}; - return oRoot; +QJsonObject EAClock::attrJson() const { + QJsonObject json; + addBaseAttr(json); + json["elementType"] = "AClock"; + QJsonObject widget; + widget["timeZone"] = QString::fromUtf8(m_attr.timeZone.id()); + widget["hourMark"] = m_attr.hourMark; + widget["hourMarkSize"] = m_attr.hourMarkSize; + widget["hourMarkColor"] = m_attr.hourMarkColor.name(); + widget["minMark"] = m_attr.minMark; + widget["minMarkSize"] = m_attr.minMarkSize; + widget["minMarkColor"] = m_attr.minMarkColor.name(); + widget["hourHandColor"] = m_attr.hourHandColor.name(); + widget["minHandColor"] = m_attr.minHandColor.name(); + widget["secHandColor"] = m_attr.secHandColor.name(); + widget["text"] = m_attr.text; + widget["textFontFamily"] = m_attr.textFont.family(); + widget["textFontSize"] = m_attr.textFont.pointSize(); + widget["textFontBold"] = m_attr.textFont.bold(); + widget["textFontItalics"] = m_attr.textFont.italic(); + widget["textFontUnderline"] = m_attr.textFont.underline(); + widget["textColor"] = m_attr.textColor.name(); + widget["hhLen"] = m_attr.hhLen; + widget["mhLen"] = m_attr.mhLen; + widget["shLen"] = m_attr.shLen; + widget["hhWidth"] = m_attr.hhWidth; + widget["mhWidth"] = m_attr.mhWidth; + widget["shWidth"] = m_attr.shWidth; + widget["showSecHand"] = m_attr.showSecHand; + widget["path"] = m_attr.path; + widget["name"] = m_attr.name; + widget["selfCreateDialName"] = m_attr.selfCreateDialName; + widget["bCustomDial"] = m_attr.hasDialImg; + json["widget"] = widget; + json["play"] = QJsonObject{{"duration", m_attr.playDuration}}; + return json; } diff --git a/LedOK/program/eaclock.h b/LedOK/program/eaclock.h new file mode 100644 index 0000000..785ce4c --- /dev/null +++ b/LedOK/program/eaclock.h @@ -0,0 +1,67 @@ +#ifndef EACLOCK_H +#define EACLOCK_H + +#include "ebase.h" +#include +#include + +class EAClock : public EBase { + Q_OBJECT +public: + struct Data { + QTimeZone timeZone; + int hourMark{0};//时针 + int hourMarkSize{5};//时针大小 + QColor hourMarkColor{Qt::green};//时针颜色 + int minMark{1};//分针 + int minMarkSize{2};//分针大小 + QColor minMarkColor{Qt::yellow};//分针颜色 + QColor hourHandColor;//秒针 + QColor minHandColor;//秒针大小 + QColor secHandColor;//秒针颜色 + int hhLen{50}, mhLen{75}, shLen{100}; + int hhWidth{15}, mhWidth{10}, shWidth{5}; + // r/2, r / 20 + // r*3/4, r / 30 + // r, r / 40 + QString text;//标题 + QFont textFont{"Arial", 9};//标题字体 + QColor textColor;//标题字体颜色 + int playDuration{10};// + QString path; + QString name; + QString selfCreateDialName; + bool hasDialImg{false}; + bool showSecHand{true}; + }; + + explicit EAClock(EBase *multiWin = nullptr); + explicit EAClock(const QJsonObject &json, EBase *multiWin = nullptr); + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; + int type() const override { return EBase::AClock; } + QWidget* attrWgt() override; + bool save(const QString &pRoot) override; + QJsonObject attrJson() const override; + +protected: + void timerEvent(QTimerEvent *) override; + void drawMarkCircular (QPainter *painter, const QPointF &pos, const QColor &color, qreal diameter); + void drawMarkRectangle(QPainter *painter, const QPointF &pos, const QColor &color, qreal len, qreal rotate); + void drawMarkNumber (QPainter *painter, const QPointF &pos, const QColor &color, qreal len, int num); + void paintDial(QPainter *painter); + void paintText(QPainter *painter); + + qreal radius() const { + return (qMin(rect().width(), rect().height()) - qMax(m_attr.minMarkSize, m_attr.hourMarkSize)) / 2; + } + + void cal(); + + Data m_attr; + QImage dial_img; + double hAngle, mAngle, sAngle; + int timerId{0}; +}; + +#endif // EACLOCK_H diff --git a/LedOK/wProgramManager/eaudio.cpp b/LedOK/program/eaudio.cpp similarity index 96% rename from LedOK/wProgramManager/eaudio.cpp rename to LedOK/program/eaudio.cpp index 48e05a3..599c72d 100644 --- a/LedOK/wProgramManager/eaudio.cpp +++ b/LedOK/program/eaudio.cpp @@ -1,6 +1,7 @@ #include "eaudio.h" #include "cfg.h" #include "tools.h" +#include "base/ffutil.h" #include #include #include @@ -13,7 +14,7 @@ EAudio *EAudio::create(const QString &file, PageListItem *pageItem, EBase *multiWin) { int64_t dur; - QString err = Tools::audioInfo(file.toUtf8(), &dur); + QString err = audioInfo(file.toUtf8(), &dur); if(! err.isEmpty()) { QMessageBox::critical(gMainWin, "Audio Error", err+"\n"+file); return nullptr; @@ -79,7 +80,7 @@ bool EAudio::save(const QString &pageDir) { void EAudio::paint(QPainter *painter, const QStyleOptionGraphicsItem *a, QWidget *b) { painter->setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform); - static auto img = QPixmap(":/res/ProgramManager/EditProgram/Audio.png"); + static auto img = QPixmap(":/res/program/Audio.png"); auto inner = innerRect(); if(inner.width() > inner.height()) inner.setWidth(inner.height()); else if(inner.height() > inner.width()) inner.setHeight(inner.width()); @@ -144,7 +145,7 @@ QWidget* EAudio::attrWgt() { auto file = QFileDialog::getOpenFileName(gMainWin, tr("Select File"), gFileHome, EAudio::filters()); if(file.isEmpty()) return; int64_t dur; - QString err = Tools::audioInfo(file.toUtf8(), &dur); + QString err = audioInfo(file.toUtf8(), &dur); if(! err.isEmpty()) { QMessageBox::critical(gMainWin, "Audio Error", err+"\n"+file); return; diff --git a/LedOK/wProgramManager/eaudio.h b/LedOK/program/eaudio.h similarity index 100% rename from LedOK/wProgramManager/eaudio.h rename to LedOK/program/eaudio.h diff --git a/LedOK/wProgramManager/ebase.cpp b/LedOK/program/ebase.cpp similarity index 98% rename from LedOK/wProgramManager/ebase.cpp rename to LedOK/program/ebase.cpp index 50bc2e6..2e32c7b 100644 --- a/LedOK/wProgramManager/ebase.cpp +++ b/LedOK/program/ebase.cpp @@ -1,5 +1,5 @@ #include "ebase.h" -#include "gqt.h" +#include "gutil/qgui.h" #include "tools.h" #include #include @@ -90,7 +90,7 @@ void EBase::addBaseAttr(QJsonObject &obj) const { } QRectF EBase::innerRect() const { - auto ele = mMultiWin!=nullptr ? mMultiWin : this; + auto ele = mMultiWin ? mMultiWin : this; int bdWidth = ele->bdImgIdx > -1 ? borderImgs[ele->bdImgIdx].img.height() : 0; return QRectF(bdWidth, bdWidth, ele->mWidth-bdWidth-bdWidth, ele->mHeight-bdWidth-bdWidth); } @@ -520,7 +520,7 @@ void EBase::clearSnap() { update(); } -void EBase::addBaseAttrWgt(QVBoxLayout *vBox) { +void EBase::addBaseAttrWgt(QBoxLayout *vBox) { if(mMultiWin!=nullptr) return; auto hBox = new QHBoxLayout(); hBox->addWidget(new QLabel(tr("Area"))); @@ -648,10 +648,11 @@ void EBase::addBaseAttrWgt(QVBoxLayout *vBox) { hBox->setSpacing(0); hBox->addStretch(); - auto borderFd = new QComboBox(); + auto borderFd = new QComboBox; borderFd->addItem(tr("None")); for(int i=0; iaddItem(QIcon(borderImgs[i].img), QString::number(borderImgs[i].img.height()), borderImgs[i].name); borderFd->setIconSize(QSize(borderImgMaxWidth, borderImgMaxHeight)); + if(bdImgIdx>-1) borderFd->setCurrentIndex(bdImgIdx+1); connect(borderFd, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this](int idx){ bdImgIdx = idx-1; if(bdImgIdx==-1 && bdTimerId>0) { @@ -670,6 +671,7 @@ void EBase::addBaseAttrWgt(QVBoxLayout *vBox) { borderEffFd->addItem(tr("Rotate"), "rotate"); borderEffFd->addItem(tr("Blink"), "blink"); borderEffFd->addItem(tr("None"), ""); + if(bdImgIdx>-1) setCurrentData(borderEffFd, bdEff); connect(borderEffFd, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this, borderEffFd] { bdEff = borderEffFd->currentData().toString(); if(bdTimerId>0) { @@ -687,7 +689,7 @@ void EBase::addBaseAttrWgt(QVBoxLayout *vBox) { borderSpeedFd->addItem(tr("Slow"), 1); borderSpeedFd->addItem(tr("Moderate"), 2); borderSpeedFd->addItem(tr("Fast"), 3); - borderSpeedFd->setCurrentIndex(1); + if(bdImgIdx>-1) setCurrentData(borderSpeedFd, bdSpeed); connect(borderSpeedFd, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this, borderSpeedFd] { bdSpeed = borderSpeedFd->currentData().toInt(); if(bdTimerId>0) { @@ -700,10 +702,4 @@ void EBase::addBaseAttrWgt(QVBoxLayout *vBox) { hBox->addStretch(); vBox->addLayout(hBox); - - if(bdImgIdx>-1) { - borderFd->setCurrentIndex(bdImgIdx+1); - select(borderEffFd, bdEff); - select(borderSpeedFd, bdSpeed); - } } diff --git a/LedOK/wProgramManager/ebase.h b/LedOK/program/ebase.h similarity index 98% rename from LedOK/wProgramManager/ebase.h rename to LedOK/program/ebase.h index 578b52b..7a88e12 100644 --- a/LedOK/wProgramManager/ebase.h +++ b/LedOK/program/ebase.h @@ -31,7 +31,7 @@ public: virtual bool save(const QString &) {return true;} virtual QWidget* attrWgt() = 0; - void addBaseAttrWgt(QVBoxLayout *vBox); + void addBaseAttrWgt(QBoxLayout *vBox); inline void setSize(qreal width, qreal height) { prepareGeometryChange(); mWidth = width; diff --git a/LedOK/wProgramManager/edclock.cpp b/LedOK/program/edclock.cpp similarity index 89% rename from LedOK/wProgramManager/edclock.cpp rename to LedOK/program/edclock.cpp index b5ece55..a63fb8d 100644 --- a/LedOK/wProgramManager/edclock.cpp +++ b/LedOK/program/edclock.cpp @@ -7,8 +7,9 @@ #include #include #include +#include -eDClock::eDClock(EBase *multiWin) : EBase(multiWin) { +EDClock::EDClock(EBase *multiWin) : EBase(multiWin) { mType = EBase::DClock; m_attr.timeZoneId = QTimeZone::systemTimeZoneId(); m_attr.font = QFont("Arial", 9); @@ -29,7 +30,7 @@ eDClock::eDClock(EBase *multiWin) : EBase(multiWin) { init(); } -eDClock::eDClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { +EDClock::EDClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { mType = EBase::DClock; setBaseAttr(json); auto widget = json["widget"]; @@ -58,14 +59,14 @@ eDClock::eDClock(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { init(); } -void eDClock::init() { +void EDClock::init() { connect(Tools::getInstance(), &Tools::sTick, this, [this]() { datetime = QDateTime::currentDateTime().toTimeZone(QTimeZone(m_attr.timeZoneId)); update(); }); } -void eDClock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { +void EDClock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QString text; QDate date = datetime.date(); QTime time = datetime.time(); @@ -133,7 +134,7 @@ void eDClock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, Q EBase::paint(painter, option, widget); } -QWidget* eDClock::attrWgt() { +QWidget* EDClock::attrWgt() { auto wgtAttr = new QWidget(); auto vBox = new QVBoxLayout(wgtAttr); vBox->setContentsMargins(6, 0, 6, 0); @@ -378,15 +379,10 @@ QWidget* eDClock::attrWgt() { hBox = new QHBoxLayout(); hBox->addSpacing(6); - auto fdBold = new QPushButton(); + auto fdBold = new QPushButton("B"); + fdBold->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-weight: bold;} QPushButton:checked{background: #29c; color: #fff;}"); fdBold->setFixedSize(30, 30); - QIcon icon; - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontBold_u.png"), QSize(), QIcon::Normal, QIcon::Off); - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontBold_s.png"), QSize(), QIcon::Normal, QIcon::On); - fdBold->setIcon(icon); - fdBold->setIconSize(QSize(30, 30)); fdBold->setCheckable(true); - fdBold->setFlat(true); fdBold->setChecked(m_attr.font.bold()); connect(fdBold, &QCheckBox::toggled, this, [this](bool checked) { m_attr.font.setBold(checked); @@ -394,15 +390,10 @@ QWidget* eDClock::attrWgt() { }); hBox->addWidget(fdBold); - auto fdItalic = new QPushButton(); + auto fdItalic = new QPushButton("I"); + fdItalic->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-style: italic;} QPushButton:checked{background: #29c; color: #fff;}"); fdItalic->setFixedSize(30, 30); - QIcon icon1; - icon1.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontItalics_u.png"), QSize(), QIcon::Normal, QIcon::Off); - icon1.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontItalics_s.png"), QSize(), QIcon::Normal, QIcon::On); - fdItalic->setIcon(icon1); - fdItalic->setIconSize(QSize(30, 30)); fdItalic->setCheckable(true); - fdItalic->setFlat(true); fdItalic->setChecked(m_attr.font.italic()); connect(fdItalic, &QCheckBox::toggled, this, [this](bool checked) { m_attr.font.setItalic(checked); @@ -410,21 +401,16 @@ QWidget* eDClock::attrWgt() { }); hBox->addWidget(fdItalic); - auto fdUnderline = new QPushButton(); - fdUnderline->setFixedSize(30, 30); - QIcon icon2; - icon2.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontUnderline_u.png"), QSize(), QIcon::Normal, QIcon::Off); - icon2.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontUnderline_s.png"), QSize(), QIcon::Normal, QIcon::On); - fdUnderline->setIcon(icon2); - fdUnderline->setIconSize(QSize(30, 30)); - fdUnderline->setCheckable(true); - fdUnderline->setFlat(true); - fdUnderline->setChecked(m_attr.font.underline()); - connect(fdUnderline, &QCheckBox::toggled, this, [this](bool checked) { + auto fdFontUnderline = new QPushButton("U"); + fdFontUnderline->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; text-decoration: underline;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontUnderline->setFixedSize(30, 30); + fdFontUnderline->setCheckable(true); + fdFontUnderline->setChecked(m_attr.font.underline()); + connect(fdFontUnderline, &QCheckBox::toggled, this, [this](bool checked) { m_attr.font.setUnderline(checked); update(); }); - hBox->addWidget(fdUnderline); + hBox->addWidget(fdFontUnderline); auto fdColor = new LoColorSelector("T", m_attr.textColor); fdColor->setFixedWidth(30); @@ -467,7 +453,7 @@ QWidget* eDClock::attrWgt() { return wgtAttr; } -QJsonObject eDClock::attrJson() const{ +QJsonObject EDClock::attrJson() const{ QJsonObject oWidget; oWidget["timeZone"] = QString::fromUtf8(m_attr.timeZoneId); oWidget["year"] = m_attr.year; diff --git a/LedOK/wProgramManager/edclock.h b/LedOK/program/edclock.h similarity index 88% rename from LedOK/wProgramManager/edclock.h rename to LedOK/program/edclock.h index 23cbba9..fbce201 100644 --- a/LedOK/wProgramManager/edclock.h +++ b/LedOK/program/edclock.h @@ -9,7 +9,7 @@ #include #include "ebase.h" -class eDClock : public EBase { +class EDClock : public EBase { Q_OBJECT public: struct Data { @@ -32,8 +32,8 @@ public: int playDuration = 10; }; - explicit eDClock(EBase *multiWin = nullptr); - explicit eDClock(const QJsonObject &json, EBase *multiWin = nullptr); + explicit EDClock(EBase *multiWin = nullptr); + explicit EDClock(const QJsonObject &json, EBase *multiWin = nullptr); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; int type() const override { return EBase::DClock; } diff --git a/LedOK/wProgramManager/eenviron.cpp b/LedOK/program/eenviron.cpp similarity index 94% rename from LedOK/wProgramManager/eenviron.cpp rename to LedOK/program/eenviron.cpp index e5a2d20..4a92384 100644 --- a/LedOK/wProgramManager/eenviron.cpp +++ b/LedOK/program/eenviron.cpp @@ -13,6 +13,7 @@ #include #include #include +#include QJsonObject EEnviron::genProg(const QJsonObject &json, const QString &dstDir, const QString &srcPageDir) { auto widget = json["widget"]; @@ -602,54 +603,41 @@ QWidget* EEnviron::attrWgt() { hBox = new QHBoxLayout(); hBox->addSpacing(6); - auto fdBold = new QPushButton(); - fdBold->setFixedSize(QSize(30, 30)); - fdBold->setIconSize(QSize(30, 30)); - QIcon icon(":/res/ProgramManager/EditProgram/FontBold_u.png"); - icon.addFile(":/res/ProgramManager/EditProgram/FontBold_s.png", QSize(), QIcon::Normal, QIcon::On); - fdBold->setIcon(icon); - fdBold->setCheckable(true); - fdBold->setFlat(true); - fdBold->setChecked(m_attr.font.bold()); - connect(fdBold, &QPushButton::toggled, this, [this](bool checked) { + auto fdFontBold = new QPushButton("B"); + fdFontBold->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-weight: bold;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontBold->setFixedSize(30, 30); + fdFontBold->setCheckable(true); + fdFontBold->setChecked(m_attr.font.bold()); + connect(fdFontBold, &QPushButton::toggled, this, [this](bool checked) { m_attr.font.setBold(checked); calAttr(); update(); }); - hBox->addWidget(fdBold); + hBox->addWidget(fdFontBold); - auto fdItalic = new QPushButton(); - fdItalic->setFixedSize(QSize(30, 30)); - fdItalic->setIconSize(QSize(30, 30)); - QIcon icon1(":/res/ProgramManager/EditProgram/FontItalics_u.png"); - icon1.addFile(":/res/ProgramManager/EditProgram/FontItalics_s.png", QSize(), QIcon::Normal, QIcon::On); - fdItalic->setIcon(icon1); - fdItalic->setCheckable(true); - fdItalic->setFlat(true); - fdItalic->setChecked(m_attr.font.italic()); - connect(fdItalic, &QPushButton::toggled, this, [this](bool checked) { + auto fdFontItalic = new QPushButton("I"); + fdFontItalic->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-style: italic;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontItalic->setFixedSize(30, 30); + fdFontItalic->setCheckable(true); + fdFontItalic->setChecked(m_attr.font.italic()); + connect(fdFontItalic, &QPushButton::toggled, this, [this](bool checked) { m_attr.font.setItalic(checked); calAttr(); update(); }); - hBox->addWidget(fdItalic); + hBox->addWidget(fdFontItalic); - auto fdUnderline = new QPushButton(); - fdUnderline->setFixedSize(QSize(30, 30)); - fdUnderline->setIconSize(QSize(30, 30)); - QIcon icon2(":/res/ProgramManager/EditProgram/FontUnderline_u.png"); - icon2.addFile(":/res/ProgramManager/EditProgram/FontUnderline_s.png", QSize(), QIcon::Normal, QIcon::On); - fdUnderline->setIcon(icon2); - fdUnderline->setCheckable(true); - fdUnderline->setFlat(true); - fdUnderline->setChecked(m_attr.font.underline()); - connect(fdUnderline, &QPushButton::toggled, this, [this](bool checked) { + auto fdFontUnderline = new QPushButton("U"); + fdFontUnderline->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; text-decoration: underline;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontUnderline->setFixedSize(30, 30); + fdFontUnderline->setCheckable(true); + fdFontUnderline->setChecked(m_attr.font.underline()); + connect(fdFontUnderline, &QPushButton::toggled, this, [this](bool checked) { m_attr.font.setUnderline(checked); calAttr(); update(); }); - hBox->addWidget(fdUnderline); - + hBox->addWidget(fdFontUnderline); auto fdColor = new LoColorSelector("T", m_attr.textColor); fdColor->setFixedWidth(30); diff --git a/LedOK/wProgramManager/eenviron.h b/LedOK/program/eenviron.h similarity index 100% rename from LedOK/wProgramManager/eenviron.h rename to LedOK/program/eenviron.h diff --git a/LedOK/wProgramManager/egif.cpp b/LedOK/program/egif.cpp similarity index 100% rename from LedOK/wProgramManager/egif.cpp rename to LedOK/program/egif.cpp diff --git a/LedOK/wProgramManager/egif.h b/LedOK/program/egif.h similarity index 100% rename from LedOK/wProgramManager/egif.h rename to LedOK/program/egif.h diff --git a/LedOK/wProgramManager/emultiwin.cpp b/LedOK/program/emultiwin.cpp similarity index 80% rename from LedOK/wProgramManager/emultiwin.cpp rename to LedOK/program/emultiwin.cpp index 581d074..64a6f08 100644 --- a/LedOK/wProgramManager/emultiwin.cpp +++ b/LedOK/program/emultiwin.cpp @@ -34,8 +34,8 @@ EMultiWin::EMultiWin(const QJsonObject &json, PageListItem *pageItem) : mPageIte else if(type=="Photo") inner = EPhoto::create(element.toObject(), pageItem, this); else if(type=="Gif") inner = EGif::create(element.toObject(), pageItem, this); else if(type=="Movie") inner = EVideo::create(element.toObject(), pageItem, this); - else if(type=="DClock") inner = new eDClock(element.toObject(), this); - else if(type=="AClock") inner = new eAClock(element.toObject(), this); + else if(type=="DClock") inner = new EDClock(element.toObject(), this); + else if(type=="AClock") inner = new EAClock(element.toObject(), this); else if(type=="Temp") inner = new EEnviron(element.toObject(), this); else if(type=="Web") inner = new EWeb(element.toObject(), this); else if(type=="Timer") inner = new ETimer(element.toObject(), this); @@ -123,16 +123,16 @@ QWidget* EMultiWin::attrWgt() { auto hBox = new QHBoxLayout(); auto btnAdd = new QPushButton(); - btnAdd->setIcon(QIcon(":/res/ProgramManager/EditProgram/Add.png")); + btnAdd->setIcon(QIcon(":/res/program/Add.png")); btnAdd->setProperty("style","multiTool"); auto menu = new QMenu(); - menu->addAction(QIcon(":/res/ProgramManager/EditProgram/Text.png"), tr("Text"))->setData(EBase::Text); - menu->addAction(QIcon(":/res/ProgramManager/EditProgram/Photo.png"), tr("Photo"))->setData(EBase::Photo); - menu->addAction(QIcon(":/res/ProgramManager/EditProgram/Movie.png"), tr("Video"))->setData(EBase::Video); - menu->addAction(QIcon(":/res/ProgramManager/EditProgram/Gif.png"), tr("Gif"))->setData(EBase::Gif); - menu->addAction(QIcon(":/res/ProgramManager/EditProgram/DClock.png"), tr("DClock"))->setData(EBase::DClock); - menu->addAction(QIcon(":/res/ProgramManager/EditProgram/AClock.png"), tr("AClock"))->setData(EBase::AClock); + menu->addAction(QIcon(":/res/program/Text.png"), tr("Text"))->setData(EBase::Text); + menu->addAction(QIcon(":/res/program/Photo.png"), tr("Photo"))->setData(EBase::Photo); + menu->addAction(QIcon(":/res/program/Movie.png"), tr("Video"))->setData(EBase::Video); + menu->addAction(QIcon(":/res/program/Gif.png"), tr("Gif"))->setData(EBase::Gif); + menu->addAction(QIcon(":/res/program/DClock.png"), tr("DClock"))->setData(EBase::DClock); + menu->addAction(QIcon(":/res/program/AClock.png"), tr("AClock"))->setData(EBase::AClock); auto listWgt = new MListWidget(); connect(menu, &QMenu::triggered, this, [this, listWgt](QAction *act) { int type = act->data().toInt(); @@ -148,7 +148,7 @@ QWidget* EMultiWin::attrWgt() { ePhoto->setZValue(order++); ePhoto->setFlag(QGraphicsItem::ItemStacksBehindParent); inners.append(ePhoto); - auto item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Photo.png"), tr("Photo")+" "+ePhoto->mName); + auto item = new QListWidgetItem(QIcon(":/res/program/Photo.png"), tr("Photo")+" "+ePhoto->mName); item->setData(Qt::UserRole, QVariant::fromValue(static_cast(ePhoto))); listWgt->addItem(item); if(i==files.count()-1) { @@ -165,7 +165,7 @@ QWidget* EMultiWin::attrWgt() { eGif->setZValue(order++); eGif->setFlag(QGraphicsItem::ItemStacksBehindParent); inners.append(eGif); - auto item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Gif.png"), tr("Gif")+" "+eGif->mName); + auto item = new QListWidgetItem(QIcon(":/res/program/Gif.png"), tr("Gif")+" "+eGif->mName); item->setData(Qt::UserRole, QVariant::fromValue(static_cast(eGif))); listWgt->addItem(item); if(i == files.count()-1) { @@ -178,25 +178,25 @@ QWidget* EMultiWin::attrWgt() { if(! file.isEmpty()) { auto eVideo = EVideo::create(file, mPageItem, this); if(eVideo==nullptr) return; - item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Movie.png"), tr("Video")+" "+eVideo->mRawName); + item = new QListWidgetItem(QIcon(":/res/program/Movie.png"), tr("Video")+" "+eVideo->mRawName); gFileHome = eVideo->mRawDir; ele = eVideo; } } else if(type==EBase::Text) { ele = new EText(this); - item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Text.png"), tr("Text")); + item = new QListWidgetItem(QIcon(":/res/program/Text.png"), tr("Text")); } else if(type==EBase::DClock) { - ele = new eDClock(this); - item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/DClock.png"), tr("DClock")); + ele = new EDClock(this); + item = new QListWidgetItem(QIcon(":/res/program/DClock.png"), tr("DClock")); } else if(type==EBase::AClock) { - ele = new eAClock(this); - item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/AClock.png"), tr("AClock")); + ele = new EAClock(this); + item = new QListWidgetItem(QIcon(":/res/program/AClock.png"), tr("AClock")); } else if(type==EBase::Environ) { ele = new EEnviron(this); - item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Temp.png"), tr("Environment")); + item = new QListWidgetItem(QIcon(":/res/program/Temp.png"), tr("Environment")); } else if(type==EBase::Timer) { ele = new ETimer(this); - item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Timer.png"), tr("Timer")); + item = new QListWidgetItem(QIcon(":/res/program/Timer.png"), tr("Timer")); } if(ele != nullptr) { ele->setSize(mWidth, mHeight); @@ -212,7 +212,7 @@ QWidget* EMultiWin::attrWgt() { hBox->addWidget(btnAdd); auto btnDel = new QPushButton(); - btnDel->setIcon(QIcon(":/res/ProgramManager/EditProgram/Delete.png")); + btnDel->setIcon(QIcon(":/res/program/Delete.png")); btnDel->setProperty("style","multiTool"); connect(btnDel, &QPushButton::clicked, this, [this, listWgt] { auto row = listWgt->currentRow(); @@ -229,7 +229,7 @@ QWidget* EMultiWin::attrWgt() { hBox->addWidget(btnDel); auto btnClean = new QPushButton(); - btnClean->setIcon(QIcon(":/res/ProgramManager/EditProgram/Clean.png")); + btnClean->setIcon(QIcon(":/res/program/Clean.png")); btnClean->setProperty("style","multiTool"); connect(btnClean, &QPushButton::clicked, this, [this, listWgt] { listWgt->clear(); @@ -239,7 +239,7 @@ QWidget* EMultiWin::attrWgt() { hBox->addWidget(btnClean); auto btnGoUp = new QPushButton(); - btnGoUp->setIcon(QIcon(":/res/ProgramManager/EditProgram/GoUp.png")); + btnGoUp->setIcon(QIcon(":/res/program/GoUp.png")); btnGoUp->setProperty("style","multiTool"); connect(btnGoUp, &QPushButton::clicked, this, [this, listWgt] { int row = listWgt->currentRow(); @@ -253,7 +253,7 @@ QWidget* EMultiWin::attrWgt() { hBox->addWidget(btnGoUp); auto btnGoDown = new QPushButton(); - btnGoDown->setIcon(QIcon(":/res/ProgramManager/EditProgram/GoDown.png")); + btnGoDown->setIcon(QIcon(":/res/program/GoDown.png")); btnGoDown->setProperty("style","multiTool"); connect(btnGoDown, &QPushButton::clicked, this, [this, listWgt] { int row = listWgt->currentRow(); @@ -273,14 +273,14 @@ QWidget* EMultiWin::attrWgt() { foreach(auto inner, inners) { QListWidgetItem *item = nullptr; int type = inner->type(); - if(type==EBase::Text) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Text.png"), tr("Text")); - else if(type==EBase::Photo) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Photo.png"), tr("Photo")+" "+static_cast(inner)->mName); - else if(type==EBase::Video) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Movie.png"), tr("Video")+" "+static_cast(inner)->mRawName); - else if(type==EBase::Gif) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Gif.png"), tr("Gif")+" "+static_cast(inner)->mName); - else if(type==EBase::DClock) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/DClock.png"), tr("DClock")); - else if(type==EBase::AClock) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/AClock.png"), tr("AClock")); - else if(type==EBase::Environ) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Temp.png"), tr("Environment")); - else if(type==EBase::Timer) item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Timer.png"), tr("Timer")); + if(type==EBase::Text) item = new QListWidgetItem(QIcon(":/res/program/Text.png"), tr("Text")); + else if(type==EBase::Photo) item = new QListWidgetItem(QIcon(":/res/program/Photo.png"), tr("Photo")+" "+static_cast(inner)->mName); + else if(type==EBase::Video) item = new QListWidgetItem(QIcon(":/res/program/Movie.png"), tr("Video")+" "+static_cast(inner)->mRawName); + else if(type==EBase::Gif) item = new QListWidgetItem(QIcon(":/res/program/Gif.png"), tr("Gif")+" "+static_cast(inner)->mName); + else if(type==EBase::DClock) item = new QListWidgetItem(QIcon(":/res/program/DClock.png"), tr("DClock")); + else if(type==EBase::AClock) item = new QListWidgetItem(QIcon(":/res/program/AClock.png"), tr("AClock")); + else if(type==EBase::Environ) item = new QListWidgetItem(QIcon(":/res/program/Temp.png"), tr("Environment")); + else if(type==EBase::Timer) item = new QListWidgetItem(QIcon(":/res/program/Timer.png"), tr("Timer")); if(item != nullptr) { item->setData(Qt::UserRole, QVariant::fromValue(static_cast(inner))); listWgt->addItem(item); diff --git a/LedOK/wProgramManager/emultiwin.h b/LedOK/program/emultiwin.h similarity index 100% rename from LedOK/wProgramManager/emultiwin.h rename to LedOK/program/emultiwin.h diff --git a/LedOK/wProgramManager/ephoto.cpp b/LedOK/program/ephoto.cpp similarity index 95% rename from LedOK/wProgramManager/ephoto.cpp rename to LedOK/program/ephoto.cpp index 531b807..b2451a9 100644 --- a/LedOK/wProgramManager/ephoto.cpp +++ b/LedOK/program/ephoto.cpp @@ -76,14 +76,14 @@ void EPhoto::loadFiles() { if(! img.isNull()) return; if(! QFileInfo::exists(mDir + "/" + mName)) return; img = QImage(mDir + "/" + mName); - if(gProgItem->mSplitWidth) { - int cnt = (gProgItem->mWidth+gProgItem->mSplitWidth-1) / gProgItem->mSplitWidth; - QImage square(gProgItem->mSplitWidth, gProgItem->mHeight*cnt, QImage::Format_ARGB32); + if(gProgItem->mMaxWidth) { + QImage square(gProgItem->mMaxWidth, gProgItem->mHeight*gProgItem->mSplitWidths.size(), QImage::Format_ARGB32); QPainter painter(&square); - auto rect = innerRect(); + QRectF rect(x(), y(), mWidth, mHeight); painter.drawImage(rect, img); - for(int i=1; imSplitWidth, rect.y() + gProgItem->mHeight); + auto end = gProgItem->mSplitWidths.size() - 1; + for(int i=0; imSplitWidths[i], rect.y() + gProgItem->mHeight); painter.drawImage(rect, img); } square.save(mDir + "/" + mName+"-square.png", "PNG"); diff --git a/LedOK/wProgramManager/ephoto.h b/LedOK/program/ephoto.h similarity index 100% rename from LedOK/wProgramManager/ephoto.h rename to LedOK/program/ephoto.h diff --git a/LedOK/program/etext.cpp b/LedOK/program/etext.cpp new file mode 100644 index 0000000..421f667 --- /dev/null +++ b/LedOK/program/etext.cpp @@ -0,0 +1,819 @@ +#include "base/locolorselector.h" +#include "cfg.h" +#include "etext.h" +#include "globaldefine.h" +#include "tools.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static QColor charColors[]{"#fff","#f00","#f00","#f0f","#c0c","#ff0","#f80","#0f0","#0f0","#0a0","#0a0","#7b0","#00f","#00f","#0af","#0ef"}; + +EText::EText(EBase *multiWin) : EBase(multiWin) { + mType = EBase::Text; + m_attr.text = ""+tr("Enter your text")+""; + connect(this, &EText::sizeChanged, this, &EText::updImg); + updImg(); +} +EText::EText(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { + mType = EBase::Text; + setBaseAttr(json); + setElement(json, m_attr); + connect(this, &EText::sizeChanged, this, &EText::updImg); + updImg(); +} + +void EText::setElement(const QJsonObject &json, Data &attr) { + auto widget = json["widget"]; + attr.text = widget["text"].toString(); + attr.align = static_cast(widget["align"].toInt()); + auto backColor = widget["backColor"].toString(); + attr.backColor = backColor.isEmpty() ? QColor(0,0,0,0) : QColor(backColor); + auto play = json["play"]; + attr.playMode = play["style"].toInt(); + auto turning = play["turning"]; + attr.flip.effect = turning["strEffect"].toString(); + attr.flip.pageDuration = turning["iEffectTime"].toInt(); + attr.flip.effectDuration = turning["iEffectSpeed"].toInt(); + auto rolling = play["rolling"]; + attr.scroll.effect = rolling["rollingStyle"].toInt(); + attr.scroll.effectSpeed = rolling["rollingSpeed"].toInt(); + attr.scroll.headTailSpacing = rolling["headTailSpacing"].toInt(); + attr.scroll.duration = rolling["playDuration"].toInt(); + attr.duration = play["static"]["playDuration"].toInt(); +} + +class TTextEdit : public QTextEdit { +public: + TTextEdit() {} + explicit TTextEdit(const QString &text) : QTextEdit(text){} + QSize minimumSizeHint() const override { + return sizeHint(); + }; + QSize sizeHint() const override { + auto size = QTextEdit::sizeHint(); + auto minH = minimumHeight(); + if(minH > 0) size.setHeight(minH+0xfff); + return size; + }; +}; +QWidget* EText::attrWgt() { + auto wgtAttr = new QWidget; + auto vBox = new QVBoxLayout(wgtAttr); + vBox->setContentsMargins(4, 0, 4, 0); + vBox->setSpacing(3); + + addBaseAttrWgt(vBox); + + auto hBox = new QHBoxLayout; + hBox->addWidget(new QLabel(tr("Basic Properties"))); + + auto line = new QFrame; + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + hBox->addWidget(line, 1); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout; + + auto fdText = new TTextEdit(""); + + auto fdFontFamily = new QFontComboBox; + fdFontFamily->setEditable(false); + fdFontFamily->setCurrentFont(QFont("黑体")); + connect(fdFontFamily, &QFontComboBox::currentFontChanged, fdText, [fdText](const QFont &f) { + QTextCharFormat fmt; + fmt.setFontFamilies({f.family()}); + QTextCursor cursor = fdText->textCursor(); + if(! cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeCharFormat(fmt); + }); + hBox->addWidget(fdFontFamily); + + hBox->addStretch(); + + auto fdFontSize = new QSpinBox; + fdFontSize->setRange(4, 9999); + fdFontSize->setValue(16); + connect(fdFontSize, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, fdText, [fdText](int value) { + if(value <= 0) return; + QTextCharFormat fmt; + fmt.setProperty(QTextFormat::FontPixelSize, value); + QTextCursor cursor = fdText->textCursor(); + if(! cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeCharFormat(fmt); + }); + hBox->addWidget(fdFontSize); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout; + hBox->setSpacing(3); + + auto wTextAlignHL = new QPushButton(QIcon(":/res/program/TextAlignHL.png"), ""); + wTextAlignHL->setStyleSheet("QPushButton{border: none; background: #bbb;} QPushButton:checked{background: #29c;}"); + wTextAlignHL->setFixedSize(30, 30); + wTextAlignHL->setIconSize(QSize(30, 30)); + wTextAlignHL->setCheckable(true); + wTextAlignHL->setChecked(true); + hBox->addWidget(wTextAlignHL); + + auto wTextAlignHC = new QPushButton(QIcon(":/res/program/TextAlignHC.png"), ""); + wTextAlignHC->setStyleSheet("QPushButton{border: none; background: #bbb;} QPushButton:checked{background: #29c;}"); + wTextAlignHC->setFixedSize(30, 30); + wTextAlignHC->setIconSize(QSize(30, 30)); + wTextAlignHC->setCheckable(true); + hBox->addWidget(wTextAlignHC); + + auto wTextAlignHR = new QPushButton(QIcon(":/res/program/TextAlignHR.png"), ""); + wTextAlignHR->setStyleSheet("QPushButton{border: none; background: #bbb;} QPushButton:checked{background: #29c;}"); + wTextAlignHR->setFixedSize(30, 30); + wTextAlignHR->setIconSize(QSize(30, 30)); + wTextAlignHR->setCheckable(true); + hBox->addWidget(wTextAlignHR); + + hBox->addStretch(); + + auto fdFontBold = new QPushButton("B"); + fdFontBold->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-weight: bold;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontBold->setFixedSize(30, 30); + fdFontBold->setCheckable(true); + connect(fdFontBold, &QToolButton::toggled, fdText, [fdText](bool checked) { + QTextCharFormat fmt; + fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal); + Tools::mergeFormat(fdText, fmt); + }); + hBox->addWidget(fdFontBold); + + auto fdFontItalic = new QPushButton("I"); + fdFontItalic->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-style: italic;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontItalic->setFixedSize(30, 30); + fdFontItalic->setCheckable(true); + connect(fdFontItalic, &QToolButton::toggled, fdText, [fdText](bool checked) { + QTextCharFormat fmt; + fmt.setFontItalic(checked); + Tools::mergeFormat(fdText, fmt); + }); + hBox->addWidget(fdFontItalic); + + auto fdFontUnderline = new QPushButton("U"); + fdFontUnderline->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; text-decoration: underline;} QPushButton:checked{background: #29c; color: #fff;}"); + fdFontUnderline->setFixedSize(30, 30); + fdFontUnderline->setCheckable(true); + connect(fdFontUnderline, &QToolButton::toggled, fdText, [fdText](bool checked) { + QTextCharFormat fmt; + fmt.setFontUnderline(checked); + Tools::mergeFormat(fdText, fmt); + }); + hBox->addWidget(fdFontUnderline); + + hBox->addStretch(); + + auto fdTextColor = new LoColorSelector("T", Qt::white); + fdTextColor->setToolTip(tr("Text Color")); + fdTextColor->setFixedSize(30, 30); + connect(fdTextColor, &LoColorSelector::sColorChanged, fdText, [fdText](const QColor &color) { + if(! color.isValid()) return; + QTextCharFormat fmt; + fmt.setForeground(color); + Tools::mergeFormat(fdText, fmt); + }); + hBox->addWidget(fdTextColor); + + auto fdBackColor = new LoColorSelector("B", m_attr.backColor); + fdBackColor->setToolTip(tr("Back Color")); + fdBackColor->setFixedSize(30, 30); + connect(fdBackColor, &LoColorSelector::sColorChanged, this, [this](const QColor &color) { + if(! color.isValid()) return; + m_attr.backColor = color; + updImg(); + }); + hBox->addWidget(fdBackColor); + + auto fdRandomColor = new QPushButton(QIcon(":/res/random.png"), ""); + fdRandomColor->setToolTip(tr("Colorful Text")); + fdRandomColor->setFixedSize(30, 30); + fdRandomColor->setIconSize(QSize(30, 30)); + connect(fdRandomColor, &QPushButton::clicked, fdText, [fdText] { + auto cursor = fdText->textCursor(); + auto len = fdText->document()->characterCount(); + QTextCharFormat fmt; + int last = -1, idx; + for(int i=0; iaddWidget(fdRandomColor); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout; + hBox->setSpacing(3); + + auto wTextAlignVT = new QPushButton(QIcon(":/res/program/TextAlignVT.png"), ""); + wTextAlignVT->setStyleSheet("QPushButton{border: none; background: #bbb;} QPushButton:checked{background: #29c;}"); + wTextAlignVT->setFixedSize(30, 30); + wTextAlignVT->setIconSize(QSize(30, 30)); + wTextAlignVT->setCheckable(true); + hBox->addWidget(wTextAlignVT); + + auto wTextAlignVC = new QPushButton(QIcon(":/res/program/TextAlignVC.png"), ""); + wTextAlignVC->setStyleSheet("QPushButton{border: none; background: #bbb;} QPushButton:checked{background: #29c;}"); + wTextAlignVC->setFixedSize(30, 30); + wTextAlignVC->setIconSize(QSize(30, 30)); + wTextAlignVC->setCheckable(true); + hBox->addWidget(wTextAlignVC); + + auto wTextAlignVB = new QPushButton(QIcon(":/res/program/TextAlignVB.png"), ""); + wTextAlignVB->setStyleSheet("QPushButton{border: none; background: #bbb;} QPushButton:checked{background: #29c;}"); + wTextAlignVB->setFixedSize(30, 30); + wTextAlignVB->setIconSize(QSize(30, 30)); + wTextAlignVB->setCheckable(true); + hBox->addWidget(wTextAlignVB); + + hBox->addStretch(); + + auto lb = new QLabel(tr("Kerning")); + lb->setToolTip(lb->text()); + hBox->addWidget(lb); + + auto fdLetterSpacing = new QSpinBox(); + fdLetterSpacing->setMaximum(999); + connect(fdLetterSpacing, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this, fdText](int value) { + QTextCharFormat fmt; + fmt.setFontLetterSpacing(value); + QTextCursor cursor = fdText->textCursor(); + if(! cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeCharFormat(fmt); + updImg(); + }); + hBox->addWidget(fdLetterSpacing); + + lb = new QLabel(tr("Line Spacing")); + lb->setToolTip(lb->text()); + hBox->addWidget(lb); + + auto fdLineSpacing = new QSpinBox(); + fdLineSpacing->setRange(-99, 999); + connect(fdLineSpacing, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this, fdText](int value) { + QTextBlockFormat fmt; + fmt.setLineHeight(value, QTextBlockFormat::LineDistanceHeight); + QTextCursor cursor = fdText->textCursor(); + if(! cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); + cursor.mergeBlockFormat(fmt); + updImg(); + }); + hBox->addWidget(fdLineSpacing); + + vBox->addLayout(hBox); + + auto wTextAlignH = new QButtonGroup(wgtAttr); + wTextAlignH->addButton(wTextAlignHL, Qt::AlignLeft); + wTextAlignH->addButton(wTextAlignHC, Qt::AlignHCenter); + wTextAlignH->addButton(wTextAlignHR, Qt::AlignRight); + connect(wTextAlignH, &QButtonGroup::idClicked, this, [this, fdText](int value) { + QTextBlockFormat fmt; + fmt.setAlignment((Qt::Alignment) value); + QTextCursor cursor = fdText->textCursor(); + cursor.mergeBlockFormat(fmt); + updImg(); + }); + + auto wTextAlignV = new QButtonGroup(wgtAttr); + wTextAlignV->addButton(wTextAlignVT, Qt::AlignTop); + wTextAlignV->addButton(wTextAlignVC, Qt::AlignVCenter); + wTextAlignV->addButton(wTextAlignVB, Qt::AlignBottom); + connect(wTextAlignV, &QButtonGroup::idClicked, this, [this](int value) { + m_attr.align = (Qt::Alignment) value; + updImg(); + }); + + auto v_align = m_attr.align & Qt::AlignVertical_Mask; + if(v_align==Qt::AlignTop) wTextAlignVT->setChecked(true); + if(v_align==Qt::AlignVCenter) wTextAlignVC->setChecked(true); + if(v_align==Qt::AlignBottom) wTextAlignVB->setChecked(true); + + fdText->setMinimumHeight(160); + auto doc = fdText->document(); + if(doc) doc->setDocumentMargin(2); + auto font = fdText->font(); + font.setFamilies({"Arial","黑体"}); + font.setPixelSize(16); + if(! gTextAntialiasing) font.setStyleStrategy(QFont::NoAntialias); + fdText->setFont(font); + auto pal = fdText->palette(); + pal.setColor(QPalette::Base, Qt::black); + pal.setColor(QPalette::Text, Qt::white); + fdText->setPalette(pal); + fdText->setFrameShape(QFrame::NoFrame); + fdText->setAcceptRichText(false); + fdText->setHtml(m_attr.text); + connect(fdText, &QTextEdit::textChanged, this, [this, fdText] { + m_attr.text = fdText->toHtml(); + updImg(); + }); + vBox->addWidget(fdText); + + hBox = new QHBoxLayout; + hBox->addStretch(); + + auto pageInfoWgt = new QWidget; + auto hhh = new QHBoxLayout(pageInfoWgt); + hhh->setContentsMargins(0,0,0,0); + + hhh->addWidget(new QLabel(tr("PageCount:"))); + + auto fdPageCnt = new QLabel(QString::number(mImgs.size())); + hhh->addWidget(fdPageCnt); + + hhh->addSpacing(20); + hhh->addWidget(new QLabel(tr("page"))); + + auto fdPageIdx = new QSpinBox(); + fdPageIdx->setRange(1, mImgs.size()); + connect(fdPageIdx, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int idx) { + curIdx = idx - 1; + update(); + }); + hhh->addWidget(fdPageIdx); + hBox->addWidget(pageInfoWgt); + + hBox->addStretch(); + + auto btnImport = new QPushButton(tr("Import txt File")); + btnImport->setProperty("ssType", "progManageTool"); + connect(btnImport, &QPushButton::clicked, fdText, [fdText] { + auto filePath = QFileDialog::getOpenFileName(gMainWin, tr("Select File"), gFileHome, "Txt(*.txt)"); + if(filePath.isEmpty()) return; + QFile file(filePath); + if(! file.open(QFile::ReadOnly)) { + QMessageBox::critical(gMainWin, tr("Fail"), tr("File Open Fail")); + return; + } + auto data = file.readAll(); + file.close(); + QTextCodec::ConverterState state; + QString text = QTextCodec::codecForName("UTF-8")->toUnicode(data.constData(), data.size(), &state); + if(state.invalidChars > 0) text = QString::fromLocal8Bit(data); + fdText->setText(text); + }); + hBox->addWidget(btnImport); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout; + hBox->addWidget(new QLabel(tr("Play Properties"))); + + line = new QFrame(); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + hBox->addWidget(line, 1); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout; + hBox->addStretch(); + + auto fdFlip = new QRadioButton(tr("Flip")); + hBox->addWidget(fdFlip); + hBox->addStretch(); + + auto fdScroll = new QRadioButton(tr("Scroll")); + hBox->addWidget(fdScroll); + hBox->addStretch(); + + auto fdStatic = new QRadioButton(tr("Static")); + hBox->addWidget(fdStatic); + hBox->addStretch(); + + vBox->addLayout(hBox); + + auto fdPlayStyle = new QButtonGroup(wgtAttr); + fdPlayStyle->addButton(fdFlip, EText::Flip); + fdPlayStyle->addButton(fdScroll, EText::Scroll); + fdPlayStyle->addButton(fdStatic, EText::Static); + if(m_attr.playMode==EText::Flip) fdFlip->setChecked(true); + else if(m_attr.playMode==EText::Scroll) fdScroll->setChecked(true); + else if(m_attr.playMode==EText::Static) fdStatic->setChecked(true); + + auto wgtAttrFlip = new QWidget(); + auto fdDur = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.flip.pageDuration * mImgs.size() * 1000)); + auto fdPageDur = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.flip.pageDuration * 1000)); + { + auto vBox = new QVBoxLayout(wgtAttrFlip); + vBox->setContentsMargins(2, 0, 2, 0); + vBox->setSpacing(3); + + hBox = new QHBoxLayout; + + auto label = new QLabel(tr("Play Duration")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + fdDur->setReadOnly(true); + fdDur->setButtonSymbols(QAbstractSpinBox::NoButtons); + fdDur->setDisplayFormat("H:mm:ss"); + fdDur->setStyleSheet("QTimeEdit{background-color:#ddd;}"); + hBox->addWidget(fdDur); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + + label = new QLabel(tr("Duration/Page")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + fdPageDur->setDisplayFormat("H:mm:ss"); + fdPageDur->setCurrentSection(QTimeEdit::SecondSection); + hBox->addWidget(fdPageDur); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + + label = new QLabel(tr("Entrance Effect")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto fdEff = new QComboBox(); + fdEff->addItem(tr("no"), "no"); + fdEff->addItem(tr("random"), "random"); + fdEff->addItem(tr("right to left"), "right to left"); + fdEff->addItem(tr("bottom to top"), "bottom to top"); + fdEff->addItem(tr("left to right"), "left to right"); + fdEff->addItem(tr("top to bottom"), "top to bottom"); + int idx = fdEff->findData(m_attr.flip.effect); + if(idx!=-1) fdEff->setCurrentIndex(idx); + connect(fdEff, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this, fdEff] { + m_attr.flip.effect = fdEff->currentData().toString(); + update(); + }); + hBox->addWidget(fdEff); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + + label = new QLabel(tr("Effect time")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto wEffectSpeed = new QSpinBox(); + wEffectSpeed->setValue(m_attr.flip.effectDuration); + hBox->addWidget(wEffectSpeed); + hBox->addWidget(new QLabel(tr("s"))); + hBox->addStretch(); + + vBox->addLayout(hBox); + vBox->addStretch(); + + connect(fdPageDur, &QTimeEdit::timeChanged, this, [this, wEffectSpeed, fdPageDur, fdDur](const QTime &time) { + int effDur = wEffectSpeed->value(); + int pageDur = time.msecsSinceStartOfDay()/1000; + if(pageDur < effDur) { + QMessageBox::warning(gMainWin, tr("Tip Info"), tr("Effect time cannot be longer than duration time")); + pageDur = effDur; + fdPageDur->setTime(QTime::fromMSecsSinceStartOfDay(pageDur*1000)); + fdPageDur->setFocus(); + } + m_attr.flip.pageDuration = pageDur; + fdDur->setTime(QTime::fromMSecsSinceStartOfDay(pageDur * mImgs.size() * 1000)); + }); + connect(wEffectSpeed, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this, wEffectSpeed, fdPageDur](int value) { + int pageDur = fdPageDur->time().msecsSinceStartOfDay()/1000; + if(value > pageDur) { + QMessageBox::warning(gMainWin, tr("Tip Info"), tr("Effect time cannot be longer than duration time")); + if(pageDur>1) value = pageDur-1; + else value = 0; + wEffectSpeed->setValue(value); + wEffectSpeed->setFocus(); + } + m_attr.flip.effectDuration = value; + }); + } + auto wgtAttrScroll = new QWidget(); + { + auto vBox = new QVBoxLayout(wgtAttrScroll); + vBox->setContentsMargins(2, 0, 2, 0); + vBox->setSpacing(3); + + auto hBox = new QHBoxLayout(); + + auto label = new QLabel(tr("Play Duration")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto timeEdit = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.scroll.duration*1000)); + timeEdit->setDisplayFormat("H:mm:ss"); + timeEdit->setCurrentSectionIndex(2); + connect(timeEdit, &QTimeEdit::timeChanged, this, [this](const QTime &time) { + m_attr.scroll.duration = time.msecsSinceStartOfDay()/1000; + }); + hBox->addWidget(timeEdit); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + + label = new QLabel(tr("Head-Tail Spacing")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto wHeadTailSpacing = new QSpinBox; + wHeadTailSpacing->setRange(0, 9999); + wHeadTailSpacing->setValue(m_attr.scroll.headTailSpacing); + connect(wHeadTailSpacing, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.scroll.headTailSpacing = value; + }); + hBox->addWidget(wHeadTailSpacing); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + + label = new QLabel(tr("Scroll Style")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto wRollingStyle = new QComboBox; + wRollingStyle->addItem(tr("Right -> Left")); + wRollingStyle->addItem(tr("Bottom -> Top")); + wRollingStyle->addItem(tr("Left -> Right")); + wRollingStyle->addItem(tr("Top -> Bottom")); + wRollingStyle->setCurrentIndex(m_attr.scroll.effect); + connect(wRollingStyle, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this](int index) { + m_attr.scroll.effect = index; + updImg(); + }); + hBox->addWidget(wRollingStyle); + hBox->addStretch(); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + + label = new QLabel(tr("Scroll Speed")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto wRollingSpeed = new QSpinBox(); + wRollingSpeed->setMaximum(9999); + wRollingSpeed->setValue(m_attr.scroll.effectSpeed); + connect(wRollingSpeed, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { + m_attr.scroll.effectSpeed = value; + }); + hBox->addWidget(wRollingSpeed); + hBox->addStretch(); + + vBox->addLayout(hBox); + vBox->addStretch(); + } + auto wgtAttrStatic = new QWidget(); + { + auto vBox = new QVBoxLayout(wgtAttrStatic); + vBox->setContentsMargins(2, 0, 2, 0); + vBox->setSpacing(3); + + hBox = new QHBoxLayout(); + auto label = new QLabel(tr("Play Duration")); + label->setMinimumWidth(100); + hBox->addWidget(label); + + auto timeEdit = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.duration*1000)); + timeEdit->setDisplayFormat("H:mm:ss"); + timeEdit->setCurrentSectionIndex(2); + connect(timeEdit, &QTimeEdit::timeChanged, this, [this](const QTime &time) { + m_attr.duration = time.msecsSinceStartOfDay() / 1000; + }); + hBox->addWidget(timeEdit); + hBox->addStretch(); + + vBox->addLayout(hBox); + vBox->addStretch(); + } + auto stackBox = new QStackedLayout; + vBox->addLayout(stackBox); + stackBox->addWidget(wgtAttrFlip); + stackBox->addWidget(wgtAttrScroll); + stackBox->addWidget(wgtAttrStatic); + stackBox->setCurrentIndex(m_attr.playMode); + connect(fdPlayStyle, &QButtonGroup::idToggled, this, [this, stackBox, pageInfoWgt](int value, bool checked) { + if(! checked) return; + m_attr.playMode = value; + updImg(); + stackBox->setCurrentIndex(value); + pageInfoWgt->setVisible(value==Flip); + }); + connect(this, &EText::updPageCnt, wgtAttr, [this, fdPageCnt, fdPageIdx, fdPageDur, fdDur] { + fdPageCnt->setText(QString::number(mImgs.size())); + fdPageIdx->setRange(1, mImgs.size()); + fdPageIdx->setValue(1); + fdDur->setTime(QTime::fromMSecsSinceStartOfDay(fdPageDur->time().msecsSinceStartOfDay() * mImgs.size())); + }); + return wgtAttr; +} + +bool EText::save(const QString &pageDir) { + QString idDir = pageDir + QString("/%1-%2-%3-%4-%5").arg(zValue()).arg((int)x()).arg((int)y()).arg((int)mWidth).arg((int)mHeight); + QDir(idDir).mkdir("."); + for(int i=0; isave(); + auto rect = innerRect(); + if(m_attr.playMode!=EText::Flip) curIdx = 0; + else if(curIdx>=mImgs.size()) curIdx = mImgs.size() - 1; + else if(curIdx < 0) curIdx = 0; + if(m_attr.playMode==EText::Scroll) painter->drawImage(rect.x(), rect.y(), mImgs[0], 0, 0, rect.width(), rect.height()); + else painter->drawImage(rect.x(), rect.y(), mImgs[curIdx]); + painter->restore(); + EBase::paint(painter, option, widget); +} + +void EText::updImg() { + auto innerRect = this->innerRect(); + int width = innerRect.width(); + int height = innerRect.height(); + if(width<1 || height<1) return; + QTextDocument doc; + doc.setDocumentMargin(0); + QFont font; + font.setFamilies({"Arial","黑体"}); + font.setPixelSize(16); + if(! gTextAntialiasing) font.setStyleStrategy(QFont::NoAntialias); + doc.setDefaultFont(font); + doc.setDefaultStyleSheet("body {color: #fff;}"); + doc.setHtml(m_attr.text); + if(m_attr.playMode==EText::Flip) { + doc.setPageSize(innerRect.size()); + auto pageHeight = height; + auto pageCnt = doc.pageCount(); + QImage img(width, pageHeight*pageCnt, QImage::Format_ARGB32); + img.fill(m_attr.backColor); + { + QPainter painter(&img); + doc.drawContents(&painter); + } + if(pageCnt > 1) { + check: + for(int y=pageHeight-1; y 1) { + for(int y=img.height()-pageHeight; yss; ee--) for(int i=0; i=0; ee--) for(int i=0; i mImgs; + int curIdx{0}; +}; + +#endif // ETEXT_H diff --git a/LedOK/wProgramManager/etimer.cpp b/LedOK/program/etimer.cpp similarity index 89% rename from LedOK/wProgramManager/etimer.cpp rename to LedOK/program/etimer.cpp index 7cce05c..3163e32 100644 --- a/LedOK/wProgramManager/etimer.cpp +++ b/LedOK/program/etimer.cpp @@ -15,7 +15,7 @@ #include #include #include - +#include ETimer::ETimer(EBase *multiWin) : EBase(multiWin) { mType = EBase::Timer; @@ -243,48 +243,33 @@ QWidget* ETimer::attrWgt() { hBox = new QHBoxLayout(); hBox->addSpacing(6); - auto fdFontBold = new QPushButton(); - fdFontBold->setChecked(attr.font.bold()); + auto fdFontBold = new QPushButton("B"); + fdFontBold->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-weight: bold;} QPushButton:checked{background: #29c; color: #fff;}"); fdFontBold->setFixedSize(30, 30); - QIcon icon; - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontBold_u.png"), QSize(), QIcon::Normal, QIcon::Off); - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontBold_s.png"), QSize(), QIcon::Normal, QIcon::On); - fdFontBold->setIcon(icon); - fdFontBold->setIconSize(QSize(30, 30)); fdFontBold->setCheckable(true); - fdFontBold->setFlat(true); + fdFontBold->setChecked(attr.font.bold()); connect(fdFontBold, &QCheckBox::toggled, this, [this](bool checked) { attr.font.setBold(checked); update(); }); hBox->addWidget(fdFontBold); - auto fdFontItalic = new QPushButton(); - fdFontItalic->setChecked(attr.font.italic()); + auto fdFontItalic = new QPushButton("I"); + fdFontItalic->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; font-style: italic;} QPushButton:checked{background: #29c; color: #fff;}"); fdFontItalic->setFixedSize(30, 30); - icon = QIcon(); - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontItalics_u.png"), QSize(), QIcon::Normal, QIcon::Off); - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontItalics_s.png"), QSize(), QIcon::Normal, QIcon::On); - fdFontItalic->setIcon(icon); - fdFontItalic->setIconSize(QSize(30, 30)); fdFontItalic->setCheckable(true); - fdFontItalic->setFlat(true); + fdFontItalic->setChecked(attr.font.italic()); connect(fdFontItalic, &QCheckBox::toggled, this, [this](bool checked) { attr.font.setItalic(checked); update(); }); hBox->addWidget(fdFontItalic); - auto fdFontUnderline = new QPushButton(); - fdFontUnderline->setChecked(attr.font.underline()); + auto fdFontUnderline = new QPushButton("U"); + fdFontUnderline->setStyleSheet("QPushButton{background: #bbb; color: #888; font-size: 20px; text-decoration: underline;} QPushButton:checked{background: #29c; color: #fff;}"); fdFontUnderline->setFixedSize(30, 30); - icon = QIcon(); - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontUnderline_u.png"), QSize(), QIcon::Normal, QIcon::Off); - icon.addFile(QString::fromUtf8(":/res/ProgramManager/EditProgram/FontUnderline_s.png"), QSize(), QIcon::Normal, QIcon::On); - fdFontUnderline->setIcon(icon); - fdFontUnderline->setIconSize(QSize(30, 30)); fdFontUnderline->setCheckable(true); - fdFontUnderline->setFlat(true); + fdFontUnderline->setChecked(attr.font.underline()); connect(fdFontUnderline, &QCheckBox::toggled, this, [this](bool checked) { attr.font.setUnderline(checked); update(); diff --git a/LedOK/wProgramManager/etimer.h b/LedOK/program/etimer.h similarity index 100% rename from LedOK/wProgramManager/etimer.h rename to LedOK/program/etimer.h diff --git a/LedOK/wProgramManager/evideo.cpp b/LedOK/program/evideo.cpp similarity index 94% rename from LedOK/wProgramManager/evideo.cpp rename to LedOK/program/evideo.cpp index abd6e27..916b5f3 100644 --- a/LedOK/wProgramManager/evideo.cpp +++ b/LedOK/program/evideo.cpp @@ -2,6 +2,7 @@ #include "cfg.h" #include "tools.h" #include "base/waitingdlg.h" +#include "base/ffutil.h" #include "videosplitthread.h" #include #include @@ -14,7 +15,7 @@ EVideo *EVideo::create(const QString &file, PageListItem *pageItem, EBase *multi int64_t dur; AVCodecID codecId; QImage img; - QString err = Tools::videoInfo(file.toUtf8(), img, &dur, &codecId); + QString err = videoInfo(file.toUtf8(), img, &dur, &codecId); if(! err.isEmpty()) { QMessageBox::critical(gMainWin, "Video Error", err+"\n"+file); return 0; @@ -38,7 +39,7 @@ EVideo *EVideo::create(const QJsonObject &json, PageListItem *pageItem, EBase *m else return nullptr; int64_t dur; QImage img; - QString err = Tools::videoInfo(file.toUtf8(), img, &dur, 0); + QString err = videoInfo(file.toUtf8(), img, &dur, 0); if(! err.isEmpty()) return nullptr; auto ins = new EVideo(dir, name, widget["pathRaw"].toString(), widget["fileRaw"].toString(), img, dur/1000000, pageItem, multiWin); ins->setBaseAttr(json); @@ -52,7 +53,7 @@ QJsonObject EVideo::genProg(const QJsonObject &ele, const QString &dstDir, ProgI auto widget = ele["widget"]; auto path = widget["path"].toString(); auto name = widget["file"].toString(); - if(progItem->mSplitWidth) name += "-square.mp4"; + if(progItem->mMaxWidth) name += "-square.mp4"; QString srcFile = path + "/" + name; QFileInfo srcInfo(srcFile); if(! srcInfo.isFile()) return QJsonObject(); @@ -175,7 +176,7 @@ QWidget* EVideo::attrWgt() { QFileInfo rawInfo(rawFile); int64_t dur; AVCodecID codecId; - QString err = Tools::videoInfo(rawFile.toUtf8(), mCoverImg, &dur, &codecId); + QString err = videoInfo(rawFile.toUtf8(), mCoverImg, &dur, &codecId); if(! err.isEmpty()) { QMessageBox::critical(gMainWin, "Video Error", err+"\n"+rawFile); return; @@ -228,10 +229,9 @@ bool EVideo::save(const QString &pageDir) { else return false; QFile(oldFile).copy(saveFile); mDir = pageDir; - if(gProgItem->mSplitWidth) { - int cnt = (gProgItem->mWidth+gProgItem->mSplitWidth-1) / gProgItem->mSplitWidth; + if(gProgItem->mMaxWidth) { auto waitingDlg = new WaitingDlg(gProgEditorWin, "正在转码视频 ..."); - auto thread = new VideoSplitThread(mWidth, mHeight, gProgItem->mSplitWidth, gProgItem->mHeight*cnt, cnt, pos(), saveFile.toUtf8()); + auto thread = new VideoSplitThread(mWidth, mHeight, gProgItem->mMaxWidth, gProgItem->mHeight, gProgItem->mSplitWidths, pos(), saveFile.toUtf8()); connect(thread, &VideoSplitThread::emErr, this, [saveFile, waitingDlg](QString err) { waitingDlg->close(); if(! err.isEmpty()) QMessageBox::critical(gProgEditorWin, "Video trans error", err+"\n"+saveFile); @@ -264,9 +264,9 @@ QJsonObject EVideo::attrJson() const { QString EVideo::transcoding(QString rawFile, QString rawName, QString dir, int w, int h, AVCodecID codec_id) { QSettings settings; - int rawMin = qMin(w, h); - if(settings.value("VideoCompress", true).toBool() && rawMin > 768 && w > gProgItem->mWidth && h > gProgItem->mHeight) { - double rate = 720.0 / rawMin; + int rawMax = qMax(w, h); + if(settings.value("VideoCompress", true).toBool() && rawMax > 1360 && (w > gProgItem->mWidth || h > gProgItem->mHeight)) { + double rate = 1280.0 / rawMax; w *= rate; h *= rate; } else if(! settings.value("VideoTranscoding", true).toBool() || codec_id == AV_CODEC_ID_H264) { diff --git a/LedOK/wProgramManager/evideo.h b/LedOK/program/evideo.h similarity index 100% rename from LedOK/wProgramManager/evideo.h rename to LedOK/program/evideo.h diff --git a/LedOK/wProgramManager/eweb.cpp b/LedOK/program/eweb.cpp similarity index 98% rename from LedOK/wProgramManager/eweb.cpp rename to LedOK/program/eweb.cpp index a61cb5a..1a4b6de 100644 --- a/LedOK/wProgramManager/eweb.cpp +++ b/LedOK/program/eweb.cpp @@ -1,5 +1,5 @@ #include "eweb.h" -#include "wProgramManager/progeditorwin.h" +#include "program/progeditorwin.h" #include #include #include diff --git a/LedOK/wProgramManager/eweb.h b/LedOK/program/eweb.h similarity index 87% rename from LedOK/wProgramManager/eweb.h rename to LedOK/program/eweb.h index 2316a17..7b08a96 100644 --- a/LedOK/wProgramManager/eweb.h +++ b/LedOK/program/eweb.h @@ -8,7 +8,7 @@ class EWeb : public EBase { Q_OBJECT public: static const QImage &holder() { - static const QImage holder = QImage(":/res/ProgramManager/EditProgram/Web.png"); + static const QImage holder = QImage(":/res/program/Web.png"); return holder; } diff --git a/LedOK/wProgramManager/gentmpthread.cpp b/LedOK/program/gentmpthread.cpp similarity index 78% rename from LedOK/wProgramManager/gentmpthread.cpp rename to LedOK/program/gentmpthread.cpp index 2893530..b6835db 100644 --- a/LedOK/wProgramManager/gentmpthread.cpp +++ b/LedOK/program/gentmpthread.cpp @@ -2,19 +2,24 @@ #include "cfg.h" #include "globaldefine.h" #include "tools.h" -#include "wProgramManager/eaclock.h" -#include "wProgramManager/eaudio.h" -#include "wProgramManager/edclock.h" -#include "wProgramManager/eenviron.h" -#include "wProgramManager/egif.h" -#include "wProgramManager/etext.h" -#include "wProgramManager/etimer.h" -#include "wProgramManager/evideo.h" +#include "program/eaclock.h" +#include "program/eaudio.h" +#include "program/edclock.h" +#include "program/eenviron.h" +#include "program/egif.h" +#include "program/etext.h" +#include "program/etimer.h" +#include "program/evideo.h" #include #include #include +#include GenTmpThread::GenTmpThread(ProgItem *progItem, const QString &prog_name, const QString &zip_file, const QString &password, QObject *parent) : QThread(parent), mProgItem(progItem), prog_name(prog_name), zip_file(zip_file), password(password) { + connect(this, &QThread::finished, this, &QThread::deleteLater); + connect(this, &GenTmpThread::onErr, this, [](QString err) { + QMessageBox::warning(gMainWin, "GenTmpThread Error", err); + }); } void GenTmpThread::run() { @@ -22,18 +27,32 @@ void GenTmpThread::run() { dstDir = srcDir + "_tmp"; //清空目录 emit sProgress(tr("Preparing ..."), 0); - QDir rootDir(programsDir()); - rootDir.remove(prog_name + "_tmp.zip"); + QDir progsDir(programsDir()); + progsDir.remove(prog_name + "_tmp.zip"); QDir dstQDir(dstDir); if(! dstQDir.exists() || dstQDir.removeRecursively()) { int iReTryCount = 0; - while(!rootDir.mkdir(prog_name + "_tmp")) { + while(!progsDir.mkdir(prog_name + "_tmp")) { QThread::msleep(250); iReTryCount++; if(iReTryCount > 4) break; } } + QFile jsonFile(srcDir+"/pro.json"); + if(! jsonFile.open(QIODevice::ReadOnly)) { + onErr("Can't open "+srcDir+"/pro.json"); + return; + } + auto data = jsonFile.readAll(); + jsonFile.close(); + QJsonParseError error; + auto proJson = QJsonDocument::fromJson(data, &error); + if(error.error != QJsonParseError::NoError) { + onErr("Parse "+srcDir+"/pro.json Error: "+error.errorString()); + return; + } + //扫描节目, 返回多个节目数组 emit sProgress(tr("Scan program ..."), 30); QStringList pageNames = QDir(srcDir).entryList(QDir::Dirs | QDir::NoDotAndDotDot); @@ -42,20 +61,21 @@ void GenTmpThread::run() { QList pageJsons; foreach(QString pageName, pageNames) { QFile jsonFile(srcDir+"/"+pageName+"/page.json"); - if(jsonFile.open(QIODevice::ReadOnly)){ - QJsonDocument pageJson = QJsonDocument::fromJson(jsonFile.readAll()); + if(jsonFile.open(QIODevice::ReadOnly)) { + auto data = jsonFile.readAll(); jsonFile.close(); - pageJsons.append(pageJson); + auto pageJson = QJsonDocument::fromJson(data, &error); + if(error.error == QJsonParseError::NoError) pageJsons.append(pageJson); } } - //根据order排序 std::sort(pageJsons.begin(), pageJsons.end(), [](const QJsonDocument &a, const QJsonDocument &b) { return a["order"].toInt() < b["order"].toInt(); }); + QJsonArray items; foreach(QJsonDocument pageJson, pageJsons) { srcPageDir = srcDir + "/" + pageJson["name"].toString(); - items.append(cvtPage(pageJson)); + items.append(cvtPage(pageJson, proJson)); } emit sProgress(tr("Create json ..."), 60); @@ -85,8 +105,9 @@ void GenTmpThread::run() { } //此处需要把幻灯片中的元素按层顺序排序,再放入layers中,每个元素对一个layer。ewindow中的多个顺序元素为一个层上的时间轴上的素材 -QJsonObject GenTmpThread::cvtPage(const QJsonDocument &pageJson) { +QJsonObject GenTmpThread::cvtPage(const QJsonDocument &pageJson, const QJsonDocument &proJson) { auto audios = pageJson["audios"].toArray(); + auto sourceRepeat = pageJson["loop"].toBool(); QJsonArray sources; int start = 0; foreach(auto audio, audios) { @@ -119,7 +140,7 @@ QJsonObject GenTmpThread::cvtPage(const QJsonDocument &pageJson) { start += dur; } QJsonArray layers; - if(! sources.isEmpty()) layers.append(QJsonObject{{"repeat", true}, {"sources", sources}}); + if(! sources.isEmpty()) layers.append(QJsonObject{{"repeat", sourceRepeat}, {"sources", sources}}); auto elements = pageJson["elements"].toArray(); foreach(auto ele, elements) { @@ -152,24 +173,23 @@ QJsonObject GenTmpThread::cvtPage(const QJsonDocument &pageJson) { } else { QJsonObject source = cvtEle(type, ele.toObject()); if(! source.isEmpty()) { - if(mProgItem->mSplitWidth==0) { + if(mProgItem->mMaxWidth && (type=="Photo" || type=="Movie")) { + source["left"] = 0; + source["top"] = 0; + source["width"] = mProgItem->mMaxWidth; + source["height"] = mProgItem->mHeight * mProgItem->mSplitWidths.size(); + } else { source["left"] = geometry["x"]; source["top"] = geometry["y"]; source["width"] = geometry["w"]; source["height"] = geometry["h"]; - } else { - source["left"] = 0; - source["top"] = 0; - source["width"] = mProgItem->mSplitWidth; - int cnt = (gProgItem->mWidth+gProgItem->mSplitWidth-1) / gProgItem->mSplitWidth; - source["height"] = mProgItem->mHeight*cnt; } source["playTime"] = 0; sources.append(source); } } if(! sources.isEmpty()) { - QJsonObject layer{{"repeat", false}, {"sources", sources}}; + QJsonObject layer{{"repeat", sourceRepeat}, {"sources", sources}}; auto border = ele["border"].toString(); if(! border.isEmpty()) { QString bdSrc = ":res/borders/"+border; @@ -225,7 +245,6 @@ QJsonObject GenTmpThread::cvtPage(const QJsonDocument &pageJson) { schedules.append(schedule); } } - return QJsonObject{ {"_id", QUuid::createUuid().toString(QUuid::WithoutBraces)}, {"priority", 0}, @@ -235,8 +254,9 @@ QJsonObject GenTmpThread::cvtPage(const QJsonDocument &pageJson) { {"_id", QUuid::createUuid().toString(QUuid::WithoutBraces)}, {"totalSize", 0}, {"name", pageJson["name"].toString()}, - {"width", pageJson["resolution"]["w"]}, - {"height", pageJson["resolution"]["h"]}, + {"width", proJson["resolution"]["w"]}, + {"height", proJson["resolution"]["h"]}, + {"splitWidths", proJson["splitWidths"]}, {"_company", "alahover"}, {"_department", "alahover"}, {"_role", "alahover"}, @@ -266,17 +286,28 @@ QJsonObject GenTmpThread::cvtEle(const QString &type, const QJsonObject &ele) { QJsonObject GenTmpThread::convertText(const QJsonObject &json) { EText::Data attr; EText::setElement(json, attr); - QJsonObject oRes; - oRes["_type"] = "MultiPng"; - oRes["name"] = "MultiPng"; - oRes["id"] = res_id++; - //把["widget"]["files"]字段的数组转成[{"text0.png","move up"}] + QJsonObject source; + auto type = mProgItem->mMaxWidth ? "SplitText" : "MultiPng"; + source["_type"] = type; + source["name"] = type; + source["id"] = res_id++; auto widget = json["widget"]; QJsonArray srcFiles = widget["files"].toArray(); - oRes["iPicCount"] = srcFiles.count(); + source["iPicCount"] = srcFiles.size(); + if(attr.playMode==EText::Flip) { + source["playMode"] = "Flip"; + source["timeSpan"] = attr.flip.pageDuration * srcFiles.size(); + if(attr.flip.effectDuration >= attr.flip.pageDuration) attr.flip.effectDuration = attr.flip.pageDuration / 2; + } else if(attr.playMode==EText::Scroll) { + source["playMode"] = "Scroll"; + source["timeSpan"] = attr.scroll.duration; + } else if(attr.playMode==EText::Static) { + source["playMode"] = "Static"; + source["timeSpan"] = attr.duration; + } QJsonArray arrayPics; QString filePrefix = srcPageDir+"/"+widget["idDir"].toString()+"/"; - for(int i=0; i=attr.turning.pageDuration) attr.turning.effectDuration=attr.turning.pageDuration/2; - arrayPic["effectSpeed"]=attr.turning.effectDuration; - arrayPic["picDuration"]=attr.turning.pageDuration; - break; - case EText::Scroll: - if(attr.rolling.rollingStyle==0) arrayPic["effect"] = "right to left"; - else if(attr.rolling.rollingStyle==1) arrayPic["effect"] = "bottom to top"; - else if(attr.rolling.rollingStyle==2) arrayPic["effect"] = "left to right"; - else if(attr.rolling.rollingStyle==3) arrayPic["effect"] = "top to bottom"; - oRes["timeSpan"] = attr.rolling.playDuration; - arrayPic["effectSpeed"] = attr.rolling.rollingSpeed; + if(attr.playMode==EText::Flip) { + arrayPic["effect"] = attr.flip.effect; + arrayPic["effectSpeed"] = attr.flip.effectDuration; + arrayPic["picDuration"] = attr.flip.pageDuration; + } else if(attr.playMode==EText::Scroll) { + if(attr.scroll.effect==0) arrayPic["effect"] = "right to left"; + else if(attr.scroll.effect==1) arrayPic["effect"] = "bottom to top"; + else if(attr.scroll.effect==2) arrayPic["effect"] = "left to right"; + else if(attr.scroll.effect==3) arrayPic["effect"] = "top to bottom"; + arrayPic["effectSpeed"] = attr.scroll.effectSpeed; arrayPic["picDuration"] = 0; - break; - case EText::Static: - arrayPic["effect"]="no"; - oRes["timeSpan"] = attr.playDuration; - arrayPic["effectSpeed"]=0; - arrayPic["picDuration"]=attr.playDuration; - break; - //转换成plainText - default: break; + } else if(attr.playMode==EText::Static) { + arrayPic["effect"] = "no"; + arrayPic["effectSpeed"] = 0; + arrayPic["picDuration"] = attr.duration; } arrayPics.append(arrayPic); } - oRes["arrayPics"] = arrayPics; - return oRes; + source["arrayPics"] = arrayPics; + return source; } //转换图片 QJsonObject GenTmpThread::convertPhoto(const QJsonObject &ele){ @@ -325,7 +345,7 @@ QJsonObject GenTmpThread::convertPhoto(const QJsonObject &ele){ QFileInfo srcInfo(srcFile); QJsonObject source; if(! srcInfo.isFile()) return source; - if(mProgItem->mSplitWidth) { + if(mProgItem->mMaxWidth) { srcFile += "-square.png"; auto md5 = Tools::fileMd5(srcFile); if(md5.isEmpty()) return source; @@ -488,11 +508,11 @@ QJsonObject GenTmpThread::convertAClock(const QJsonObject &json) { oRes["mime"] = "image/png"; oRes["name"] = "001"; oRes["timeSpan"] = json["play"]["duration"]; - oRes["shade"] = 0;//表盘形状 - oRes["opacity"] = 1;//透明度 - oRes["showBg"] = false;//是否显示背景色 - oRes["bgColor"] = 0; - oRes["showHourScale"] = false;//是否显示时针 + oRes["shade"] = 0;//表盘形状 + oRes["opacity"] = 1;//透明度 + oRes["showBg"] = false;//是否显示背景色 + oRes["bgColor"] = 0; + oRes["showHourScale"] = false;//是否显示时针 auto color = widget["hourMarkColor"]; oRes["scaleHourColor"] = color.isString() ? color : Tools::int2Color(color.toInt()).name(); color = widget["minMarkColor"]; @@ -503,12 +523,17 @@ QJsonObject GenTmpThread::convertAClock(const QJsonObject &json) { oRes["pinMinColor"] = color.isString() ? color : Tools::int2Color(color.toInt()).name(); color = widget["secHandColor"]; oRes["pinSecColor"] = color.isString() ? color : Tools::int2Color(color.toInt()).name(); - + oRes["pinHourLen"] = widget["hhLen"].toInt(); + oRes["pinMinLen"] = widget["mhLen"].toInt(); + oRes["pinSecLen"] = widget["shLen"].toInt(); + oRes["pinHourWidth"] = widget["hhWidth"].toInt(); + oRes["pinMinWidth"] = widget["mhWidth"].toInt(); + oRes["pinSecWidth"] = widget["shWidth"].toInt(); oRes["showMinScale"] = false; oRes["scaleStyle"] = 0; oRes["showScaleNum"] = false; oRes["pinStyle"] = 1; - oRes["showSecond"] = true; + oRes["showSecond"] = widget["showSecHand"]; //下同Video oRes["entryEffect"] = "None"; oRes["exitEffect"] = "None"; @@ -564,26 +589,32 @@ QJsonObject GenTmpThread::convertTimer(const QJsonObject &json) { Tools::saveImg(dstDir, metric, font, color, imgs, tr("hour"), "hour"); Tools::saveImg(dstDir, metric, font, color, imgs, tr("min"), "min"); Tools::saveImg(dstDir, metric, font, color, imgs, tr("sec"), "sec"); - auto innerW = json["innerW"].toInt(); - auto innerH = json["innerH"].toInt(); - auto rect = metric.boundingRect(0, 0, innerW, innerH, Qt::AlignCenter | Qt::TextWordWrap, text); - QImage img(qMin(rect.width(), innerW), qMin(rect.height(), innerH), QImage::Format_ARGB32); - img.fill(Qt::transparent); - QPainter painter(&img); - painter.setFont(font); - painter.setPen(color); - painter.drawText(QRectF(0, 0, img.width(), img.height()), text, QTextOption(Qt::AlignCenter)); - QBuffer buf; - if(img.save(&buf, "PNG")) { - QCryptographicHash cryptoHash(QCryptographicHash::Md5); - cryptoHash.addData(buf.data()); - auto md5 = QString::fromLatin1(cryptoHash.result().toHex()); - QFile file(dstDir+"/"+md5); - if(file.open(QFile::WriteOnly)) { - file.write(buf.data()); - file.close(); - imgs.insert("text", md5); + if(! text.isEmpty()) { + auto innerW = json["innerW"].toInt(); + auto innerH = json["innerH"].toInt(); + auto rect = metric.boundingRect(0, 0, innerW, innerH, Qt::AlignCenter | Qt::TextWordWrap, text); + QImage img(qMin(rect.width(), innerW), qMin(rect.height(), innerH), QImage::Format_ARGB32); + img.fill(Qt::transparent); + { + QPainter painter(&img); + painter.setFont(font); + painter.setPen(color); + painter.drawText(QRectF(0, 0, img.width(), img.height()), text, QTextOption(Qt::AlignCenter)); } + QByteArray data; + QBuffer buffer(&data); + buffer.open(QIODevice::WriteOnly); + if(img.save(&buffer, "PNG")) { + QCryptographicHash cryptoHash(QCryptographicHash::Md5); + cryptoHash.addData(data); + auto md5 = QString::fromLatin1(cryptoHash.result().toHex()); + QFile file(dstDir+"/"+md5); + if(file.open(QFile::WriteOnly)) { + file.write(data); + file.close(); + imgs.insert("text", md5); + } else emit onErr("convertTimer file.open false"); + } else emit onErr("convertTimer img.save false"); } oRes["imgs"] = imgs; return oRes; diff --git a/LedOK/wProgramManager/gentmpthread.h b/LedOK/program/gentmpthread.h similarity index 91% rename from LedOK/wProgramManager/gentmpthread.h rename to LedOK/program/gentmpthread.h index 0b83e3e..73e1bde 100644 --- a/LedOK/wProgramManager/gentmpthread.h +++ b/LedOK/program/gentmpthread.h @@ -12,7 +12,7 @@ public: protected: virtual void run() override; - QJsonObject cvtPage(const QJsonDocument &jProg); + QJsonObject cvtPage(const QJsonDocument &, const QJsonDocument &); QJsonObject cvtEle(const QString &type, const QJsonObject &json); QJsonObject convertText(const QJsonObject &json); QJsonObject convertPhoto(const QJsonObject &json); @@ -23,7 +23,7 @@ protected: QJsonObject convertTimer(const QJsonObject &json); signals: void sProgress(QString, int, bool = false); - + void onErr(QString); private: QString prog_name, dstDir, srcPageDir; QString zip_file, password; diff --git a/LedOK/wProgramManager/pageeditor.cpp b/LedOK/program/pageeditor.cpp similarity index 76% rename from LedOK/wProgramManager/pageeditor.cpp rename to LedOK/program/pageeditor.cpp index 6cc6447..5cedf72 100644 --- a/LedOK/wProgramManager/pageeditor.cpp +++ b/LedOK/program/pageeditor.cpp @@ -2,19 +2,19 @@ #include "cfg.h" #include "globaldefine.h" #include "tools.h" -#include "wProgramManager/eaclock.h" -#include "wProgramManager/eaudio.h" -#include "wProgramManager/ebase.h" -#include "wProgramManager/edclock.h" -#include "wProgramManager/eenviron.h" -#include "wProgramManager/egif.h" -#include "wProgramManager/emultiwin.h" -#include "wProgramManager/ephoto.h" -#include "wProgramManager/etext.h" -#include "wProgramManager/etimer.h" -#include "wProgramManager/evideo.h" -#include "wProgramManager/eweb.h" -#include "wProgramManager/pagelistitem.h" +#include "program/eaclock.h" +#include "program/eaudio.h" +#include "program/ebase.h" +#include "program/edclock.h" +#include "program/eenviron.h" +#include "program/egif.h" +#include "program/emultiwin.h" +#include "program/ephoto.h" +#include "program/etext.h" +#include "program/etimer.h" +#include "program/evideo.h" +#include "program/eweb.h" +#include "program/pagelistitem.h" #include #include #include @@ -30,7 +30,7 @@ PageEditor::PageEditor(QWidget *parent) : QWidget(parent) { toolBar->setStyleSheet("QToolBar{spacing: 2px;}"); toolBar->setIconSize(QSize(18, 18)); toolBar->addSeparator(); - auto actScaleUp = new QAction(QIcon(":/res/ProgramManager/EditProgram/ScaleUp.png"), tr("Zoom In")); + auto actScaleUp = new QAction(QIcon(":/res/program/ScaleUp.png"), tr("Zoom In")); toolBar->addAction(actScaleUp); //放大 connect(actScaleUp, &QAction::triggered, this, &PageEditor::onScaleUp); @@ -43,11 +43,11 @@ PageEditor::PageEditor(QWidget *parent) : QWidget(parent) { fdScale->setAlignment(Qt::AlignCenter); toolBar->addWidget(fdScale);//当前视图比例 - auto actScaleDown = new QAction(QIcon(":/res/ProgramManager/EditProgram/ScaleDown.png"), tr("Zoom Out")); + auto actScaleDown = new QAction(QIcon(":/res/program/ScaleDown.png"), tr("Zoom Out")); toolBar->addAction(actScaleDown);//缩小 connect(actScaleDown, &QAction::triggered, this, &PageEditor::onScaleDown); - QAction *actScaleOrg = new QAction(QIcon(":/res/ProgramManager/EditProgram/ScaleOrg.png"), tr("Original size")); + QAction *actScaleOrg = new QAction(QIcon(":/res/program/ScaleOrg.png"), tr("Original size")); connect(actScaleOrg, &QAction::triggered, this, [this] { curScale = 100; fdScale->setText("100"); @@ -56,22 +56,22 @@ PageEditor::PageEditor(QWidget *parent) : QWidget(parent) { toolBar->addAction(actScaleOrg);//1:1恢复视图 toolBar->addSeparator(); - QAction *actDelete = new QAction(QIcon(":/res/ProgramManager/EditProgram/Delete.png"), tr("Delete the secect media")); - QAction *actClean = new QAction(QIcon(":/res/ProgramManager/EditProgram/Clean.png"), tr("Clear all media")); - //QAction *actCut = new QAction(QIcon(":/res/ProgramManager/EditProgram/Cut.png"), tr("Cut media")); - QAction *actLayerUp = new QAction(QIcon(":/res/ProgramManager/EditProgram/LayerUp.png"), tr("Move layer up")); - QAction *actLayerDown = new QAction(QIcon(":/res/ProgramManager/EditProgram/LayerDown.png"), tr("Send backward")); - QAction *actLayerTop = new QAction(QIcon(":/res/ProgramManager/EditProgram/LayerTop.png"), tr("Bring to front")); - QAction *actLayerBottom = new QAction(QIcon(":/res/ProgramManager/EditProgram/LayerBottom.png"), tr("Move to the bottom layer")); - QAction *actTileFull = new QAction(QIcon(":/res/ProgramManager/EditProgram/TileFull.png"), tr("Fill the entire screen")); - QAction *actTileH = new QAction(QIcon(":/res/ProgramManager/EditProgram/TileH.png"), tr("Fill the screen horizontally")); - QAction *actTileV = new QAction(QIcon(":/res/ProgramManager/EditProgram/TileV.png"), tr("Fill the screen vertically")); - QAction *actArrayTop = new QAction(QIcon(":/res/ProgramManager/EditProgram/ArrayTop.png"), tr("Align top")); - QAction *actArrayHCenter = new QAction(QIcon(":/res/ProgramManager/EditProgram/ArrayHCenter.png"), tr("Center vertically")); - QAction *actArrayBottom = new QAction(QIcon(":/res/ProgramManager/EditProgram/ArrayBottom.png"), tr("Bottom align")); - QAction *actArrayLeft = new QAction(QIcon(":/res/ProgramManager/EditProgram/ArrayLeft.png"), tr("Align left")); - QAction *actArrayVCenter = new QAction(QIcon(":/res/ProgramManager/EditProgram/ArrayVCenter.png"), tr("Center horizontally")); - QAction *actArrayRight = new QAction(QIcon(":/res/ProgramManager/EditProgram/ArrayRight.png"), tr("Align right")); + QAction *actDelete = new QAction(QIcon(":/res/program/Delete.png"), tr("Delete the secect media")); + QAction *actClean = new QAction(QIcon(":/res/program/Clean.png"), tr("Clear all media")); + //QAction *actCut = new QAction(QIcon(":/res/program/Cut.png"), tr("Cut media")); + QAction *actLayerUp = new QAction(QIcon(":/res/program/LayerUp.png"), tr("Move layer up")); + QAction *actLayerDown = new QAction(QIcon(":/res/program/LayerDown.png"), tr("Send backward")); + QAction *actLayerTop = new QAction(QIcon(":/res/program/LayerTop.png"), tr("Bring to front")); + QAction *actLayerBottom = new QAction(QIcon(":/res/program/LayerBottom.png"), tr("Move to the bottom layer")); + QAction *actTileFull = new QAction(QIcon(":/res/program/TileFull.png"), tr("Fill the entire screen")); + QAction *actTileH = new QAction(QIcon(":/res/program/TileH.png"), tr("Fill the screen horizontally")); + QAction *actTileV = new QAction(QIcon(":/res/program/TileV.png"), tr("Fill the screen vertically")); + QAction *actArrayTop = new QAction(QIcon(":/res/program/ArrayTop.png"), tr("Align top")); + QAction *actArrayHCenter = new QAction(QIcon(":/res/program/ArrayHCenter.png"), tr("Center vertically")); + QAction *actArrayBottom = new QAction(QIcon(":/res/program/ArrayBottom.png"), tr("Bottom align")); + QAction *actArrayLeft = new QAction(QIcon(":/res/program/ArrayLeft.png"), tr("Align left")); + QAction *actArrayVCenter = new QAction(QIcon(":/res/program/ArrayVCenter.png"), tr("Center horizontally")); + QAction *actArrayRight = new QAction(QIcon(":/res/program/ArrayRight.png"), tr("Align right")); toolBar->addAction(actDelete); toolBar->addAction(actClean); toolBar->addSeparator(); @@ -169,7 +169,7 @@ void PageEditor::onScaleDown() { } void PageEditor::onDelete() { auto scene = graphicsView->scene(); - if(nullptr == scene) return; + if(0==scene) return; auto selectedItems = scene->selectedItems(); if(selectedItems.count() == 0) return; foreach(QGraphicsItem *selectedItem, selectedItems) if(selectedItem->type() >= QGraphicsItem::UserType) { diff --git a/LedOK/wProgramManager/pageeditor.h b/LedOK/program/pageeditor.h similarity index 100% rename from LedOK/wProgramManager/pageeditor.h rename to LedOK/program/pageeditor.h diff --git a/LedOK/wProgramManager/pagelistitem.cpp b/LedOK/program/pagelistitem.cpp similarity index 91% rename from LedOK/wProgramManager/pagelistitem.cpp rename to LedOK/program/pagelistitem.cpp index ebba2f7..8c56443 100644 --- a/LedOK/wProgramManager/pagelistitem.cpp +++ b/LedOK/program/pagelistitem.cpp @@ -1,25 +1,27 @@ #include "pagelistitem.h" #include "cfg.h" #include "tools.h" -#include "wProgramManager/wplanlist.h" +#include "base/ffutil.h" +#include "program/wplanlist.h" #include "base/lodateselector.h" -#include "wProgramManager/ebase.h" -#include "wProgramManager/etext.h" -#include "wProgramManager/ephoto.h" -#include "wProgramManager/evideo.h" -#include "wProgramManager/eaudio.h" -#include "wProgramManager/egif.h" -#include "wProgramManager/edclock.h" -#include "wProgramManager/eaclock.h" -#include "wProgramManager/eenviron.h" -#include "wProgramManager/eweb.h" -#include "wProgramManager/etimer.h" -#include "wProgramManager/emultiwin.h" +#include "program/ebase.h" +#include "program/etext.h" +#include "program/ephoto.h" +#include "program/evideo.h" +#include "program/eaudio.h" +#include "program/egif.h" +#include "program/edclock.h" +#include "program/eaclock.h" +#include "program/eenviron.h" +#include "program/eweb.h" +#include "program/etimer.h" +#include "program/emultiwin.h" #include "globaldefine.h" #include #include #include #include +#include #include #include @@ -38,19 +40,19 @@ PageListItem::PageListItem(const QJsonObject &attr, const QString &pageDir) : mA auto elements = mAttr["elements"].toArray(); foreach(auto ele, elements) { QString type = ele["elementType"].toString(); - EBase *element = nullptr; + EBase *element = 0; if(type=="Text") element = new EText(ele.toObject()); else if(type=="Photo") element = EPhoto::create(ele.toObject(), this); else if(type=="Gif") element = EGif::create(ele.toObject(), this); else if(type=="Movie") element = EVideo::create(ele.toObject(), this); else if(type=="Audio") element = EAudio::create(ele.toObject(), this); - else if(type=="DClock") element = new eDClock(ele.toObject()); - else if(type=="AClock") element = new eAClock(ele.toObject()); + else if(type=="DClock") element = new EDClock(ele.toObject()); + else if(type=="AClock") element = new EAClock(ele.toObject()); else if(type=="Temp") element = new EEnviron(ele.toObject()); else if(type=="Web") element = new EWeb(ele.toObject()); else if(type=="Timer") element = new ETimer(ele.toObject()); else if(type=="Window") element = new EMultiWin(ele.toObject(), this); - if(element!=nullptr) mScene->addItem(element); + if(element) mScene->addItem(element); } } @@ -160,17 +162,17 @@ QPushButton:hover { } QPushButton#bnAddPlan { - image: url(:/res/ProgramManager/EditProgram/AddPlan.png); + image: url(:/res/program/AddPlan.png); width: 24; height: 24; } QPushButton#bnClearPlan { - image: url(:/res/ProgramManager/EditProgram/Clean.png); + image: url(:/res/program/Clean.png); width: 24; height: 24; } QPushButton#bnDel { - image: url(:/res/ProgramManager/EditProgram/Delete.png); + image: url(:/res/program/Delete.png); width: 18; height: 18; } @@ -238,6 +240,15 @@ QPushButton[ssName="weeklySelector"]:checked { this->fdPlayTimes->setText(QString::number(value)); }); hBox->addWidget(fdPlayTimes); + hBox->addSpacing(20); + + auto fdLoop = new QCheckBox(tr("Sources Repeat")); + fdLoop->setChecked(mAttr["loop"].toBool()); + connect(fdLoop, &QCheckBox::toggled, this, [this](bool checked) { + mAttr["loop"] = checked; + }); + hBox->addWidget(fdLoop); + hBox->addStretch(); vBox->addLayout(hBox); @@ -249,7 +260,7 @@ QPushButton[ssName="weeklySelector"]:checked { hBox = new QHBoxLayout(); auto lb = new QLabel(); - lb->setPixmap(QPixmap(":/res/ProgramManager/EditProgram/Audio.png").scaledToHeight(24, Qt::SmoothTransformation)); + lb->setPixmap(QPixmap(":/res/program/Audio.png").scaledToHeight(24, Qt::SmoothTransformation)); hBox->addWidget(lb); hBox->addWidget(new QLabel(tr("Audios"))); hBox->addStretch(); @@ -261,7 +272,7 @@ QPushButton[ssName="weeklySelector"]:checked { hBox->addStretch(); auto btnAdd = new QPushButton(); - btnAdd->setIcon(QIcon(":/res/ProgramManager/EditProgram/Add.png")); + btnAdd->setIcon(QIcon(":/res/program/Add.png")); btnAdd->setProperty("style","multiTool"); mAudiosList = new QListWidget(); @@ -270,14 +281,14 @@ QPushButton[ssName="weeklySelector"]:checked { int durs = fdTtlDur->text().toInt(); for(int i=0; isetData(Qt::UserRole, QVariant::fromValue(info)); mAudiosList->addItem(item); if(i == files.count()-1) { @@ -292,7 +303,7 @@ QPushButton[ssName="weeklySelector"]:checked { hBox->addWidget(btnAdd); auto btnDel = new QPushButton(); - btnDel->setIcon(QIcon(":/res/ProgramManager/EditProgram/Delete.png")); + btnDel->setIcon(QIcon(":/res/program/Delete.png")); btnDel->setProperty("style","multiTool"); connect(btnDel, &QPushButton::clicked, this, [this, fdTtlDur] { auto row = mAudiosList->currentRow(); @@ -307,7 +318,7 @@ QPushButton[ssName="weeklySelector"]:checked { hBox->addWidget(btnDel); auto btnGoUp = new QPushButton(); - btnGoUp->setIcon(QIcon(":/res/ProgramManager/EditProgram/GoUp.png")); + btnGoUp->setIcon(QIcon(":/res/program/GoUp.png")); btnGoUp->setProperty("style","multiTool"); connect(btnGoUp, &QPushButton::clicked, this, [this] { int row = mAudiosList->currentRow(); @@ -318,7 +329,7 @@ QPushButton[ssName="weeklySelector"]:checked { hBox->addWidget(btnGoUp); auto btnGoDown = new QPushButton(); - btnGoDown->setIcon(QIcon(":/res/ProgramManager/EditProgram/GoDown.png")); + btnGoDown->setIcon(QIcon(":/res/program/GoDown.png")); btnGoDown->setProperty("style","multiTool"); connect(btnGoDown, &QPushButton::clicked, this, [this] { int row = mAudiosList->currentRow(); @@ -339,7 +350,7 @@ QPushButton[ssName="weeklySelector"]:checked { foreach(auto audio, audios) { AudioInfo info{audio["dir"].toString(), audio["name"].toString(), audio["dur"].toInt(), audio["vol"].toInt()}; if(info.dir.isEmpty() || info.name.isEmpty() || info.dur==0) continue; - auto item = new QListWidgetItem(QIcon(":/res/ProgramManager/EditProgram/Audio.png"), info.name); + auto item = new QListWidgetItem(QIcon(":/res/program/Audio.png"), info.name); item->setData(Qt::UserRole, QVariant::fromValue(info)); durs += info.dur; mAudiosList->addItem(item); diff --git a/LedOK/wProgramManager/pagelistitem.h b/LedOK/program/pagelistitem.h similarity index 100% rename from LedOK/wProgramManager/pagelistitem.h rename to LedOK/program/pagelistitem.h diff --git a/LedOK/wProgramManager/progcreatedlg.cpp b/LedOK/program/progcreatedlg.cpp similarity index 80% rename from LedOK/wProgramManager/progcreatedlg.cpp rename to LedOK/program/progcreatedlg.cpp index dca2456..40f36a1 100644 --- a/LedOK/wProgramManager/progcreatedlg.cpp +++ b/LedOK/program/progcreatedlg.cpp @@ -1,10 +1,10 @@ #include "progcreatedlg.h" -#include "gqt.h" +#include "gutil/qgui.h" #include "globaldefine.h" #include #include -ProgCreateDlg::ProgCreateDlg(QString name, int width, int height, QString remarks, QWidget *parent, bool lockName) : BaseDlg(parent) { +ProgCreateDlg::ProgCreateDlg(QString name, int width, int height, QString remarks, QString widths, QWidget *parent) : BaseDlg(parent) { auto vBox = new VBox(this); auto hBox = new HBox(vBox); @@ -33,8 +33,10 @@ ProgCreateDlg::ProgCreateDlg(QString name, int width, int height, QString remark hBox->addWidget(label); hBox->addSpacing(6); - fdName = new QLineEdit(name); - if(lockName) fdName->setDisabled(true); + fdName = new QLineEdit; + if(name.isEmpty()) name = QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"); + else fdName->setDisabled(true); + fdName->setText(name); hBox->addWidget(fdName); hBox = new HBox(vBox); @@ -82,16 +84,16 @@ ProgCreateDlg::ProgCreateDlg(QString name, int width, int height, QString remark hBox = new HBox(vBox); - auto lbSplitWidth = new QLabel(tr("打折宽度")); - lbSplitWidth->setVisible(gWidthSplit); + auto lbSplitWidth = new QLabel(tr("每段打折宽度 (用空格分隔)")); hBox->addWidget(lbSplitWidth); - fdSplitWidth = new QSpinBox; - fdSplitWidth->setVisible(gWidthSplit); - fdSplitWidth->setMaximum(9999); - fdSplitWidth->setValue(0); - hBox->addWidget(fdSplitWidth); - hBox->addStretch(); + fdSplitWidths = new QLineEdit(widths); + fdSplitWidths->setPlaceholderText("256 256 256 ..."); + hBox->addWidget(fdSplitWidths); + if(! gWidthSplit) { + lbSplitWidth->setVisible(false); + fdSplitWidths->setVisible(false); + } hBox = new HBox(vBox); hBox->addStretch(); diff --git a/LedOK/wProgramManager/progcreatedlg.h b/LedOK/program/progcreatedlg.h similarity index 81% rename from LedOK/wProgramManager/progcreatedlg.h rename to LedOK/program/progcreatedlg.h index 5db0575..07284da 100644 --- a/LedOK/wProgramManager/progcreatedlg.h +++ b/LedOK/program/progcreatedlg.h @@ -9,12 +9,12 @@ class ProgCreateDlg : public BaseDlg { Q_OBJECT public: - ProgCreateDlg(QString name, int width, int height, QString remarks, QWidget *parent = nullptr, bool lockName = false); + ProgCreateDlg(QString name, int width, int height, QString remarks, QString, QWidget *parent = nullptr); QLineEdit *fdName; QSpinBox *fdWidth; QSpinBox *fdHeight; QTextEdit *fdRemark; - QSpinBox *fdSplitWidth; + QLineEdit *fdSplitWidths; }; #endif // PROGCREATEDLG_H diff --git a/LedOK/wProgramManager/progeditorwin.cpp b/LedOK/program/progeditorwin.cpp similarity index 82% rename from LedOK/wProgramManager/progeditorwin.cpp rename to LedOK/program/progeditorwin.cpp index e10ba54..8c32453 100644 --- a/LedOK/wProgramManager/progeditorwin.cpp +++ b/LedOK/program/progeditorwin.cpp @@ -10,20 +10,20 @@ #include "tools.h" #include "globaldefine.h" #include "base/waitingdlg.h" -#include "wProgramManager/ebase.h" -#include "wProgramManager/etext.h" -#include "wProgramManager/ephoto.h" -#include "wProgramManager/evideo.h" -#include "wProgramManager/eaudio.h" -#include "wProgramManager/egif.h" -#include "wProgramManager/edclock.h" -#include "wProgramManager/eaclock.h" -#include "wProgramManager/eenviron.h" -#include "wProgramManager/eweb.h" -#include "wProgramManager/etimer.h" -#include "wProgramManager/emultiwin.h" -#include "wProgramManager/gentmpthread.h" -#include "wProgramManager/sendprogramdialog.h" +#include "program/ebase.h" +#include "program/etext.h" +#include "program/ephoto.h" +#include "program/evideo.h" +#include "program/eaudio.h" +#include "program/egif.h" +#include "program/edclock.h" +#include "program/eaclock.h" +#include "program/eenviron.h" +#include "program/eweb.h" +#include "program/etimer.h" +#include "program/emultiwin.h" +#include "program/gentmpthread.h" +#include "program/sendprogramdialog.h" #include "progcreatedlg.h" #include #include @@ -42,7 +42,8 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare gProgEditorWin = this; gProgItem = progItem; setWindowModality(Qt::WindowModal); - if(parent!=nullptr && ! parent->isMaximized()) resize(parent->size()); + setAttribute(Qt::WA_AlwaysShowToolTips); + if(parent && ! parent->isMaximized()) resize(parent->size()); else resize(1280, 720); setWindowFlag(Qt::Window); setAttribute(Qt::WA_DeleteOnClose); @@ -77,10 +78,10 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); toolBar->setIconSize(QSize(46, 40)); - auto action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Save.png"), tr("Save")); + auto action = new QAction(QIcon(":/res/program/Save.png"), tr("Save")); connect(action, &QAction::triggered, this, &ProgEditorWin::onSave); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/SaveAs.png"), tr("Save as")); + action = new QAction(QIcon(":/res/program/SaveAs.png"), tr("Save as")); connect(action, &QAction::triggered, this, [this] { auto saveThread = QThread::create([this](){ save(); @@ -112,19 +113,43 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare dlgTip->exec(); close(); setWindowTitle(progName); - this->mProgItem->mProgPanel->onCreateNewProgramOnOpenEditProgramWidget(progName, QSize(mProgItem->mWidth, mProgItem->mHeight), this->mProgItem->mRemark, this->mProgItem->mSplitWidth); + mProgItem->mProgPanel->onCreateNewProgramOnOpenEditProgramWidget(progName, QSize(mProgItem->mWidth, mProgItem->mHeight), mProgItem->mRemark, mProgItem->mSplitWidths, mProgItem->mMaxWidth); }); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Setting.png"), tr("Setting")); - connect(action, &QAction::triggered, this, [this](){ - ProgCreateDlg dlg(this->mProgItem->mName, mProgItem->mWidth, mProgItem->mHeight, this->mProgItem->mRemark, this, true); + action = new QAction(QIcon(":/res/program/Setting.png"), tr("Setting")); + connect(action, &QAction::triggered, this, [this]() { + QString widthsStr; + foreach(auto width, mProgItem->mSplitWidths) { + if(! widthsStr.isEmpty()) widthsStr.append(" "); + widthsStr.append(QString::number(width)); + } + ProgCreateDlg dlg(mProgItem->mName, mProgItem->mWidth, mProgItem->mHeight, mProgItem->mRemark, widthsStr, this); if(dlg.exec() != QDialog::Accepted) return; mProgItem->mWidth = dlg.fdWidth->value(); mProgItem->mHeight = dlg.fdHeight->value(); - this->mProgItem->mRemark = dlg.fdRemark->toPlainText(); - this->mProgItem->m_last = QDateTime::currentDateTime(); - this->mProgItem->m_fsize = dirFileSize(this->mProgItem->mProgDir); - this->mProgItem->onSetProgram(); + mProgItem->mRemark = dlg.fdRemark->toPlainText(); + mProgItem->mSplitWidths.clear(); + mProgItem->mMaxWidth = 0; + auto splitWidths = dlg.fdSplitWidths->text().split(" ", Qt::SkipEmptyParts); + int ttl = 0; + foreach(auto splitWidth, splitWidths) { + int val = splitWidth.toInt(); + if(val==0) continue; + if(mProgItem->mMaxWidth < val) mProgItem->mMaxWidth = val; + ttl += val; + mProgItem->mSplitWidths.append(val); + } + if(mProgItem->mMaxWidth) { + while(ttl < mProgItem->mWidth) { + mProgItem->mSplitWidths.append(mProgItem->mMaxWidth); + ttl += mProgItem->mMaxWidth; + } + if(ttl > mProgItem->mWidth) mProgItem->mSplitWidths.last() -= ttl - mProgItem->mWidth; + } + + mProgItem->m_last = QDateTime::currentDateTime(); + mProgItem->m_fsize = dirFileSize(mProgItem->mProgDir); + mProgItem->onSetProgram(); int n = listPage->count(); for(int i=0; i(listPage->item(i)); @@ -136,75 +161,65 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare auto items = page->mScene->items(); foreach(auto item, items) { auto element = static_cast(item); - if(element->mMultiWin == nullptr) element->fitProgSize(); + if(element->mMultiWin == 0) element->fitProgSize(); } page->mScene->update(); } + onSave(); }); toolBar->addAction(action); toolBar->addSeparator(); - if(progItem->mSplitWidth==0) { - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Window.png"), tr("MuliContentWindow")); + if(progItem->mSplitWidths.isEmpty()) { + action = new QAction(QIcon(":/res/program/Window.png"), tr("MuliContentWindow")); action->setToolTip(tr("In this window, a plurality of different program materials can be added and played according to the order of joining the list;")); action->setData(EBase::Window); toolBar->addAction(action); toolBar->addSeparator(); - - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Text.png"), tr("Text")); - action->setData(EBase::Text); - toolBar->addAction(action); } - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Photo.png"), tr("Photo")); + action = new QAction(QIcon(":/res/program/Text.png"), tr("Text")); + action->setData(EBase::Text); + toolBar->addAction(action); + action = new QAction(QIcon(":/res/program/Photo.png"), tr("Photo")); action->setData(EBase::Photo); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Movie.png"), tr("Video")); + action = new QAction(QIcon(":/res/program/Movie.png"), tr("Video")); action->setData(EBase::Video); toolBar->addAction(action); - if(progItem->mSplitWidth==0) { - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Gif.png"), tr("Gif")); + if(progItem->mSplitWidths.isEmpty()) { + action = new QAction(QIcon(":/res/program/Gif.png"), tr("Gif")); action->setData(EBase::Gif); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/DClock.png"), tr("Clock")); + action = new QAction(QIcon(":/res/program/DClock.png"), tr("Clock")); action->setData(EBase::DClock); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/AClock.png"), tr("Analog Clock")); + action = new QAction(QIcon(":/res/program/AClock.png"), tr("Analog Clock")); action->setData(EBase::AClock); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Temp.png"), tr("Environment")); + action = new QAction(QIcon(":/res/program/Temp.png"), tr("Environment")); action->setData(EBase::Environ); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Web.png"), tr("Web")); + action = new QAction(QIcon(":/res/program/Web.png"), tr("Web")); action->setData(EBase::Web); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Timer.png"), tr("Timer")); + action = new QAction(QIcon(":/res/program/Timer.png"), tr("Timer")); action->setData(EBase::Timer); toolBar->addAction(action); } -// action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Audio.png"), tr("Audio")); -// action->setData(EBase::Audio); -// toolBar->addAction(action); toolBar->addSeparator(); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/preview.png"), tr("Play")+"/"+tr("Stop")); + action = new QAction(QIcon(":/res/program/preview.png"), tr("Play")+"/"+tr("Stop")); connect(action, &QAction::triggered, this, [this] { if(PlayWin::self!=nullptr) PlayWin::self->close(); else { if(isProgChanged()) onSave(); - LoEmptyDialog * msgbox = new LoEmptyDialog(this); - //转换节目 + auto waitingDlg = new WaitingDlg(this, tr("Generate preview data")+" ..."); auto converter = new GenTmpThread(mProgItem, mProgItem->mName, "", "" ,this); - //转换结束,发送信号触发converter释放内存 - connect(converter, SIGNAL(finished()), converter, SLOT(deleteLater())); - connect(converter, SIGNAL(finished()), msgbox, SLOT(unlock())); - //链接转换进度信号到进度条槽函数 - connect(converter, SIGNAL(sProgress(QString,int,bool)), msgbox->mIndicator, SLOT(onProgress(QString,int,bool))); - //链接进度对话框启动信号到转换开始槽函数 - connect(msgbox, SIGNAL(startUp()), converter, SLOT(start())); - msgbox->lock(tr("Generate preview data")+"...",tr("Ready"),tr("Generate TimeOut")); - msgbox->exec(); - + connect(converter, &QThread::finished, waitingDlg, &WaitingDlg::close); + connect(converter, &GenTmpThread::sProgress, waitingDlg->mIndicator, &CustomProgressIndicator::onProgress); + converter->start(); + waitingDlg->exec(); QFile file(mProgItem->mProgDir+"_tmp/program"); if(! file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QString value = file.readAll(); @@ -213,29 +228,25 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare QJsonObject prog = QJsonDocument::fromJson(value.toUtf8(), &jsErr).object(); if(jsErr.error) return; int www = mProgItem->mWidth, hhh = mProgItem->mHeight; - if(mProgItem->mSplitWidth) { - int cnt = (mProgItem->mWidth+mProgItem->mSplitWidth-1) / mProgItem->mSplitWidth; - www = mProgItem->mSplitWidth; - hhh = mProgItem->mHeight*cnt; + if(mProgItem->mMaxWidth) { + www = mProgItem->mMaxWidth; + hhh *= mProgItem->mSplitWidths.size(); } PlayWin::self = PlayWin::newIns(www, hhh, mProgItem->mProgDir+"_tmp", prog); } }); toolBar->addAction(action); - action = new QAction(QIcon(":/res/ProgramManager/EditProgram/Send.png"), tr("Publish")); + action = new QAction(QIcon(":/res/program/Send.png"), tr("Publish")); connect(action, &QAction::triggered, this, [this]{ onSave(); - auto waitingDlg = new WaitingDlg(this, tr("Convertering")); - auto converter = new GenTmpThread(this->mProgItem, this->mProgItem->mName, "", "", this); - connect(converter, &QThread::finished, converter, &QThread::deleteLater); - connect(converter, &QThread::finished, waitingDlg, &WaitingDlg::success); - connect(converter, SIGNAL(sProgress(QString,int,bool)), waitingDlg->mIndicator, SLOT(onProgress(QString,int,bool))); + auto waitingDlg = new WaitingDlg(this, tr("Convertering")+" ..."); + auto converter = new GenTmpThread(mProgItem, mProgItem->mName, "", "", this); + connect(converter, &QThread::finished, waitingDlg, &WaitingDlg::close); + connect(converter, &GenTmpThread::sProgress, waitingDlg->mIndicator, &CustomProgressIndicator::onProgress); converter->start(); - //msgbox->lock(tr("Convertering")+"...",tr("Converter Successed"),tr("Converter TimeOut")); waitingDlg->exec(); - - auto dlg = new SendProgramDialog(this, this->mProgItem->mName, programsDir()); - dlg->show(); + SendProgramDialog dlg(mProgItem->mName, this); + dlg.exec(); }); toolBar->addAction(action); @@ -322,12 +333,12 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare } else if(type==EBase::DClock) { if(iNewHeight>80 && (mProgItem->mWidth>=mProgItem->mHeight)) iNewHeight=80; - element = new eDClock(); + element = new EDClock(); } else if(type==EBase::AClock) { if(iNewWidth > 120) iNewWidth = 120; if(iNewHeight > 120) iNewHeight = 120; - element = new eAClock(); + element = new EAClock(); } else if(type==EBase::Environ) element = new EEnviron(); else if(type==EBase::Web) { @@ -337,7 +348,7 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare else if(type==EBase::Timer) element = new ETimer(); else if(type==EBase::Audio) ; else if(type==EBase::Window) element = new EMultiWin(mPageItem); - if(nullptr != element) { + if(element) { if(element->mWidth==0) { element->setPos(mNewEleX, mNewEleY); element->setSize(iNewWidth, iNewHeight); @@ -378,11 +389,11 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare toolBar->setIconSize(QSize(22,16)); toolBar->setStyleSheet("QToolBar{spacing: 8px;}"); - QAction *actAdd = new QAction(QIcon(":/res/ProgramManager/EditProgram/Add.png"), tr("Add page")); + QAction *actAdd = new QAction(QIcon(":/res/program/Add.png"), tr("Add page")); connect(actAdd, &QAction::triggered, this, &ProgEditorWin::onAddPage); toolBar->addAction(actAdd); - QAction *actCopy = new QAction(QIcon(":/res/ProgramManager/EditProgram/Copy.png"), tr("Copy page")); + QAction *actCopy = new QAction(QIcon(":/res/program/Copy.png"), tr("Copy page")); connect(actCopy, &QAction::triggered, this, [this] { if(listPage->count() > 0) { auto cur = static_cast(listPage->currentItem()); @@ -397,7 +408,7 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare }); toolBar->addAction(actCopy); - QAction *actDel = new QAction(QIcon(":/res/ProgramManager/EditProgram/Delete.png"), tr("Delete page")); + QAction *actDel = new QAction(QIcon(":/res/program/Delete.png"), tr("Delete page")); connect(actDel, &QAction::triggered, this, [this] { if(listPage->count() == 1) progEditorMid->onClean(); else if(listPage->count() > 1) { @@ -413,7 +424,7 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare }); toolBar->addAction(actDel); - QAction *actMoveUp = new QAction(QIcon(":/res/ProgramManager/EditProgram/GoUp.png"), tr("Move up")); + QAction *actMoveUp = new QAction(QIcon(":/res/program/GoUp.png"), tr("Move up")); connect(actMoveUp, &QAction::triggered, this, [this] { if(listPage->count() > 1) { int index = listPage->currentRow(); @@ -429,7 +440,7 @@ ProgEditorWin::ProgEditorWin(ProgItem *progItem, QWidget *parent) : BaseWin(pare }); toolBar->addAction(actMoveUp); - QAction *actMoveDown = new QAction(QIcon(":/res/ProgramManager/EditProgram/GoDown.png"), tr("Move down")); + QAction *actMoveDown = new QAction(QIcon(":/res/program/GoDown.png"), tr("Move down")); connect(actMoveDown, &QAction::triggered, this, [this] { if(listPage->count() > 1) { int index = listPage->currentRow(); @@ -608,6 +619,7 @@ void ProgEditorWin::save() { void ProgEditorWin::onSave() { auto waitingDlg = new WaitingDlg(this, tr("Saving..."), tr("Success")); + waitingDlg->btnAbort->hide(); //dlg->lock(tr("Saving..."),tr("Success"),tr("Save failed")); waitingDlg->show(); save(); diff --git a/LedOK/wProgramManager/progeditorwin.h b/LedOK/program/progeditorwin.h similarity index 94% rename from LedOK/wProgramManager/progeditorwin.h rename to LedOK/program/progeditorwin.h index dd12d82..7b252f5 100644 --- a/LedOK/wProgramManager/progeditorwin.h +++ b/LedOK/program/progeditorwin.h @@ -1,7 +1,7 @@ #ifndef PROGEDITORWIN_H #define PROGEDITORWIN_H #include "basewin.h" -#include "wProgramManager/pageeditor.h" +#include "program/pageeditor.h" #include class ProgPanel; diff --git a/LedOK/wProgramManager/progitem.cpp b/LedOK/program/progitem.cpp similarity index 60% rename from LedOK/wProgramManager/progitem.cpp rename to LedOK/program/progitem.cpp index 02a5258..da97cc4 100644 --- a/LedOK/wProgramManager/progitem.cpp +++ b/LedOK/program/progitem.cpp @@ -1,15 +1,18 @@ #include "progitem.h" +#include "gutil/qcore.h" #include "tools.h" #include "progeditorwin.h" +#include "base/waitingdlg.h" #include "gentmpthread.h" #include "base/loemptydialog.h" #include "usbdetectdialog.h" #include #include "sendprogramdialog.h" #include "mainwindow.h" +#include -ProgItem::ProgItem(const QString &progsDir, const QString &name, int w, int h, const QString &remarks, int splitWidth, LoQTreeWidget *tree, ProgPanel *progPanel) : QTreeWidgetItem(UserType), - mName(name), mWidth(w), mHeight(h), mRemark(remarks), mSplitWidth(splitWidth), mProgsDir(progsDir), mProgPanel(progPanel), mTree(tree) { +ProgItem::ProgItem(const QString &progsDir, const QString &name, int w, int h, const QString &remarks, QList &splitWidths, int maxWidth, LoQTreeWidget *tree, ProgPanel *progPanel) : QTreeWidgetItem(UserType), + mName(name), mWidth(w), mHeight(h), mRemark(remarks), mSplitWidths(splitWidths), mMaxWidth(maxWidth), mProgsDir(progsDir), mProgPanel(progPanel), mTree(tree) { m_last = QDateTime::currentDateTime(); mProgDir = progsDir + "/" + mName; m_orgName = mName; @@ -21,7 +24,12 @@ ProgItem::ProgItem(const QString &progsDir, const QJsonObject &json, LoQTreeWidg mWidth = json["resolution"]["w"].toInt(); mHeight = json["resolution"]["h"].toInt(); mRemark = json["remarks"].toString(); - mSplitWidth = json["splitWidth"].toInt(); + auto splitWidths = json["splitWidths"].toArray(); + foreach(auto splitWidth, splitWidths) { + int width = splitWidth.toInt(); + if(mMaxWidth < width) mMaxWidth = width; + mSplitWidths.append(width); + } m_fsize = json["file_size"].toDouble(); m_last = QDateTime::fromString(json["last_edit"].toString(), "yyyy-MM-dd hh:mm:ss"); mProgDir = progsDir + "/" + mName; @@ -30,20 +38,15 @@ ProgItem::ProgItem(const QString &progsDir, const QJsonObject &json, LoQTreeWidg init(); } -void ProgItem::init() -{ - auto cfg = Tools::getInstance(); - setData(ENUM_PROGRAMLISTHEADERITEM_NAME, 0,mName); +void ProgItem::init() { + setForeground(ENUM_PROGRAMLISTHEADERITEM_NAME, Qt::transparent); + setText(ENUM_PROGRAMLISTHEADERITEM_NAME, mName); setData(ENUM_PROGRAMLISTHEADERITEM_RESOLUTION, 0, QString("%1 x %2").arg(mWidth).arg(mHeight)); - if(m_fsize<=0) - setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize((qint64)100)); - else - setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize(m_fsize)); + if(m_fsize<=0) setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, byteSizeStr((qint64)100)); + else setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, byteSizeStr(m_fsize)); setData(ENUM_PROGRAMLISTHEADERITEM_LASTTIME, 0, m_last.toString("yyyy-MM-dd hh:mm:ss")); setTextAlignment(ENUM_PROGRAMLISTHEADERITEM_NAME, Qt::AlignLeft | Qt::AlignVCenter); - for(int i=1; iinsertTopLevelItem(0,this); @@ -69,9 +72,9 @@ QPushButton:hover { m_bnExport->setStyleSheet(R"rrr( QPushButton { border-radius: 4px; - image: url(:/res/ProgramManager/bnExport_u.png); + image: url(:/res/program/bnExport_u.png); } -QPushButton:pressed{image: url(:/res/ProgramManager/bnExport_s.png);} +QPushButton:pressed{image: url(:/res/program/bnExport_s.png);} QPushButton:hover{background-color: #cccccc;} )rrr"); @@ -84,9 +87,9 @@ QPushButton:hover{background-color: #cccccc;} m_bnSend->setStyleSheet(R"rrr( QPushButton{ border-radius: 4px; - image: url(:/res/ProgramManager/bnSend_u.png); + image: url(:/res/program/bnSend_u.png); } -QPushButton:pressed{image: url(:/res/ProgramManager/bnSend_s.png);} +QPushButton:pressed{image: url(:/res/program/bnSend_s.png);} QPushButton:hover{background-color: #cccccc;} )rrr"); @@ -106,7 +109,7 @@ void ProgItem::save() { } else if(mName != m_orgName) { dParent.rename(m_orgName, mName); m_orgName = mName; - mProgDir = mProgsDir + MACRO_FENGEFU + mName; + mProgDir = mProgsDir + "/" + mName; } dRoot = QDir(mProgDir); @@ -116,7 +119,9 @@ void ProgItem::save() { obj["name"] = mName; obj["resolution"] = QJsonObject{{"w", mWidth}, {"h", mHeight}}; obj["remarks"] = mRemark; - obj["splitWidth"] = mSplitWidth; + QJsonArray splitWidths; + foreach(auto splitWidth, mSplitWidths) splitWidths.append(splitWidth); + obj["splitWidths"] = splitWidths; obj["file_size"] = m_fsize; obj["last_edit"] = m_last.toString("yyyy-MM-dd hh:mm:ss"); QJsonDocument json(obj); @@ -133,10 +138,9 @@ void ProgItem::del() { } //设置列表项的值 void ProgItem::onSetProgram() { - auto cfg = Tools::getInstance(); m_bnName->setText(mName); setData(ENUM_PROGRAMLISTHEADERITEM_RESOLUTION, 0, QString("%1 x %2").arg(mWidth).arg(mHeight)); - setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, cfg->convertFileSize(m_fsize<=0 ? 100 : m_fsize)); + setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, byteSizeStr(m_fsize<=0 ? 100 : m_fsize)); setData(ENUM_PROGRAMLISTHEADERITEM_LASTTIME, 0, m_last.toString("yyyy-MM-dd hh:mm:ss")); save(); } @@ -146,36 +150,22 @@ void ProgItem::onUsbExportProgram(){ connect(pDlg, &UsbDetectDialog::acceptData, this, &ProgItem::onUsbExportProgramPro); pDlg->exec(); } -void ProgItem::onUsbExportProgramPro(QString strPath, QString strPassword){ - LoEmptyDialog *msgbox = new LoEmptyDialog(mProgPanel); - QString strUsbProgramName = mName; - auto converter = new GenTmpThread(this, strUsbProgramName, strPath + (strPath.endsWith('/') ? "program.zip" : "/program.zip"), strPassword, this); - connect(converter, &QThread::finished, converter, &QThread::deleteLater); - //转换结束,发送信号触发converter释放内存 - connect(converter, SIGNAL(finished()), msgbox, SLOT(unlock())); - connect(converter, SIGNAL(finished()), this, SLOT(UsbExportFinished())); - //链接转换进度信号到进度条槽函数 - connect(converter, SIGNAL(sProgress(QString,int,bool)), msgbox->mIndicator, SLOT(onProgress(QString,int,bool))); - //链接进度对话框启动信号到转换开始槽函数 - connect(msgbox, SIGNAL(startUp()), converter, SLOT(start())); - msgbox->lock(tr("Convertering")+"...",tr("USB Export Successed"),tr("USB Export TimeOut")); - msgbox->exec(); +void ProgItem::onUsbExportProgramPro(QString strPath, QString strPassword) { + auto waitingDlg = new WaitingDlg(mProgPanel, tr("Convertering")+" ..."); + auto converter = new GenTmpThread(this, mName, strPath + (strPath.endsWith('/') ? "program.zip" : "/program.zip"), strPassword, this); + connect(converter, &QThread::finished, waitingDlg, &WaitingDlg::success); + connect(converter, &GenTmpThread::sProgress, waitingDlg->mIndicator, &CustomProgressIndicator::onProgress); + converter->start(); + waitingDlg->exec(); } -void ProgItem::onSendProgram(){ - LoEmptyDialog *msgbox = new LoEmptyDialog(mProgPanel); - //转换节目 +void ProgItem::onSendProgram() { + auto waitingDlg = new WaitingDlg(mProgPanel, tr("Convertering")+" ..."); auto converter = new GenTmpThread(this, mName, "", "", this); - connect(converter, &QThread::finished, converter, &QThread::deleteLater); - //转换结束,发送信号触发converter释放内存 - connect(converter, SIGNAL(finished()), msgbox, SLOT(unlock())); - //链接转换进度信号到进度条槽函数 - connect(converter, SIGNAL(sProgress(QString,int,bool)), msgbox->mIndicator, SLOT(onProgress(QString,int,bool))); - //链接进度对话框启动信号到转换开始槽函数 - connect(msgbox, SIGNAL(startUp()), converter, SLOT(start())); - msgbox->lock(tr("Convertering")+"...",tr("Converter Successed"),tr("Converter TimeOut")); - msgbox->exec(); - - auto dlg = new SendProgramDialog(mProgPanel, mName, programsDir()); - dlg->show(); + connect(converter, &QThread::finished, waitingDlg, &WaitingDlg::close); + connect(converter, &GenTmpThread::sProgress, waitingDlg->mIndicator, &CustomProgressIndicator::onProgress); + converter->start(); + waitingDlg->exec(); + SendProgramDialog dlg(mName, mProgPanel); + dlg.exec(); } diff --git a/LedOK/wProgramManager/progitem.h b/LedOK/program/progitem.h similarity index 88% rename from LedOK/wProgramManager/progitem.h rename to LedOK/program/progitem.h index ebef519..62a9ff6 100644 --- a/LedOK/wProgramManager/progitem.h +++ b/LedOK/program/progitem.h @@ -13,7 +13,7 @@ class ProgPanel; class ProgItem : public QObject, public QTreeWidgetItem { Q_OBJECT public: - explicit ProgItem(const QString &progsDir, const QString &name, int w, int h, const QString & remarks, int splitWidth, LoQTreeWidget *parent = nullptr, ProgPanel *pWnd=nullptr); + explicit ProgItem(const QString &progsDir, const QString &name, int w, int h, const QString & remarks, QList &splitWidths, int, LoQTreeWidget *parent = nullptr, ProgPanel *pWnd=nullptr); explicit ProgItem(const QString &progsDir, const QJsonObject &json, LoQTreeWidget *parent = nullptr, ProgPanel *pWnd=nullptr); void save(); @@ -24,7 +24,8 @@ public: int mWidth; int mHeight; QString mRemark; - int mSplitWidth{0}; + QList mSplitWidths; + int mMaxWidth{0}; QString mProgsDir; QString mProgDir; qint64 m_fsize{0}; diff --git a/LedOK/wProgramManager/sendprogramdialog.cpp b/LedOK/program/sendprogramdialog.cpp similarity index 92% rename from LedOK/wProgramManager/sendprogramdialog.cpp rename to LedOK/program/sendprogramdialog.cpp index ec3f8f6..cac842e 100644 --- a/LedOK/wProgramManager/sendprogramdialog.cpp +++ b/LedOK/program/sendprogramdialog.cpp @@ -1,273 +1,270 @@ -#include "sendprogramdialog.h" -#include "tools.h" -#include -#include -#include -#include - -SendProgramDialog::SendProgramDialog(QWidget *parent, QString strProgramName, QString strProgramPath) : QWidget(parent, Qt::Window) { - setWindowModality(Qt::ApplicationModal); - setAttribute(Qt::WA_DeleteOnClose); - resize(1024, 700); - setWindowTitle(tr("Publish")+" "+strProgramName); - auto vBox = new QVBoxLayout(this); - auto hBox = new QHBoxLayout(); - - label = new QLabel(tr("success info")); - hBox->addWidget(label); - - hBox->addStretch(); - - auto pushButtonRefresh = new QPushButton(tr("Refresh")); - pushButtonRefresh->setProperty("ssType", "progManageTool"); - connect(pushButtonRefresh, SIGNAL(clicked()),this, SLOT(onRefresh())); - hBox->addWidget(pushButtonRefresh); - - auto txtSearch = new QLineEdit(); - txtSearch->setFixedWidth(150); - txtSearch->setClearButtonEnabled(true); - txtSearch->setStyleSheet("QLineEdit{border: 2px solid #aaaaaa; padding: 2px;}"); - txtSearch->addAction(new QAction(QIcon(":/res/ProgramManager/bnSearch.png"), QString()), QLineEdit::LeadingPosition); - connect(txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &))); - hBox->addWidget(txtSearch); - - vBox->addLayout(hBox); - - wDevicePublishList = new LoQTreeWidget(); - wDevicePublishList->setProperty("ssType", "topList"); - m_headerItem = new QTreeWidgetItem(); - m_headerItem->setTextAlignment(1, Qt::AlignHCenter | Qt::AlignVCenter); - for(int i=1; isetTextAlignment(i, Qt::AlignCenter); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 0, ""); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, tr("Screen ID")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 0, tr("Online")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, tr("Screen IP")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, tr("Screen Size")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT,0,tr("Security")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 0, tr("Progress")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, tr("Remark Name")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, tr("Remarks")); - wDevicePublishList->setHeaderItem(m_headerItem); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_CHECK, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, QHeaderView::Interactive); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, QHeaderView::Stretch); - wDevicePublishList->header()->setStretchLastSection(false); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 52); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 130); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 130); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 88); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 50); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, 52); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 160); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 120); - vBox->addWidget(wDevicePublishList); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - - auto btnPublish = new QPushButton(tr("Publish")); - connect(btnPublish, &QPushButton::clicked, this, [this] { - if(mWaitCnt > 0) return; - int cnt = wDevicePublishList->topLevelItemCount(); - int sentCnt{0}; - for(int i=0; itopLevelItem(i); - if(item->checkState(0) != Qt::Checked) continue; - auto row = static_cast(item); - if(row->mIsSending) continue; - if(row->mLedCard->bPassword && row->mLedCard->m_bLockStatus) { - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, tr("This screen is encrypted")); - row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red); - continue; - } - row->fdProgress->setValue(0); - if(sentCnt>=5) { - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, " 等待中 ..."); - row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::black); - mWaitCnt++; - continue; - } - row->mIsSending = true; - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, ""); - auto sendProg = new SendProgThread(m_strProgramPath+"/"+m_strProgramName+"_tmp", row->mLedCard->m_strCardIp, 3333); - connect(sendProg, &SendProgThread::emErr, row, [this, row](QString strTip) { - row->mIsSending = false; - if(strTip=="OK") { - row->setCheckState(0, Qt::Unchecked); - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "OK"); - row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::darkGreen); - } else { - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip); - row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red); - } - sendNext(); - }); - connect(sendProg, &SendProgThread::emProgress, row->fdProgress, &QProgressBar::setValue); - connect(this, &SendProgramDialog::stopAllThd, sendProg, &SendProgThread::stop); - sendProg->start(); - sentCnt++; - } - }); - btnPublish->setProperty("ssType", "progManageTool"); - hBox->addWidget(btnPublish); - - auto btnCancel = new QPushButton(tr("Cancel")); - connect(btnCancel, &QPushButton::clicked, this, &QWidget::close); - btnCancel->setProperty("ssType", "progManageTool"); - hBox->addWidget(btnCancel); - - vBox->addLayout(hBox); - - m_strProgramName = strProgramName; - m_strProgramPath = strProgramPath; - - onRefresh(); - - auto timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, &SendProgramDialog::onRefresh); - timer->start(60000); -} -void SendProgramDialog::closeEvent(QCloseEvent *) { - emit stopAllThd(); -} -void SendProgramDialog::sendNext() { - if(mWaitCnt <= 0) return; - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; itopLevelItem(i); - if(item->checkState(0) != Qt::Checked) continue; - auto row = static_cast(item); - if(row->mIsSending) continue; - if(row->mLedCard->bPassword && row->mLedCard->m_bLockStatus) continue; - if(! row->data(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0).toString().startsWith(" ")) continue; - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, ""); - row->fdProgress->setValue(0); - row->mIsSending = true; - mWaitCnt--; - auto sendProg = new SendProgThread(m_strProgramPath+"/"+m_strProgramName+"_tmp", row->mLedCard->m_strCardIp, 3333); - connect(sendProg, &SendProgThread::emErr, row, [this, row](QString strTip) { - row->mIsSending = false; - if(strTip=="OK") { - row->setCheckState(0, Qt::Unchecked); - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "OK"); - row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::darkGreen); - } else { - row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip); - row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red); - } - sendNext(); - }); - connect(sendProg, &SendProgThread::emProgress, row->fdProgress, &QProgressBar::setValue); - connect(this, &SendProgramDialog::stopAllThd, sendProg, &SendProgThread::stop); - sendProg->start(); - return; - } -} - -void SendProgramDialog::onRefresh() { - int iCount = gDevicePanel->LedCardList.count(); - for(int i=0; iLedCardList.at(i)); - label->setText(tr("All")+":"+QString::number(iCount)); -} -void SendProgramDialog::onAddLedCard(LedCard *p) { - int iExistFlg=0; - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; i(wDevicePublishList->topLevelItem(i))->mLedCard->m_strCardId; - if(strTempCardId == p->m_strCardId) { - iExistFlg=1; - static_cast(wDevicePublishList->topLevelItem(i))->SetItemParam(p); - break; - } - } - if(iExistFlg==0) new wProgramPublishItem(p, wDevicePublishList, this, m_strProgramName, m_strProgramPath); -} -void SendProgramDialog::FilterProgram(const QString &strtemp) -{ - if (strtemp.isEmpty()) //显示全部 - { - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); - } - } - else - { - QList resultList = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID); //搜索结果 - if (resultList.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - - QList resultList6 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME); //搜索结果 - if (resultList6.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList6.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - - - //QMessageBox::warning(this, "Export", "FilterProgram"); - QList resultList1 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE); //搜索结果 - if (resultList1.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList1.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - } - } - } - } -} +#include "sendprogramdialog.h" +#include "tools.h" +#include "cfg.h" +#include +#include +#include +#include + +SendProgramDialog::SendProgramDialog(QString progName, QWidget *parent) : QDialog(parent), mProgName(progName) { + setWindowFlag(Qt::WindowMaximizeButtonHint); + setWindowTitle(tr("Publish")+" "+mProgName); + resize(1024, 700); + auto vBox = new QVBoxLayout(this); + auto hBox = new QHBoxLayout(); + + label = new QLabel(tr("success info")); + hBox->addWidget(label); + + hBox->addStretch(); + + auto pushButtonRefresh = new QPushButton(tr("Refresh")); + pushButtonRefresh->setProperty("ssType", "progManageTool"); + connect(pushButtonRefresh, SIGNAL(clicked()),this, SLOT(onRefresh())); + hBox->addWidget(pushButtonRefresh); + + auto txtSearch = new QLineEdit(); + txtSearch->setFixedWidth(150); + txtSearch->setClearButtonEnabled(true); + txtSearch->setStyleSheet("QLineEdit{border: 2px solid #aaaaaa; padding: 2px;}"); + txtSearch->addAction(new QAction(QIcon(":/res/program/bnSearch.png"), QString()), QLineEdit::LeadingPosition); + connect(txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &))); + hBox->addWidget(txtSearch); + + vBox->addLayout(hBox); + + wDevicePublishList = new LoQTreeWidget(); + wDevicePublishList->setProperty("ssType", "topList"); + m_headerItem = new QTreeWidgetItem(); + m_headerItem->setTextAlignment(1, Qt::AlignHCenter | Qt::AlignVCenter); + for(int i=1; isetTextAlignment(i, Qt::AlignCenter); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 0, ""); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, tr("Screen ID")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 0, tr("Online")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, tr("Screen IP")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, tr("Screen Size")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT,0,tr("Security")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, tr("Remark Name")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 0, tr("Progress")); + m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, tr("Remarks")); + wDevicePublishList->setHeaderItem(m_headerItem); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_CHECK, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, QHeaderView::Fixed); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, QHeaderView::Interactive); + wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, QHeaderView::Stretch); + wDevicePublishList->header()->setStretchLastSection(false); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 52); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 130); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 130); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 88); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 50); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, 52); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 160); + wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 120); + vBox->addWidget(wDevicePublishList); + + hBox = new QHBoxLayout(); + hBox->addStretch(); + + auto btnPublish = new QPushButton(tr("Publish")); + connect(btnPublish, &QPushButton::clicked, this, [this] { + if(mWaitCnt > 0) return; + int cnt = wDevicePublishList->topLevelItemCount(); + int sentCnt{0}; + for(int i=0; itopLevelItem(i); + if(item->checkState(0) != Qt::Checked) continue; + auto row = static_cast(item); + if(row->mIsSending) continue; + if(row->mLedCard->bPassword && row->mLedCard->m_bLockStatus) { + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, tr("This screen is encrypted")); + row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red); + continue; + } + row->fdProgress->setValue(0); + if(sentCnt>=5) { + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, " 等待中 ..."); + row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::black); + mWaitCnt++; + continue; + } + row->mIsSending = true; + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, ""); + auto sendProg = new SendProgThread(programsDir()+"/"+mProgName+"_tmp", row->mLedCard->m_strCardIp, 3333); + connect(sendProg, &SendProgThread::emErr, row, [this, row](QString strTip) { + row->mIsSending = false; + if(strTip=="OK") { + row->setCheckState(0, Qt::Unchecked); + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "OK"); + row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::darkGreen); + } else { + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip); + row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red); + } + sendNext(); + }); + connect(sendProg, &SendProgThread::emProgress, row->fdProgress, &QProgressBar::setValue); + connect(this, &SendProgramDialog::stopAllThd, sendProg, &SendProgThread::stop); + sendProg->start(); + sentCnt++; + } + }); + btnPublish->setProperty("ssType", "progManageTool"); + hBox->addWidget(btnPublish); + + auto btnCancel = new QPushButton(tr("Cancel")); + connect(btnCancel, &QPushButton::clicked, this, &QWidget::close); + btnCancel->setProperty("ssType", "progManageTool"); + hBox->addWidget(btnCancel); + + vBox->addLayout(hBox); + + onRefresh(); + + auto timer = new QTimer(this); + connect(timer, &QTimer::timeout, this, &SendProgramDialog::onRefresh); + timer->start(60000); +} +void SendProgramDialog::closeEvent(QCloseEvent *) { + emit stopAllThd(); +} +void SendProgramDialog::sendNext() { + if(mWaitCnt <= 0) return; + int cnt = wDevicePublishList->topLevelItemCount(); + for(int i=0; itopLevelItem(i); + if(item->checkState(0) != Qt::Checked) continue; + auto row = static_cast(item); + if(row->mIsSending) continue; + if(row->mLedCard->bPassword && row->mLedCard->m_bLockStatus) continue; + if(! row->data(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0).toString().startsWith(" ")) continue; + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, ""); + row->fdProgress->setValue(0); + row->mIsSending = true; + mWaitCnt--; + auto sendProg = new SendProgThread(programsDir()+"/"+mProgName+"_tmp", row->mLedCard->m_strCardIp, 3333); + connect(sendProg, &SendProgThread::emErr, row, [this, row](QString strTip) { + row->mIsSending = false; + if(strTip=="OK") { + row->setCheckState(0, Qt::Unchecked); + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "OK"); + row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::darkGreen); + } else { + row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip); + row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red); + } + sendNext(); + }); + connect(sendProg, &SendProgThread::emProgress, row->fdProgress, &QProgressBar::setValue); + connect(this, &SendProgramDialog::stopAllThd, sendProg, &SendProgThread::stop); + sendProg->start(); + return; + } +} + +void SendProgramDialog::onRefresh() { + int iCount = gDevicePanel->mLedCards.count(); + for(int i=0; imLedCards.at(i)); + label->setText(tr("All")+":"+QString::number(iCount)); +} +void SendProgramDialog::onAddLedCard(LedCard *p) { + int iExistFlg=0; + int cnt = wDevicePublishList->topLevelItemCount(); + for(int i=0; i(wDevicePublishList->topLevelItem(i))->mLedCard->m_strCardId; + if(strTempCardId == p->m_strCardId) { + iExistFlg=1; + static_cast(wDevicePublishList->topLevelItem(i))->SetItemParam(p); + break; + } + } + if(iExistFlg==0) new wProgramPublishItem(p, wDevicePublishList, this, mProgName, programsDir()); +} +void SendProgramDialog::FilterProgram(const QString &strtemp) +{ + if (strtemp.isEmpty()) //显示全部 + { + for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); + } + } + else + { + QList resultList = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID); //搜索结果 + if (resultList.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); + if (resultList.contains(topItem)) + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + + QList resultList6 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME); //搜索结果 + if (resultList6.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); + if (resultList6.contains(topItem)) + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + + + //QMessageBox::warning(this, "Export", "FilterProgram"); + QList resultList1 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE); //搜索结果 + if (resultList1.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); + if (resultList1.contains(topItem)) + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP); //搜索结果 + if (resultList2.size() > 0) + { + //QMessageBox::warning(this, "Export", QString(resultList.size())); + for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); + if (resultList2.contains(topItem)) + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 + else + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + else { + for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) + { + QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); + wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 + } + } + } + } + } + } +} diff --git a/LedOK/wProgramManager/sendprogramdialog.h b/LedOK/program/sendprogramdialog.h similarity index 71% rename from LedOK/wProgramManager/sendprogramdialog.h rename to LedOK/program/sendprogramdialog.h index dc12b3e..5bea778 100644 --- a/LedOK/wProgramManager/sendprogramdialog.h +++ b/LedOK/program/sendprogramdialog.h @@ -1,31 +1,31 @@ -#ifndef SENDPROGRAMDIALOG_H -#define SENDPROGRAMDIALOG_H - -#include "wprogrampublishitem.h" - -class SendProgramDialog : public QWidget { - Q_OBJECT -public: - explicit SendProgramDialog(QWidget *parent = nullptr, QString strProgramName = "", QString strProgramPath = ""); -protected: - void closeEvent(QCloseEvent *event) override; -signals: - void stopAllThd(); -protected slots: - void onRefresh(); - void FilterProgram(const QString &strtemp); -private: - void sendNext(); - void onAddLedCard(LedCard *p); - - LoQTreeWidget *wDevicePublishList; - int mWaitCnt{0}; - QLabel *label; - - QTreeWidgetItem *m_headerItem = nullptr; - QString m_strProgramName; - QString m_strProgramPath; - QString m_strUrl; -}; - -#endif // SENDPROGRAMDIALOG_H +#ifndef SENDPROGRAMDIALOG_H +#define SENDPROGRAMDIALOG_H + +#include "wprogrampublishitem.h" +#include + +class SendProgramDialog : public QDialog { + Q_OBJECT +public: + explicit SendProgramDialog(QString, QWidget *parent = nullptr); +protected: + void closeEvent(QCloseEvent *event) override; +signals: + void stopAllThd(); +protected slots: + void onRefresh(); + void FilterProgram(const QString &strtemp); +private: + void sendNext(); + void onAddLedCard(LedCard *p); + + LoQTreeWidget *wDevicePublishList; + int mWaitCnt{0}; + QLabel *label; + + QTreeWidgetItem *m_headerItem = nullptr; + QString mProgName; + QString m_strUrl; +}; + +#endif // SENDPROGRAMDIALOG_H diff --git a/LedOK/wProgramManager/sendprogthread.cpp b/LedOK/program/sendprogthread.cpp similarity index 96% rename from LedOK/wProgramManager/sendprogthread.cpp rename to LedOK/program/sendprogthread.cpp index 4486214..c6eda2d 100644 --- a/LedOK/wProgramManager/sendprogthread.cpp +++ b/LedOK/program/sendprogthread.cpp @@ -1,224 +1,225 @@ -#include "sendprogthread.h" -#include -#include -#include -#include -#include -#include - -SendProgThread::SendProgThread(const QString &progDir, const QString &ip, int port) : prog_dir(progDir), ip(ip), port(port) { - connect(this, &QThread::finished, this, &QThread::deleteLater); -} - -void SendProgThread::run() { - emit emProgress(0); // 进度条归零 - auto fileInfos = QDir(prog_dir).entryInfoList(QDir::Files); - if(fileInfos.isEmpty()) { - emit emErr(tr("Program is empty")); - return; - } - if(stoped) return; - TcpSocket tcp; - tcp.connectToHost(ip, port); - if(! tcp.waitForConnected()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForConnected"); - tcp.close(); - return; - } - if(stoped) { - tcp.close(); - return; - }; - //发送节目列表协商 - QJsonArray ids; - foreach(auto fileInfo, fileInfos) { - auto baseName = fileInfo.baseName(); - if(baseName!="program") ids.append(baseName); - } - if(! ids.isEmpty()) { - QJsonObject req; - req.insert("_type", "consult"); - req.insert("proName", "program"); - req.insert("idList", ids); - req.insert("zVer", "xixun1"); - auto requ = QJsonDocument(req).toJson(QJsonDocument::Compact); - auto resNum = tcp.write(requ); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'consult'. size"+QString::number(requ.size())); - tcp.close(); - return; - } - if(! tcp.waitForReadyRead()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'consult'. size"+QString::number(requ.size())); - tcp.close(); - return; - } - auto resp = tcp.readAll(); - if(resp.isEmpty()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'consult'. size"+QString::number(requ.size())); - tcp.close(); - return; - } - if(stoped) { - tcp.close(); - return; - }; - QJsonParseError parseErr; - QJsonDocument res = QJsonDocument::fromJson(resp, &parseErr); - for(int i=2; parseErr.error == QJsonParseError::UnterminatedString && i < 10; i++) { - if(! tcp.waitForReadyRead()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'consult' "+QString::number(i)); - tcp.close(); - return; - } - auto resp2 = tcp.readAll(); - if(resp2.isEmpty()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'consult' "+QString::number(i)); - tcp.close(); - return; - } - resp += resp2; - res = QJsonDocument::fromJson(resp, &parseErr); - } - if(parseErr.error != QJsonParseError::NoError) { - emit emErr(parseErr.errorString()+" when parse consult. size:"+QString::number(resp.size())); - tcp.close(); - return; - } - if(res["_type"].toString()=="consult") { - fileInfos.clear(); - fileInfos.append(QString(prog_dir+"/program")); - QJsonArray ids = res["idList"].toArray(); - foreach(auto id, ids) fileInfos.append(QString(prog_dir+"/"+id.toString())); - } - } - if(stoped) { - tcp.close(); - return; - } - qint64 progSize = 0; - foreach(auto fileInfo, fileInfos) progSize += fileInfo.size(); - if(progSize == 0) { - emit emErr(tr("Program is empty")); - tcp.close(); - return; - } - auto req = QJsonObject(); - req.insert("_type", "proStart"); - req.insert("proName", "program"); - req.insert("proSize", progSize); - req.insert("zVer","xixun1"); - auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proStart'"); - tcp.close(); - return; - } - if(stoped) { - tcp.close(); - return; - } - //4.发送协商列表应答里的文件 - long long sentBytes = 0; - foreach(auto info, fileInfos) if(info.isFile()) { - auto baseName = info.baseName(); - auto remain = info.size(); - req = QJsonObject(); - req.insert("_type", "fileStart"); - req.insert("id", baseName); - req.insert("size", remain); - req.insert("relative_path", ""); - req.insert("zVer","xixun1"); - auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileStart'"); - tcp.close(); - return; - } - auto file = new QFile(info.filePath()); - if(! file->open(QFile::ReadOnly)) { - emit emErr(tr("Open file failed")+" "+file->errorString()); - tcp.close(); - return; - } - while(remain > 0) { - auto readed = file->read(qMin(4096LL, remain)); - if(readed.isEmpty()) { - emit emErr(tr("Read file failed")+" "+file->errorString()); - tcp.close(); - file->close(); - return; - } - if(stoped) { - tcp.close(); - file->close(); - return; - }; - resNum = tcp.write(readed); - if(resNum == -1) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write file: "+file->fileName()); - tcp.close(); - file->close(); - return; - } - if(! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForWritten file: "+file->fileName()); - tcp.close(); - file->close(); - return; - } - if(stoped) { - tcp.close(); - file->close(); - return; - }; - remain -= resNum; - sentBytes += resNum; - if(sentBytes != 0) emit emProgress(sentBytes * 99 / progSize); - } - file->close(); - if(stoped) { - tcp.close(); - return; - }; - req = QJsonObject(); - req.insert("_type", "fileEnd"); - req.insert("id", baseName); - req.insert("zVer", "xixun1"); - resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileEnd'"); - tcp.close(); - return; - } - } - if(stoped) { - tcp.close(); - return; - }; - //5.发送结束 - req = QJsonObject(); - req.insert("_type", "proEnd"); - req.insert("proName", "program"); - req.insert("zVer","xixun1"); - resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proEnd'"); - tcp.close(); - return; - }; - if(! tcp.waitForReadyRead()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'proEnd'"); - tcp.close(); - return; - } - auto resp = tcp.readAll(); - if(resp.isEmpty()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'proEnd'"); - tcp.close(); - return; - } - tcp.close(); - emit emProgress(100); - emit emErr("OK"); -} +#include "sendprogthread.h" +#include "gutil/qnetwork.h" +#include +#include +#include +#include +#include +#include + +SendProgThread::SendProgThread(const QString &progDir, const QString &ip, int port) : prog_dir(progDir), ip(ip), port(port) { + connect(this, &QThread::finished, this, &QThread::deleteLater); +} + +void SendProgThread::run() { + emit emProgress(0); // 进度条归零 + auto fileInfos = QDir(prog_dir).entryInfoList(QDir::Files); + if(fileInfos.isEmpty()) { + emit emErr(tr("Program is empty")); + return; + } + if(stoped) return; + TcpSocket tcp; + tcp.connectToHost(ip, port); + if(! tcp.waitForConnected()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForConnected"); + tcp.close(); + return; + } + if(stoped) { + tcp.close(); + return; + }; + //发送节目列表协商 + QJsonArray ids; + foreach(auto fileInfo, fileInfos) { + auto baseName = fileInfo.baseName(); + if(baseName!="program") ids.append(baseName); + } + if(! ids.isEmpty()) { + QJsonObject req; + req.insert("_type", "consult"); + req.insert("proName", "program"); + req.insert("idList", ids); + req.insert("zVer", "xixun1"); + auto requ = QJsonDocument(req).toJson(QJsonDocument::Compact); + auto resNum = tcp.write(requ); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'consult'. size"+QString::number(requ.size())); + tcp.close(); + return; + } + if(! tcp.waitForReadyRead()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'consult'. size"+QString::number(requ.size())); + tcp.close(); + return; + } + auto resp = tcp.readAll(); + if(resp.isEmpty()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'consult'. size"+QString::number(requ.size())); + tcp.close(); + return; + } + if(stoped) { + tcp.close(); + return; + }; + QJsonParseError parseErr; + QJsonDocument res = QJsonDocument::fromJson(resp, &parseErr); + for(int i=2; parseErr.error == QJsonParseError::UnterminatedString && i < 10; i++) { + if(! tcp.waitForReadyRead()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'consult' "+QString::number(i)); + tcp.close(); + return; + } + auto resp2 = tcp.readAll(); + if(resp2.isEmpty()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'consult' "+QString::number(i)); + tcp.close(); + return; + } + resp += resp2; + res = QJsonDocument::fromJson(resp, &parseErr); + } + if(parseErr.error != QJsonParseError::NoError) { + emit emErr(parseErr.errorString()+" when parse consult. size:"+QString::number(resp.size())); + tcp.close(); + return; + } + if(res["_type"].toString()=="consult") { + fileInfos.clear(); + fileInfos.append(QString(prog_dir+"/program")); + QJsonArray ids = res["idList"].toArray(); + foreach(auto id, ids) fileInfos.append(QString(prog_dir+"/"+id.toString())); + } + } + if(stoped) { + tcp.close(); + return; + } + qint64 progSize = 0; + foreach(auto fileInfo, fileInfos) progSize += fileInfo.size(); + if(progSize == 0) { + emit emErr(tr("Program is empty")); + tcp.close(); + return; + } + auto req = QJsonObject(); + req.insert("_type", "proStart"); + req.insert("proName", "program"); + req.insert("proSize", progSize); + req.insert("zVer","xixun1"); + auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proStart'"); + tcp.close(); + return; + } + if(stoped) { + tcp.close(); + return; + } + //4.发送协商列表应答里的文件 + long long sentBytes = 0; + foreach(auto info, fileInfos) if(info.isFile()) { + auto baseName = info.baseName(); + auto remain = info.size(); + req = QJsonObject(); + req.insert("_type", "fileStart"); + req.insert("id", baseName); + req.insert("size", remain); + req.insert("relative_path", ""); + req.insert("zVer","xixun1"); + auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileStart'"); + tcp.close(); + return; + } + auto file = new QFile(info.filePath()); + if(! file->open(QFile::ReadOnly)) { + emit emErr(tr("Open file failed")+" "+file->errorString()); + tcp.close(); + return; + } + while(remain > 0) { + auto readed = file->read(qMin(4096LL, remain)); + if(readed.isEmpty()) { + emit emErr(tr("Read file failed")+" "+file->errorString()); + tcp.close(); + file->close(); + return; + } + if(stoped) { + tcp.close(); + file->close(); + return; + }; + resNum = tcp.write(readed); + if(resNum == -1) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write file: "+file->fileName()); + tcp.close(); + file->close(); + return; + } + if(! tcp.waitForBytesWritten(60000)) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForWritten file: "+file->fileName()); + tcp.close(); + file->close(); + return; + } + if(stoped) { + tcp.close(); + file->close(); + return; + }; + remain -= resNum; + sentBytes += resNum; + if(sentBytes != 0) emit emProgress(sentBytes * 99 / progSize); + } + file->close(); + if(stoped) { + tcp.close(); + return; + }; + req = QJsonObject(); + req.insert("_type", "fileEnd"); + req.insert("id", baseName); + req.insert("zVer", "xixun1"); + resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileEnd'"); + tcp.close(); + return; + } + } + if(stoped) { + tcp.close(); + return; + }; + //5.发送结束 + req = QJsonObject(); + req.insert("_type", "proEnd"); + req.insert("proName", "program"); + req.insert("zVer","xixun1"); + resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); + if(resNum == -1 || ! tcp.waitForBytesWritten()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proEnd'"); + tcp.close(); + return; + }; + if(! tcp.waitForReadyRead()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'proEnd'"); + tcp.close(); + return; + } + auto resp = tcp.readAll(); + if(resp.isEmpty()) { + emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'proEnd'"); + tcp.close(); + return; + } + tcp.close(); + emit emProgress(100); + emit emErr("OK"); +} diff --git a/LedOK/wProgramManager/sendprogthread.h b/LedOK/program/sendprogthread.h similarity index 96% rename from LedOK/wProgramManager/sendprogthread.h rename to LedOK/program/sendprogthread.h index 890cc31..787fbea 100644 --- a/LedOK/wProgramManager/sendprogthread.h +++ b/LedOK/program/sendprogthread.h @@ -1,6 +1,5 @@ #ifndef SENDPROGTHREAD_H #define SENDPROGTHREAD_H -#include #include #include #include diff --git a/LedOK/wProgramManager/usbdetectdialog.cpp b/LedOK/program/usbdetectdialog.cpp similarity index 97% rename from LedOK/wProgramManager/usbdetectdialog.cpp rename to LedOK/program/usbdetectdialog.cpp index d25b739..8d16d57 100644 --- a/LedOK/wProgramManager/usbdetectdialog.cpp +++ b/LedOK/program/usbdetectdialog.cpp @@ -1,93 +1,93 @@ -#include "usbdetectdialog.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -UsbDetectDialog::UsbDetectDialog(QWidget *parent) : BaseDlg(parent) { - setAttribute(Qt::WA_DeleteOnClose); - setWindowTitle(tr("Usb upgrade program")); - resize(240, 220); - auto vBox = new QVBoxLayout(this); - - auto hBox = new QHBoxLayout(); - hBox->addStretch(); - auto bnClose = new QPushButton("X"); - bnClose->setProperty("ssType","progManageTool"); - bnClose->setFixedWidth(32); - connect(bnClose, &QPushButton::clicked, this, &BaseDlg::close); - hBox->addWidget(bnClose); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - hBox->addWidget(new QLabel(tr("Password"))); - - fdPassword = new QLineEdit(); - fdPassword->setEchoMode(QLineEdit::Password); - fdPassword->setPlaceholderText(tr("Input password")); - hBox->addWidget(fdPassword); - - vBox->addLayout(hBox); - - fdDrives = new QListWidget(); - fdDrives->setSelectionRectVisible(true); - fdDrives->setProperty("ssType", "usbList"); - fdDrives->setProperty("ssName", "usbListName"); - vBox->addWidget(fdDrives); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - auto bnOk = new QPushButton(tr("OK")); - bnOk->setProperty("ssType","progManageTool"); - connect(bnOk, &QPushButton::clicked, this, [this] { - auto selects = fdDrives->selectedItems(); - if(selects.count() > 0) { - for(auto select : selects) emit acceptData(select->text(), fdPassword->text()); - accept(); - return; - } - if(fdDrives->count() <= 0) QMessageBox::warning(this, tr("Tip"),tr("No checked USB device")); - else QMessageBox::warning(this, tr("Tip"),tr("please select usb device in list")); - }); - hBox->addWidget(bnOk); - hBox->addStretch(); - auto bnCancel = new QPushButton(tr("Cancel")); - bnCancel->setProperty("ssType","progManageTool"); - connect(bnCancel, &QPushButton::clicked, this, &BaseDlg::reject); - hBox->addWidget(bnCancel); - hBox->addStretch(); - vBox->addLayout(hBox); - - detectDriver(); - timerId = startTimer(3000); -} -void UsbDetectDialog::timerEvent(QTimerEvent *e) { - if(e->timerId() == timerId) detectDriver(); -} -void UsbDetectDialog::detectDriver() { - auto drives = QDir::drives(); //获取当前系统的盘符 - QStringList movables; - for(auto drive : drives) if(GetDriveType((WCHAR *) drive.filePath().utf16())==2) movables.append(drive.filePath()); - if(movables.size() == lastCnt) return; - if(movables.size() > lastCnt) { - for(auto movable : movables) { - for(int n=0; n < fdDrives->count(); n++) if(movable == fdDrives->item(n)->text()) goto exist; - fdDrives->addItem(movable); - exist:; - } - } else { - fdDrives->clear(); - fdDrives->addItems(movables); - } - lastCnt = movables.size(); - if(lastCnt==1) { - QListWidgetItem *item = fdDrives->item(0); - item->setSelected(true); - } -} +#include "usbdetectdialog.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +UsbDetectDialog::UsbDetectDialog(QWidget *parent) : BaseDlg(parent) { + setAttribute(Qt::WA_DeleteOnClose); + setWindowTitle(tr("Usb upgrade program")); + resize(240, 220); + auto vBox = new QVBoxLayout(this); + + auto hBox = new QHBoxLayout(); + hBox->addStretch(); + auto bnClose = new QPushButton("X"); + bnClose->setProperty("ssType","progManageTool"); + bnClose->setFixedWidth(32); + connect(bnClose, &QPushButton::clicked, this, &BaseDlg::close); + hBox->addWidget(bnClose); + + vBox->addLayout(hBox); + + hBox = new QHBoxLayout(); + hBox->addWidget(new QLabel(tr("Password"))); + + fdPassword = new QLineEdit(); + fdPassword->setEchoMode(QLineEdit::Password); + fdPassword->setPlaceholderText(tr("Input password")); + hBox->addWidget(fdPassword); + + vBox->addLayout(hBox); + + fdDrives = new QListWidget(); + fdDrives->setSelectionRectVisible(true); + fdDrives->setProperty("ssType", "usbList"); + fdDrives->setProperty("ssName", "usbListName"); + vBox->addWidget(fdDrives); + + hBox = new QHBoxLayout(); + hBox->addStretch(); + auto bnOk = new QPushButton(tr("OK")); + bnOk->setProperty("ssType","progManageTool"); + connect(bnOk, &QPushButton::clicked, this, [this] { + auto selects = fdDrives->selectedItems(); + if(selects.count() > 0) { + for(auto select : selects) emit acceptData(select->text(), fdPassword->text()); + accept(); + return; + } + if(fdDrives->count() <= 0) QMessageBox::warning(this, tr("Tip"),tr("No checked USB device")); + else QMessageBox::warning(this, tr("Tip"),tr("please select usb device in list")); + }); + hBox->addWidget(bnOk); + hBox->addStretch(); + auto bnCancel = new QPushButton(tr("Cancel")); + bnCancel->setProperty("ssType","progManageTool"); + connect(bnCancel, &QPushButton::clicked, this, &BaseDlg::reject); + hBox->addWidget(bnCancel); + hBox->addStretch(); + vBox->addLayout(hBox); + + detectDriver(); + timerId = startTimer(3000); +} +void UsbDetectDialog::timerEvent(QTimerEvent *e) { + if(e->timerId() == timerId) detectDriver(); +} +void UsbDetectDialog::detectDriver() { + auto drives = QDir::drives(); //获取当前系统的盘符 + QStringList movables; + for(auto drive : drives) if(GetDriveType((WCHAR *) drive.filePath().utf16())==2) movables.append(drive.filePath()); + if(movables.size() == lastCnt) return; + if(movables.size() > lastCnt) { + for(auto movable : movables) { + for(int n=0; n < fdDrives->count(); n++) if(movable == fdDrives->item(n)->text()) goto exist; + fdDrives->addItem(movable); + exist:; + } + } else { + fdDrives->clear(); + fdDrives->addItems(movables); + } + lastCnt = movables.size(); + if(lastCnt==1) { + QListWidgetItem *item = fdDrives->item(0); + item->setSelected(true); + } +} diff --git a/LedOK/wProgramManager/usbdetectdialog.h b/LedOK/program/usbdetectdialog.h similarity index 95% rename from LedOK/wProgramManager/usbdetectdialog.h rename to LedOK/program/usbdetectdialog.h index 1bb38b8..01fbd46 100644 --- a/LedOK/wProgramManager/usbdetectdialog.h +++ b/LedOK/program/usbdetectdialog.h @@ -1,25 +1,25 @@ -#ifndef USBDETECTDIALOG_H -#define USBDETECTDIALOG_H - -#include -#include - -class UsbDetectDialog : public BaseDlg { - Q_OBJECT -public: - explicit UsbDetectDialog(QWidget *parent = nullptr); - ~UsbDetectDialog() {if(timerId!=0) killTimer(timerId);} -protected: - void timerEvent(QTimerEvent *) override; -signals: - void acceptData(QString string1, QString string2); -private: - void detectDriver(); - QListWidget *fdDrives; - QLineEdit *fdPassword; - int timerId = 0; - int lastCnt = 0; - -}; - -#endif // USBDETECTDIALOG_H +#ifndef USBDETECTDIALOG_H +#define USBDETECTDIALOG_H + +#include +#include + +class UsbDetectDialog : public BaseDlg { + Q_OBJECT +public: + explicit UsbDetectDialog(QWidget *parent = nullptr); + ~UsbDetectDialog() {if(timerId!=0) killTimer(timerId);} +protected: + void timerEvent(QTimerEvent *) override; +signals: + void acceptData(QString string1, QString string2); +private: + void detectDriver(); + QListWidget *fdDrives; + QLineEdit *fdPassword; + int timerId = 0; + int lastCnt = 0; + +}; + +#endif // USBDETECTDIALOG_H diff --git a/LedOK/wProgramManager/videosplitthread.cpp b/LedOK/program/videosplitthread.cpp similarity index 76% rename from LedOK/wProgramManager/videosplitthread.cpp rename to LedOK/program/videosplitthread.cpp index 3253bbb..c15b591 100644 --- a/LedOK/wProgramManager/videosplitthread.cpp +++ b/LedOK/program/videosplitthread.cpp @@ -1,205 +1,212 @@ -#include "videosplitthread.h" -#include -#include -#include -extern "C"{ -#include -#include -#include -} -VideoSplitThread::VideoSplitThread(int sw, int sh, int dw, int dh, int cnt, QPointF pos, QByteArray file) : sw(sw), sh(sh), dw(dw), dh(dh), cnt(cnt), pos(pos), file(file) { - connect(this, &QThread::finished, this, &QThread::deleteLater); -} - -void VideoSplitThread::run() { - AVFormatContext *in_fmt = avformat_alloc_context(), *out_fmt = 0; - AVCodecContext *de_ctx = 0, *en_ctx = 0; - QString err; - char buf[AV_ERROR_MAX_STRING_SIZE]; - int ret; - { - if((ret = avformat_open_input(&in_fmt, file.constData(), nullptr, nullptr)) < 0) { - err = QString("Couldn't open input stream. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - if((ret = avformat_find_stream_info(in_fmt, nullptr)) < 0) { - err = QString("Couldn't find stream information. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - auto outfile = file+"-square.mp4"; - if((ret = avformat_alloc_output_context2(&out_fmt, 0, "mp4", outfile.constData())) < 0) { - err = QString("avformat_alloc_output_context2 fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - int vi_idx = -1; - AVStream *out_vi_stream; - for(uint ss=0; ssnb_streams; ss++) { - AVStream *stream = in_fmt->streams[ss]; - qDebug()<<"codec_type"<codecpar->codec_type); - if(stream->codecpar->codec_type == AVMEDIA_TYPE_DATA) continue; - AVStream *out_stream = avformat_new_stream(out_fmt, 0); - if(vi_idx == -1 && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { - vi_idx = ss; - out_vi_stream = out_stream; - } else { - if((ret = avcodec_parameters_copy(out_stream->codecpar, stream->codecpar)) < 0) { - err = QString("avcodec_parameters_copy fail. ") + av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - } - out_stream->time_base = stream->time_base; - out_stream->start_time = stream->start_time; - out_stream->duration = stream->duration; - } - if(vi_idx == -1) { - err = "Didn't find a Video Stream"; - goto free; - } - - auto codecpar = in_fmt->streams[vi_idx]->codecpar; - - auto decoder = avcodec_find_decoder(codecpar->codec_id); - if(decoder==0) { - err = "Could not found Video Decoder"; - goto free; - } - de_ctx = avcodec_alloc_context3(decoder); - de_ctx->thread_count = 4; - avcodec_parameters_to_context(de_ctx, codecpar); - if(avcodec_open2(de_ctx, decoder, 0) < 0) { - err = "Could not open Video decode Ctx"; - goto free; - } - - auto out_codecpar = out_vi_stream->codecpar; - out_codecpar->codec_type = AVMEDIA_TYPE_VIDEO; - out_codecpar->codec_id = AV_CODEC_ID_H264; - out_codecpar->format = AV_PIX_FMT_YUV420P; - out_codecpar->width = dw; - out_codecpar->height = dh; - - auto encoder = avcodec_find_encoder(out_codecpar->codec_id); - if(encoder==0) { - fprintf(stderr, "Codec not found\n"); - goto free; - } - en_ctx = avcodec_alloc_context3(encoder); - en_ctx->thread_count = 4; - avcodec_parameters_to_context(en_ctx, out_codecpar); - en_ctx->bit_rate = dw*dh*6; - en_ctx->gop_size = de_ctx->gop_size; - en_ctx->max_b_frames = 3; - en_ctx->time_base = out_vi_stream->time_base; - - if((ret = avcodec_open2(en_ctx, encoder, 0)) < 0) { - err = QString("Open video encode ctx failed. ") + av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - if(out_fmt->flags & AVFMT_NOFILE) qDebug()<<"AVFMT_NOFILE"; - else if((ret = avio_open(&out_fmt->pb, outfile.constData(), AVIO_FLAG_WRITE)) < 0) { - err = QString("avio_open fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - qDebug()<<"oformat"<oformat; - if((ret = avformat_write_header(out_fmt, 0)) < 0) { - err = QString("avformat_write_header fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free; - } - auto sws_ctx = sws_getContext(de_ctx->width, de_ctx->height, de_ctx->pix_fmt, sw, sh, AV_PIX_FMT_0RGB, SWS_FAST_BILINEAR, 0, 0, 0); - auto out_sws_ctx = sws_getContext(dw, dh, AV_PIX_FMT_0RGB, dw, dh, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, 0, 0, 0); - auto packet = av_packet_alloc(); - auto frm = av_frame_alloc(); - QImage img(sw, sh, QImage::Format_RGB32); - uint8_t *img_data[4]{img.bits(), 0, 0, 0}; - int img_linesize[4]{img.bytesPerLine(), 0, 0, 0}; - QImage out_img(dw, dh, QImage::Format_RGB32); - uint8_t *out_img_data[4]{out_img.bits(), 0, 0, 0}; - int out_img_linesize[4]{out_img.bytesPerLine(), 0, 0, 0}; - QPainter painter(&out_img); - while(1) { - if((ret = av_read_frame(in_fmt, packet)) < 0) { - if(ret!=AVERROR_EOF) { - err = QString("Read packet fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - break; - } - ret = avcodec_send_packet(de_ctx, 0); - } else { - if(packet->stream_index != vi_idx) { - av_interleaved_write_frame(out_fmt, packet); - continue; - } - ret = avcodec_send_packet(de_ctx, packet); - } - if(ret < 0) { - err = QString("avcodec_send_packet fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - break; - } - while((ret = avcodec_receive_frame(de_ctx, frm)) != AVERROR(EAGAIN)) { - if(ret < 0) { - if(ret!=AVERROR_EOF) { - err = QString("Receive frame fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free2; - } - ret = avcodec_send_frame(en_ctx, 0); - } else { - sws_scale(sws_ctx, frm->data, frm->linesize, 0, de_ctx->height, img_data, img_linesize); - painter.drawImage(pos, img); - auto apos = pos; - for(int i=1; ipts; - auto dur = frm->pkt_duration; - av_frame_unref(frm); - frm->pts = pts; - frm->pkt_duration = dur; - frm->format = AV_PIX_FMT_YUV420P; - frm->width = dw; - frm->height = dh; - if((ret = av_frame_get_buffer(frm, 0)) < 0) { - err = QString("av_frame_get_buffer fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free2; - } - sws_scale(out_sws_ctx, out_img_data, out_img_linesize, 0, dh, frm->data, frm->linesize); - ret = avcodec_send_frame(en_ctx, frm); - int pro = frm->pts*100/out_vi_stream->duration; - if(pro > lastPro) { - lastPro = pro; - emit emProgress(pro); - } - } - if(ret < 0) { - err = QString("avcodec_send_frame fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - goto free2; - } - while((ret = avcodec_receive_packet(en_ctx, packet)) != AVERROR(EAGAIN)) { - if(ret < 0) { - if(ret!=AVERROR_EOF) err = QString("Receive frame fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); - else { - av_interleaved_write_frame(out_fmt, 0); - av_write_trailer(out_fmt); - emit emProgress(100); - } - goto free2; - } else { - av_interleaved_write_frame(out_fmt, packet); - } - } - } - } - free2: - av_frame_free(&frm); - av_packet_free(&packet); - sws_freeContext(sws_ctx); - sws_freeContext(out_sws_ctx); - } - free: - avcodec_free_context(&de_ctx); - avcodec_free_context(&en_ctx); - avformat_close_input(&in_fmt); - avio_closep(&out_fmt->pb); - if(out_fmt) avformat_free_context(out_fmt); - emit emErr(err); -} +#include "videosplitthread.h" +#include +#include +#include +extern "C"{ +#include +#include +#include +} + +static void imgCleanupHandler(void *info) { + delete [] (uchar*)info; +} + +VideoSplitThread::VideoSplitThread(int elew, int eleh, int dpw, int sph, QList &widths, QPointF pos, QByteArray file) : mEleW(elew), mEleH(eleh), mDPW(dpw), mSPH(sph), mWidths(widths), pos(pos), file(file) { + connect(this, &QThread::finished, this, &QThread::deleteLater); +} + +void VideoSplitThread::run() { + AVFormatContext *in_fmt = avformat_alloc_context(), *out_fmt = 0; + AVCodecContext *de_ctx = 0, *en_ctx = 0; + QString err; + char buf[AV_ERROR_MAX_STRING_SIZE]; + int ret; + { + if((ret = avformat_open_input(&in_fmt, file.constData(), 0, 0)) < 0) { + err = QString("Couldn't open input stream. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + if((ret = avformat_find_stream_info(in_fmt, nullptr)) < 0) { + err = QString("Couldn't find stream information. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + auto outfile = file+"-square.mp4"; + if((ret = avformat_alloc_output_context2(&out_fmt, 0, "mp4", outfile.constData())) < 0) { + err = QString("avformat_alloc_output_context2 fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + int vi_idx = -1; + AVStream *out_vi_stream; + for(uint ss=0; ssnb_streams; ss++) { + AVStream *stream = in_fmt->streams[ss]; + qDebug()<<"codec_type"<codecpar->codec_type); + if(stream->codecpar->codec_type == AVMEDIA_TYPE_DATA) continue; + AVStream *out_stream = avformat_new_stream(out_fmt, 0); + if(vi_idx == -1 && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { + vi_idx = ss; + out_vi_stream = out_stream; + } else { + if((ret = avcodec_parameters_copy(out_stream->codecpar, stream->codecpar)) < 0) { + err = QString("avcodec_parameters_copy fail. ") + av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + } + out_stream->time_base = stream->time_base; + out_stream->start_time = stream->start_time; + out_stream->duration = stream->duration; + } + if(vi_idx == -1) { + err = "Didn't find a Video Stream"; + goto free; + } + + auto codecpar = in_fmt->streams[vi_idx]->codecpar; + + auto decoder = avcodec_find_decoder(codecpar->codec_id); + if(decoder==0) { + err = "Could not found Video Decoder"; + goto free; + } + de_ctx = avcodec_alloc_context3(decoder); + de_ctx->thread_count = 4; + avcodec_parameters_to_context(de_ctx, codecpar); + if(avcodec_open2(de_ctx, decoder, 0) < 0) { + err = "Could not open Video decode Ctx"; + goto free; + } + + auto outPar = out_vi_stream->codecpar; + outPar->codec_type = AVMEDIA_TYPE_VIDEO; + outPar->codec_id = AV_CODEC_ID_H264; + outPar->format = AV_PIX_FMT_YUV420P; + outPar->width = mDPW; + outPar->height = mSPH*mWidths.size(); + + auto encoder = avcodec_find_encoder(outPar->codec_id); + if(encoder==0) { + fprintf(stderr, "Codec not found\n"); + goto free; + } + en_ctx = avcodec_alloc_context3(encoder); + en_ctx->thread_count = 4; + avcodec_parameters_to_context(en_ctx, outPar); + en_ctx->bit_rate = outPar->width * outPar->height * 6; + en_ctx->gop_size = de_ctx->gop_size; + en_ctx->max_b_frames = 3; + en_ctx->time_base = out_vi_stream->time_base; + + if((ret = avcodec_open2(en_ctx, encoder, 0)) < 0) { + err = QString("Open video encode ctx failed. ") + av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + if(out_fmt->flags & AVFMT_NOFILE) qDebug()<<"AVFMT_NOFILE"; + else if((ret = avio_open(&out_fmt->pb, outfile.constData(), AVIO_FLAG_WRITE)) < 0) { + err = QString("avio_open fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + if((ret = avformat_write_header(out_fmt, 0)) < 0) { + err = QString("avformat_write_header fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free; + } + auto sws_ctx = sws_getContext(de_ctx->width, de_ctx->height, de_ctx->pix_fmt, mEleW, mEleH, AV_PIX_FMT_RGB32, SWS_FAST_BILINEAR, 0, 0, 0); + auto out_sws_ctx = sws_getContext(outPar->width, outPar->height, AV_PIX_FMT_RGB32, outPar->width, outPar->height, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, 0, 0, 0); + auto packet = av_packet_alloc(); + auto frm = av_frame_alloc(); + + int img_linesize[4]{(mEleW*4+63)/64*64}; + uint8_t *img_data[4]{new uchar[img_linesize[0] * mEleH]}; + QImage img(img_data[0], mEleW, mEleH, img_linesize[0], QImage::Format_ARGB32, imgCleanupHandler, img_data[0]); + + int out_img_linesize[4]{(outPar->width*4+63)/64*64}; + uint8_t *out_img_data[4]{new uchar[out_img_linesize[0] * outPar->height]}; + QImage out_img(out_img_data[0], outPar->width, outPar->height, out_img_linesize[0], QImage::Format_ARGB32, imgCleanupHandler, out_img_data[0]); + QPainter painter(&out_img); + auto end = mWidths.size() - 1; + while(1) { + if((ret = av_read_frame(in_fmt, packet)) < 0) { + if(ret!=AVERROR_EOF) { + err = QString("Read packet fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + break; + } + ret = avcodec_send_packet(de_ctx, 0); + } else { + if(packet->stream_index != vi_idx) { + av_interleaved_write_frame(out_fmt, packet); + continue; + } + ret = avcodec_send_packet(de_ctx, packet); + } + if(ret < 0) { + err = QString("avcodec_send_packet fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + break; + } + while((ret = avcodec_receive_frame(de_ctx, frm)) != AVERROR(EAGAIN)) { + if(ret < 0) { + if(ret!=AVERROR_EOF) { + err = QString("Receive frame fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free2; + } + ret = avcodec_send_frame(en_ctx, 0); + } else { + sws_scale(sws_ctx, frm->data, frm->linesize, 0, de_ctx->height, img_data, img_linesize); + auto apos = pos; + painter.drawImage(apos, img, QRectF(0, 0, mWidths[0]-apos.rx(), img.height())); + for(int i=0; ipts; + auto dur = frm->pkt_duration; + av_frame_unref(frm); + frm->pts = pts; + frm->pkt_duration = dur; + frm->format = AV_PIX_FMT_YUV420P; + frm->width = outPar->width; + frm->height = outPar->height; + if((ret = av_frame_get_buffer(frm, 0)) < 0) { + err = QString("av_frame_get_buffer fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free2; + } + sws_scale(out_sws_ctx, out_img_data, out_img_linesize, 0, outPar->height, frm->data, frm->linesize); + ret = avcodec_send_frame(en_ctx, frm); + int pro = frm->pts*100/out_vi_stream->duration; + if(pro > lastPro) { + lastPro = pro; + emit emProgress(pro); + } + } + if(ret < 0) { + err = QString("avcodec_send_frame fail. ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + goto free2; + } + while((ret = avcodec_receive_packet(en_ctx, packet)) != AVERROR(EAGAIN)) { + if(ret < 0) { + if(ret!=AVERROR_EOF) err = QString("Receive frame fail: ")+av_make_error_string(buf, AV_ERROR_MAX_STRING_SIZE, ret); + else { + av_interleaved_write_frame(out_fmt, 0); + av_write_trailer(out_fmt); + emit emProgress(100); + } + goto free2; + } else { + av_interleaved_write_frame(out_fmt, packet); + } + } + } + } + free2: + av_frame_free(&frm); + av_packet_free(&packet); + sws_freeContext(sws_ctx); + sws_freeContext(out_sws_ctx); + } + free: + avcodec_free_context(&de_ctx); + avcodec_free_context(&en_ctx); + avformat_close_input(&in_fmt); + avio_closep(&out_fmt->pb); + if(out_fmt) avformat_free_context(out_fmt); + emit emErr(err); +} diff --git a/LedOK/wProgramManager/videosplitthread.h b/LedOK/program/videosplitthread.h similarity index 72% rename from LedOK/wProgramManager/videosplitthread.h rename to LedOK/program/videosplitthread.h index 5280080..d2ea440 100644 --- a/LedOK/wProgramManager/videosplitthread.h +++ b/LedOK/program/videosplitthread.h @@ -6,8 +6,9 @@ class VideoSplitThread : public QThread { Q_OBJECT public: - VideoSplitThread(int sw, int sh, int dw, int dh, int cnt, QPointF pos, QByteArray file); - int sw, sh, dw, dh, cnt; + VideoSplitThread(int elew, int eleh, int dpw, int sph, QList &, QPointF pos, QByteArray file); + int mEleW, mEleH, mDPW, mSPH; + QList mWidths; QPointF pos; QByteArray file; protected: diff --git a/LedOK/wProgramManager/wplanitem.cpp b/LedOK/program/wplanitem.cpp similarity index 100% rename from LedOK/wProgramManager/wplanitem.cpp rename to LedOK/program/wplanitem.cpp diff --git a/LedOK/wProgramManager/wplanitem.h b/LedOK/program/wplanitem.h similarity index 100% rename from LedOK/wProgramManager/wplanitem.h rename to LedOK/program/wplanitem.h diff --git a/LedOK/wProgramManager/wplanitem.ui b/LedOK/program/wplanitem.ui similarity index 100% rename from LedOK/wProgramManager/wplanitem.ui rename to LedOK/program/wplanitem.ui diff --git a/LedOK/wProgramManager/wplanlist.cpp b/LedOK/program/wplanlist.cpp similarity index 100% rename from LedOK/wProgramManager/wplanlist.cpp rename to LedOK/program/wplanlist.cpp diff --git a/LedOK/wProgramManager/wplanlist.h b/LedOK/program/wplanlist.h similarity index 100% rename from LedOK/wProgramManager/wplanlist.h rename to LedOK/program/wplanlist.h diff --git a/LedOK/wProgramManager/wprogrampublishitem.cpp b/LedOK/program/wprogrampublishitem.cpp similarity index 95% rename from LedOK/wProgramManager/wprogrampublishitem.cpp rename to LedOK/program/wprogrampublishitem.cpp index af0e185..d14ce63 100644 --- a/LedOK/wProgramManager/wprogrampublishitem.cpp +++ b/LedOK/program/wprogrampublishitem.cpp @@ -83,7 +83,7 @@ void wProgramPublishItem::SetPasswordItem(LedCard *card) { m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock); connect(m_bnLock, SIGNAL(clicked()), this, SLOT(onVerifyLockPassword())); } - m_bnLock->setIcon(QIcon(card->m_bLockStatus ? ":/res/DeviceManager/Lock.png" : ":/res/DeviceManager/UnLock.png")); //如果已经验证通过密码显示绿色图标 没有验证显示蓝色锁图标 + m_bnLock->setIcon(QIcon(card->m_bLockStatus ? ":/res/device/Lock.png" : ":/res/device/UnLock.png")); //如果已经验证通过密码显示绿色图标 没有验证显示蓝色锁图标 m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock); } @@ -92,7 +92,7 @@ void wProgramPublishItem::SetItemParam(LedCard *p) { setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, p->m_strCardRemarkName); setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, p->m_strCardIp); setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, QString("%1 x %2").arg(p->m_iWidth).arg(p->m_iHeight)); - m_ImageOnline->setPixmap(QPixmap(mLedCard->m_bOnLine ? ":/res/DeviceManager/O_Online.png" : ":/res/DeviceManager/O_Offline.png")); + m_ImageOnline->setPixmap(QPixmap(mLedCard->m_bOnLine ? ":/res/device/O_Online.png" : ":/res/device/O_Offline.png")); SetPasswordItem(mLedCard); // //progresss.append(progress); diff --git a/LedOK/wProgramManager/wprogrampublishitem.h b/LedOK/program/wprogrampublishitem.h similarity index 97% rename from LedOK/wProgramManager/wprogrampublishitem.h rename to LedOK/program/wprogrampublishitem.h index 7e2d97a..958b447 100644 --- a/LedOK/wProgramManager/wprogrampublishitem.h +++ b/LedOK/program/wprogrampublishitem.h @@ -13,7 +13,7 @@ #include #include #include -#include +#include class wProgramPublishItem : public QObject, public QTreeWidgetItem { Q_OBJECT diff --git a/LedOK/qss.qrc b/LedOK/qss.qrc deleted file mode 100644 index 6345d43..0000000 --- a/LedOK/qss.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - qss/00_Common.css - qss/10_MainWindow.css - - diff --git a/LedOK/qss/00_Common.css b/LedOK/qss/00_Common.css deleted file mode 100644 index abd0697..0000000 --- a/LedOK/qss/00_Common.css +++ /dev/null @@ -1,125 +0,0 @@ -QLineEdit,QComboBox,QAbstractSpinBox { - border: 1px solid #aaaaaa; - border-radius: 3px; - padding: 2px; -} - -QGroupBox { - border: 1px solid #aaaaaa; - border-radius: 3px; - margin-top: 1.2ex; - padding-top: 1ex; -} -QGroupBox::title { - subcontrol-origin: margin; - position: relative; - left: 1.4ex; -} - -QComboBox::drop-down, -QAbstractSpinBox::up-button, -QAbstractSpinBox::down-button { - border: 0; -} -QComboBox::down-arrow, -QAbstractSpinBox::down-arrow { - image: url(:/res/ArrowDropDown.png); -} -QComboBox::down-arrow:on, -QAbstractSpinBox::up-arrow { - image: url(:/res/ArrowDropUp.png); -} - -QAbstractSpinBox::up-arrow:pressed { - top: -1px; -} -QAbstractSpinBox::down-arrow:pressed { - top: 1px; -} - -QCheckBox::indicator { - width: 24px; - height: 24px; -} -QCheckBox::indicator:disabled { - background-color: #666666; -} -QCheckBox::indicator:unchecked { - image: url(:/res/CheckBoxUnchecked.png); -} -QCheckBox::indicator:checked { - image: url(:/res/CheckBoxChecked.png); -} - -ExtendedGroupBox::indicator { - width: 10px; - height: 10px; -} -ExtendedGroupBox::indicator:unchecked { - image: url(:/res/ProgramManager/EditProgram/uncheck.png); -} -ExtendedGroupBox::indicator:checked { - image: url(:/res/ProgramManager/EditProgram/check.png); -} - -QScrollArea { - border : 0; -} -QScrollBar:vertical { - width: 12px; -} -QScrollBar:horizontal { - height: 12px; -} - -QMenu { - background-color: #eeeeee; - border: 2px solid #cccccc; -} -QMenu::item { - background-color: transparent; -} -QMenu::item:selected { - background-color: #8FC0D6; -} -QMenu::indicator:exclusive:checked { - image: url(:/res/RadioChecked.png); -} - -QToolBar::separator { - background-color: #888888; - width: 1px; -} - -LoColorSelector { - border: 1px solid #aaaaaa; - border-radius: 4px; - background-color: transparent; - padding: 3px 6px; - max-height: 30px; -} - -QTreeWidget[ssType="topList"]::item { - border-right: 1px solid #dddddd; - border-bottom: 1px solid #dddddd; - height: 40px; -} -QTreeWidget[ssType="topList"] QHeaderView::section { - border-top: 1px solid #aaaaaa; - border-bottom: 1px solid #aaaaaa; - border-left: 0; - border-right: 0; - height: 36px; -} -QTreeWidget[ssType="topList"]::item:hover { - background-color: #dddddd; -} - -QTreeWidget[ssType="topList"]::indicator, -QTreeWidget[ssType="topList"]::indicator:unchecked { - image: url(:/res/CheckBoxUnchecked.png); -} -QTreeWidget[ssType="topList"]::indicator:checked { - image: url(:/res/CheckBoxChecked.png); -} - diff --git a/LedOK/qss/10_MainWindow.css b/LedOK/qss/10_MainWindow.css deleted file mode 100644 index fecc69b..0000000 --- a/LedOK/qss/10_MainWindow.css +++ /dev/null @@ -1,70 +0,0 @@ -QPushButton[ssType="progManageTool"] { - border-radius: 4px; - background-color: #19c; - color: #000; - padding: 3px 6px; -} -QPushButton[ssType="progManageTool"]:hover { - background-color: #08b; - color: #fff; -} -QPushButton[ssType="progManageTool"]:pressed { - background-color: #07a; -} -QPushButton[ssType="progManageTool"]:disabled { - background-color: #bbb; - color: #777; -} - - -LoQTitleBar QPushButton { - border-radius: 4px; - icon-size: 20px; - width: 32px; - height: 28px; -} -LoQTitleBar QPushButton:press, -LoQTitleBar QPushButton:hover { - background-color: #C1C1C1; -} -LoQTitleBar QPushButton::menu-indicator { - image: none; -} - - -QToolButton[ss="MainTab"], -QToolButton[ss="CtrlTab"] { - border: none; -} -QToolButton[ss="MainTab"]:checked, -QToolButton[ss="MainTab"]:hover { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ddd, stop: 1.0 #8cd); - font-size: 15px; - color: #04d; -} -QToolButton[ss="CtrlTab"]:checked, -QToolButton[ss="CtrlTab"]:hover { - background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eee, stop: 1.0 #ade); - font-size: 15px; - color: #04d; -} - - -QPushButton#bnSelectFile { - border-radius: 4px; - background-color: #19c; - border: 1px solid #888; - padding: 3px 6px; -} -QPushButton#bnSelectFile:pressed { - background: transparent; -} - -QPushButton[style="multiTool"] { - border-radius: 4px; - padding: 3px 6px; -} -QPushButton[style="multiTool"]:hover { - background-color: rgba(226,226,226,1); -} - diff --git a/LedOK/res.qrc b/LedOK/res.qrc index d24f825..a40e718 100644 --- a/LedOK/res.qrc +++ b/LedOK/res.qrc @@ -1,209 +1,201 @@ - - - res/AdvParam.png - res/AppSetting.png - res/AppSettingTip.png - res/ArrowDropDown.png - res/ArrowDropUp.png - res/CheckBoxChecked.png - res/CheckBoxUnchecked.png - res/DeviceManager/Add.png - res/DeviceManager/DeviceNum_All.png - res/DeviceManager/DeviceNum_Offline.png - res/DeviceManager/DeviceNum_Online.png - res/DeviceManager/DeviceNum_Unlogin.png - res/DeviceManager/Equal.png - res/DeviceManager/FlashArrow.png - res/DeviceManager/Lock.png - res/DeviceManager/O_Offline.png - res/DeviceManager/O_Online.png - res/DeviceManager/O_Unlogin.png - res/DeviceManager/Transparent.png - res/DeviceManager/UnLock.png - res/DeviceManager/bnDetail.png - res/DeviceManager/deviceReadbackPic.png - res/DeviceManager_s.png - res/DeviceManager_u.png - res/DeviceSetting_s.png - res/DeviceSetting_u.png - res/GuangYingPin_s.png - res/GuangYingPin_u.png - res/Hdmi.png - res/Logo.ico - res/Logo.png - res/Lora.png - res/ProgramManager/EditProgram/AClock.png - res/ProgramManager/EditProgram/Add.png - res/ProgramManager/EditProgram/AddPlan.png - res/ProgramManager/EditProgram/ArrayBottom.png - res/ProgramManager/EditProgram/ArrayHCenter.png - res/ProgramManager/EditProgram/ArrayLeft.png - res/ProgramManager/EditProgram/ArrayRight.png - res/ProgramManager/EditProgram/ArrayTop.png - res/ProgramManager/EditProgram/ArrayVCenter.png - res/ProgramManager/EditProgram/Audio.png - res/ProgramManager/EditProgram/Clean.png - res/ProgramManager/EditProgram/CleanPlan.png - res/ProgramManager/EditProgram/ColorText.png - res/ProgramManager/EditProgram/Copy.png - res/ProgramManager/EditProgram/Cut.png - res/ProgramManager/EditProgram/DClock.png - res/ProgramManager/EditProgram/DateSelect.png - res/ProgramManager/EditProgram/DateSelect_enable.png - res/ProgramManager/EditProgram/Delete.png - res/ProgramManager/EditProgram/DocAlignHC_s.png - res/ProgramManager/EditProgram/DocAlignHC_u.png - res/ProgramManager/EditProgram/DocAlignHL_s.png - res/ProgramManager/EditProgram/DocAlignHL_u.png - res/ProgramManager/EditProgram/DocAlignHR_s.png - res/ProgramManager/EditProgram/DocAlignHR_u.png - res/ProgramManager/EditProgram/DocAlignVB_s.png - res/ProgramManager/EditProgram/DocAlignVB_u.png - res/ProgramManager/EditProgram/DocAlignVC_s.png - res/ProgramManager/EditProgram/DocAlignVC_u.png - res/ProgramManager/EditProgram/DocAlignVT_s.png - res/ProgramManager/EditProgram/DocAlignVT_u.png - res/ProgramManager/EditProgram/FontBold_s.png - res/ProgramManager/EditProgram/FontBold_u.png - res/ProgramManager/EditProgram/FontItalics_s.png - res/ProgramManager/EditProgram/FontItalics_u.png - res/ProgramManager/EditProgram/FontUnderline_s.png - res/ProgramManager/EditProgram/FontUnderline_u.png - res/ProgramManager/EditProgram/Gif.png - res/ProgramManager/EditProgram/GoDown.png - res/ProgramManager/EditProgram/GoUp.png - res/ProgramManager/EditProgram/LayerBottom.png - res/ProgramManager/EditProgram/LayerDown.png - res/ProgramManager/EditProgram/LayerTop.png - res/ProgramManager/EditProgram/LayerUp.png - res/ProgramManager/EditProgram/Movie.png - res/ProgramManager/EditProgram/Office.png - res/ProgramManager/EditProgram/Photo.png - res/ProgramManager/EditProgram/RadioChecked.png - res/ProgramManager/EditProgram/RadioUnchecked.png - res/ProgramManager/EditProgram/Rss.png - res/ProgramManager/EditProgram/Save.png - res/ProgramManager/EditProgram/SaveAs.png - res/ProgramManager/EditProgram/ScaleDown.png - res/ProgramManager/EditProgram/ScaleOrg.png - res/ProgramManager/EditProgram/ScaleUp.png - res/ProgramManager/EditProgram/Send.png - res/ProgramManager/EditProgram/Setting.png - res/ProgramManager/EditProgram/Temp.png - res/ProgramManager/EditProgram/Text.png - res/ProgramManager/EditProgram/TileFull.png - res/ProgramManager/EditProgram/TileH.png - res/ProgramManager/EditProgram/TileV.png - res/ProgramManager/EditProgram/Timer.png - res/ProgramManager/EditProgram/Weather.png - res/ProgramManager/EditProgram/Web.png - res/ProgramManager/EditProgram/Window.png - res/ProgramManager/EditProgram/check.png - res/ProgramManager/EditProgram/preview.png - res/ProgramManager/EditProgram/previewStop.png - res/ProgramManager/EditProgram/uncheck.png - res/ProgramManager/bnExport_s.png - res/ProgramManager/bnExport_u.png - res/ProgramManager/bnSearch.png - res/ProgramManager/bnSend_s.png - res/ProgramManager/bnSend_u.png - res/ProgramManager_s.png - res/ProgramManager_u.png - res/RadioChecked.png - res/Warning.png - res/WndClose.png - res/WndMaximize.png - res/WndMinimize.png - res/apk.png - res/bnBrightnessAdjustMent_s.png - res/bnNetConfig_s.png - res/bnPowerControl_s.png - res/bnVerifyClock_s.png - res/borders/M1_0.bmp - res/borders/M1_1.bmp - res/borders/M1_2.bmp - res/borders/M1_3.bmp - res/borders/M1_4.bmp - res/borders/M1_5.bmp - res/borders/M1_6.bmp - res/borders/M1_7.bmp - res/borders/M1_8.bmp - res/borders/M2_0.bmp - res/borders/M2_1.bmp - res/borders/M2_2.bmp - res/borders/M2_3.bmp - res/borders/M2_5.bmp - res/borders/M2_6.bmp - res/borders/M2_7.bmp - res/borders/M2_8.bmp - res/borders/M3_0.bmp - res/borders/M3_1.bmp - res/borders/M3_2.bmp - res/borders/M3_3.bmp - res/borders/M3_4.bmp - res/borders/M3_5.bmp - res/borders/M3_6.bmp - res/borders/M3_7.bmp - res/borders/M3_8.bmp - res/borders/M4_0.bmp - res/borders/M4_1.bmp - res/borders/M4_2.bmp - res/borders/M4_3.bmp - res/borders/M4_4.bmp - res/borders/M4_5.bmp - res/borders/M4_6.bmp - res/borders/M4_7.bmp - res/borders/M4_8.bmp - res/borders/M5_0.bmp - res/borders/M5_1.bmp - res/borders/M5_2.bmp - res/borders/M5_3.bmp - res/borders/M5_4.bmp - res/borders/M5_5.bmp - res/borders/M5_6.bmp - res/borders/M5_7.bmp - res/borders/M5_8.bmp - res/borders/M6_0.bmp - res/borders/M6_1.bmp - res/borders/M6_2.bmp - res/borders/M6_3.bmp - res/borders/M6_4.bmp - res/borders/M6_5.bmp - res/borders/M6_6.bmp - res/borders/M6_7.bmp - res/borders/M6_8.bmp - res/borders/M6_9.bmp - res/borders/M7_0.bmp - res/borders/M7_1.bmp - res/borders/M7_2.bmp - res/borders/M7_3.bmp - res/borders/M7_4.bmp - res/borders/M7_5.bmp - res/borders/M7_6.bmp - res/borders/M7_7.bmp - res/borders/M7_8.bmp - res/borders/M8_0.bmp - res/borders/M8_1.bmp - res/borders/M8_2.bmp - res/borders/M8_3.bmp - res/borders/M8_4.bmp - res/borders/M8_5.bmp - res/borders/M8_6.bmp - res/borders/M8_7.bmp - res/borders/M8_8.bmp - res/borders/M9_0.bmp - res/encrypt.png - res/ledset.png - res/loop.png - res/next.png - res/previous.png - res/reddot.png - res/splash.png - res/success.png - res/test.png - res/tip.png - res/video-pre.png - res/volume.png - res/ProgramManager/EditProgram/DateSelect_e.png - - + + + res/signal-0.png + res/signal-1.png + res/signal-2.png + res/signal-3.png + res/signal-4.png + res/signal-5.png + css.css + res/AdvParam.png + res/AppSetting.png + res/AppSettingTip.png + res/ArrowDropDown.png + res/ArrowDropUp.png + res/CheckBoxChecked.png + res/CheckBoxUnchecked.png + res/device/Add.png + res/device/DeviceNum_All.png + res/device/DeviceNum_Offline.png + res/device/DeviceNum_Online.png + res/device/DeviceNum_Unlogin.png + res/device/Equal.png + res/device/FlashArrow.png + res/device/Lock.png + res/device/O_Offline.png + res/device/O_Online.png + res/device/O_Unlogin.png + res/device/UnLock.png + res/device/bnDetail.png + res/device/deviceReadbackPic.png + res/DeviceManager_s.png + res/DeviceManager_u.png + res/DeviceSetting_s.png + res/DeviceSetting_u.png + res/GuangYingPin_s.png + res/GuangYingPin_u.png + res/Hdmi.png + res/Logo.ico + res/Logo.png + res/Lora.png + res/program/AClock.png + res/program/Add.png + res/program/AddPlan.png + res/program/ArrayBottom.png + res/program/ArrayHCenter.png + res/program/ArrayLeft.png + res/program/ArrayRight.png + res/program/ArrayTop.png + res/program/ArrayVCenter.png + res/program/Audio.png + res/program/Clean.png + res/program/CleanPlan.png + res/program/ColorText.png + res/program/Copy.png + res/program/Cut.png + res/program/DClock.png + res/program/DateSelect.png + res/program/DateSelect_e.png + res/program/DateSelect_enable.png + res/program/Delete.png + res/program/TextAlignHC.png + res/program/TextAlignHL.png + res/program/TextAlignHR.png + res/program/TextAlignVB.png + res/program/TextAlignVC.png + res/program/TextAlignVT.png + res/program/Gif.png + res/program/GoDown.png + res/program/GoUp.png + res/program/LayerBottom.png + res/program/LayerDown.png + res/program/LayerTop.png + res/program/LayerUp.png + res/program/Movie.png + res/program/Office.png + res/program/Photo.png + res/program/Rss.png + res/program/Save.png + res/program/SaveAs.png + res/program/ScaleDown.png + res/program/ScaleOrg.png + res/program/ScaleUp.png + res/program/Send.png + res/program/Setting.png + res/program/Temp.png + res/program/Text.png + res/program/TileFull.png + res/program/TileH.png + res/program/TileV.png + res/program/Timer.png + res/program/Weather.png + res/program/Web.png + res/program/Window.png + res/program/preview.png + res/program/previewStop.png + res/program/bnExport_s.png + res/program/bnExport_u.png + res/program/bnSearch.png + res/program/bnSend_s.png + res/program/bnSend_u.png + res/ProgramManager_s.png + res/ProgramManager_u.png + res/Warning.png + res/WndClose.png + res/WndMaximize.png + res/WndMinimize.png + res/apk.png + res/bnBrightnessAdjustMent_s.png + res/bnNetConfig_s.png + res/bnPowerControl_s.png + res/bnVerifyClock_s.png + res/borders/M1_0.bmp + res/borders/M1_1.bmp + res/borders/M1_2.bmp + res/borders/M1_3.bmp + res/borders/M1_4.bmp + res/borders/M1_5.bmp + res/borders/M1_6.bmp + res/borders/M1_7.bmp + res/borders/M1_8.bmp + res/borders/M2_0.bmp + res/borders/M2_1.bmp + res/borders/M2_2.bmp + res/borders/M2_3.bmp + res/borders/M2_5.bmp + res/borders/M2_6.bmp + res/borders/M2_7.bmp + res/borders/M2_8.bmp + res/borders/M3_0.bmp + res/borders/M3_1.bmp + res/borders/M3_2.bmp + res/borders/M3_3.bmp + res/borders/M3_4.bmp + res/borders/M3_5.bmp + res/borders/M3_6.bmp + res/borders/M3_7.bmp + res/borders/M3_8.bmp + res/borders/M4_0.bmp + res/borders/M4_1.bmp + res/borders/M4_2.bmp + res/borders/M4_3.bmp + res/borders/M4_4.bmp + res/borders/M4_5.bmp + res/borders/M4_6.bmp + res/borders/M4_7.bmp + res/borders/M4_8.bmp + res/borders/M5_0.bmp + res/borders/M5_1.bmp + res/borders/M5_2.bmp + res/borders/M5_3.bmp + res/borders/M5_4.bmp + res/borders/M5_5.bmp + res/borders/M5_6.bmp + res/borders/M5_7.bmp + res/borders/M5_8.bmp + res/borders/M6_0.bmp + res/borders/M6_1.bmp + res/borders/M6_2.bmp + res/borders/M6_3.bmp + res/borders/M6_4.bmp + res/borders/M6_5.bmp + res/borders/M6_6.bmp + res/borders/M6_7.bmp + res/borders/M6_8.bmp + res/borders/M6_9.bmp + res/borders/M7_0.bmp + res/borders/M7_1.bmp + res/borders/M7_2.bmp + res/borders/M7_3.bmp + res/borders/M7_4.bmp + res/borders/M7_5.bmp + res/borders/M7_6.bmp + res/borders/M7_7.bmp + res/borders/M7_8.bmp + res/borders/M8_0.bmp + res/borders/M8_1.bmp + res/borders/M8_2.bmp + res/borders/M8_3.bmp + res/borders/M8_4.bmp + res/borders/M8_5.bmp + res/borders/M8_6.bmp + res/borders/M8_7.bmp + res/borders/M8_8.bmp + res/borders/M9_0.bmp + res/encrypt.png + res/groupbox-checked.png + res/groupbox-unchecked.png + res/ledset.png + res/loop.png + res/next.png + res/previous.png + res/random.png + res/reddot.png + res/splash.png + res/success.png + res/test.png + res/tip.png + res/video-pre.png + res/volume.png + + diff --git a/LedOK/res/128_128.png b/LedOK/res/128_128.png deleted file mode 100644 index 5cc7e8d..0000000 Binary files a/LedOK/res/128_128.png and /dev/null differ diff --git a/LedOK/res/CheckBoxChecked - 副本 - 副本.png b/LedOK/res/CheckBoxChecked - 副本 - 副本.png deleted file mode 100644 index 45877e1..0000000 Binary files a/LedOK/res/CheckBoxChecked - 副本 - 副本.png and /dev/null differ diff --git a/LedOK/res/CheckBoxChecked.png b/LedOK/res/CheckBoxChecked.png index 3293681..45877e1 100644 Binary files a/LedOK/res/CheckBoxChecked.png and b/LedOK/res/CheckBoxChecked.png differ diff --git a/LedOK/res/CheckBoxChecked24.png b/LedOK/res/CheckBoxChecked24.png deleted file mode 100644 index 2c70ecc..0000000 Binary files a/LedOK/res/CheckBoxChecked24.png and /dev/null differ diff --git a/LedOK/res/CheckBoxUnchecked - 副本 - 副本.png b/LedOK/res/CheckBoxUnchecked - 副本 - 副本.png deleted file mode 100644 index 8fffceb..0000000 Binary files a/LedOK/res/CheckBoxUnchecked - 副本 - 副本.png and /dev/null differ diff --git a/LedOK/res/CheckBoxUnchecked.png b/LedOK/res/CheckBoxUnchecked.png index 5a5b64c..8fffceb 100644 Binary files a/LedOK/res/CheckBoxUnchecked.png and b/LedOK/res/CheckBoxUnchecked.png differ diff --git a/LedOK/res/CheckBoxUnchecked24.png b/LedOK/res/CheckBoxUnchecked24.png deleted file mode 100644 index 219e244..0000000 Binary files a/LedOK/res/CheckBoxUnchecked24.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/Lock - 副本.png b/LedOK/res/DeviceManager/Lock - 副本.png deleted file mode 100644 index 82eded8..0000000 Binary files a/LedOK/res/DeviceManager/Lock - 副本.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/Transparent.png b/LedOK/res/DeviceManager/Transparent.png deleted file mode 100644 index c6c491e..0000000 Binary files a/LedOK/res/DeviceManager/Transparent.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/UnLock - 副本.png b/LedOK/res/DeviceManager/UnLock - 副本.png deleted file mode 100644 index 5d8e51c..0000000 Binary files a/LedOK/res/DeviceManager/UnLock - 副本.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/图层 4(1).png b/LedOK/res/DeviceManager/图层 4(1).png deleted file mode 100644 index d042c54..0000000 Binary files a/LedOK/res/DeviceManager/图层 4(1).png and /dev/null differ diff --git a/LedOK/res/DeviceManager/图层 4.png b/LedOK/res/DeviceManager/图层 4.png deleted file mode 100644 index 5271b3a..0000000 Binary files a/LedOK/res/DeviceManager/图层 4.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/图层 5 拷贝.png b/LedOK/res/DeviceManager/图层 5 拷贝.png deleted file mode 100644 index dad1e82..0000000 Binary files a/LedOK/res/DeviceManager/图层 5 拷贝.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/图层 5.png b/LedOK/res/DeviceManager/图层 5.png deleted file mode 100644 index 458df1b..0000000 Binary files a/LedOK/res/DeviceManager/图层 5.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/矩形 20.png b/LedOK/res/DeviceManager/矩形 20.png deleted file mode 100644 index 70cf53a..0000000 Binary files a/LedOK/res/DeviceManager/矩形 20.png and /dev/null differ diff --git a/LedOK/res/Logo2.png b/LedOK/res/Logo2.png deleted file mode 100644 index 6b13316..0000000 Binary files a/LedOK/res/Logo2.png and /dev/null differ diff --git a/LedOK/res/Logo3.png b/LedOK/res/Logo3.png deleted file mode 100644 index a13e3ae..0000000 Binary files a/LedOK/res/Logo3.png and /dev/null differ diff --git a/LedOK/res/Logo44.ico b/LedOK/res/Logo44.ico deleted file mode 100644 index 964ac37..0000000 Binary files a/LedOK/res/Logo44.ico and /dev/null differ diff --git a/LedOK/res/Lora.psd b/LedOK/res/Lora.psd deleted file mode 100644 index 96abe52..0000000 Binary files a/LedOK/res/Lora.psd and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock1.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock1.png deleted file mode 100644 index 766649e..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock1.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock10.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock10.png deleted file mode 100644 index cbcdafa..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock10.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock2.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock2.png deleted file mode 100644 index 7509568..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock2.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock3.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock3.png deleted file mode 100644 index 193e467..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock3.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock4.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock4.png deleted file mode 100644 index c63501b..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock4.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock5.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock5.png deleted file mode 100644 index f1ce9c3..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock5.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock6.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock6.png deleted file mode 100644 index 8296304..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock6.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock7.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock7.png deleted file mode 100644 index a4bd364..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock7.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock9.png b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock9.png deleted file mode 100644 index d4f2194..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/Aclock9.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/lang_zh-cn.xml b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/lang_zh-cn.xml deleted file mode 100644 index 7bc7d25..0000000 --- a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/lang_zh-cn.xml +++ /dev/null @@ -1,459 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/language_zh-cn.xml b/LedOK/res/ProgramManager/EditProgram/AClock/AClock/language_zh-cn.xml deleted file mode 100644 index 3c8f2d2..0000000 --- a/LedOK/res/ProgramManager/EditProgram/AClock/AClock/language_zh-cn.xml +++ /dev/null @@ -1,907 +0,0 @@ - - - 简体中文 - 0 - - 屏幕配置 - 发送卡 - 屏幕控制 - 工具箱 - 硬件信息 - 设备已连接 - {c #F0F0F0}检查更新{/c} - 帮助 - {c #FFF0F0}设备已连接{/c} - {c #F0F0F0}未检测到设备{/c} - {c #F0F0F0}版本:%s{/c} - 多功能卡 - 校正 - 修改语言设置后请重启软件 - - - 设备列表 ( - / - ): - 设备列表 ( %d / %d ): - 发送卡参数 - 发送卡名称 - 编辑 - 保存 - 分辨率: - 自定义 - - 位置: - 修复 - 大屏位置信息 - DVI截取(左) - DVI截取(上) - DVI截取(宽) - DVI截取(高) - 窗口位置 - 窗口大小 - - 网口1位置信息 - 网口2位置信息 - 网口3位置信息 - 网口4位置信息 - - 网口5位置信息 - 网口6位置信息 - 网口7位置信息 - 网口8位置信息 - 网口9位置信息 - 网口10位置信息 - 网口11位置信息 - 网口12位置信息 - 网口13位置信息 - 网口14位置信息 - 网口15位置信息 - 网口16位置信息 - - 偏移X - 偏移Y - 位置(左) - 位置(上) - 位置(宽) - 位置(高) - - 音频使能(注意:当需要使用音频传输时,开启音频使能。): - 启用音频传输 - 失败,请在尝试一次. - 修复完成 - - 双卡备份 - 通过选择备份卡,然后进行配置,可把当前主卡的配置数据拷贝给备份卡. - - 缩放设置 - 缩放配置可实现全屏播放时画面自动拉伸到屏幕大小.(分辨率不能超过2K分辨率范围内的自定义) - - - 缩放参数 - 启用缩放参数 - 显示屏(目标)宽度: - 显示屏(目标)高度: - - - 设备ID:xxxxxxxxxxxxxxxx - 设备ID: - FPGA版本:xxxxxxxxxxxxxxxx - FPGA版本: - MCU版本:xxxxxxxxxxxxxxxx - MCU版本: - 型号:---- - 型号: - 名称:---- - 名称: - 分辨率:----X---- @ --HZ - 分辨率: - 接收卡数量:--;--;--;-- - 接收卡数量: - - - 显示屏配置 - 显示屏配置可以设计和配置您当前的显示屏,根据用户使用习惯我们准备了如下显示屏配置方案 。 - 向导调屏 - 用于T-75E接收卡对常规显示屏的快速调试。 - 常规调屏 - 支持所有类型接收卡对各种类型显示屏调试。 - 复杂调屏 - 支持各种不同大小的箱体连接显示屏。 - 巡检 - 支持接收卡数据巡检和发送卡修复。 - - - - 芯片CPU程序升级,切记升级过程中不要断电. - 选择一个发送卡(升级相连接的芯片) - 选择一个发送卡进行升级相连接的芯片: - 选择发送卡: - 检测发送卡 - 升级参数: - --系统文件-- - 浏览... - 升级列表: - 自动配置 - 手动配置: - 起始地址: - 数量: - 加入列表 - 删除选择 - 注意:升级过程中切勿断电. - 仅升级选择的芯片 - 升级CPU0 - 升级CPU1 - 升级FPGA接收卡程序(如果不勾选,默认升级T6接收卡程序) - 升级FPGA - 升级 CPU - 快速模式升级 - - - - 生产专用 - 选择发送卡 - 刷新列表 - 配置接收卡参数: - 箱体文件: - 箱体CRC: - 重载箱体数据 - 重置误码率 - 监控信息: - 网口连接信息: - 校验错误数量: - 误码率故障数: - CPU0 - CPU1 - 数据包 - 错误包/次数 - 箱体CRC - 运行时间 - 未检测到发送卡,请刷新设备!!! - 请加载有效箱体文件!!! - 发送数据失败!!! - - - 参数出厂设置 - 选择一个发送卡进行出厂设置: - 刷新发送卡列表 - 网口1卡数量: - 网口2卡数量: - 刷新接收卡数量 - 网口芯片数量: - 发送卡出厂设置选项: - 发送卡出厂设置 - 状态:-- - 接收卡出厂设置选项: - FPGA出厂设置 - 字库出厂设置 - gamma出厂设置 - 动态配置参数出厂设置 - 恢复不可更改数据 - 不可更改数据包含生产日期/维修记录/产品类型/产品名称等信息. - 不可更改数据授权码: - *只有当授权码正确时才可进行重置不可更改数据. - 产品名称: - 产品描述: - *默认生产日期为当前系统时间;*默认卡类型为0;默认重置维修记录. - 一键恢复出厂设置 - - 公司代码 - 解除加密支持功能 - 寄存器参数出厂设置 - 厂家代码设置 - - - 发送 - 黑屏 - 刷新 - 固化 - 确定 - 取消 - 设备列表 ( - / - ): - 设备列表 ( %d / %d ): - 水平: - 垂直: - 刷新频率: - 提示 - 序号 - 地址 - 网口 - 芯片地址 - 芯片类型 - CPU0版本 - CPU1版本 - --用户文件-- - 重复 - 错误 - 升级 - 网口 - 添加 - 移除 - 设置 - 状态 - 备注 - 时间 - 编辑 - 浏览 - 删除 - 清空 - 全选 - 日期 - 星期一 - 星期二 - 星期三 - 星期四 - 星期五 - 星期六 - 星期日 - 每天 - 加载 - 每天 - 恢复默认 - 成功 - 失败 - 完成 - - - 芯片调节 - 亮度: - 所有通道: - 实时调节 - 红: - 绿: - 蓝: - 自定义 : - Gamma编辑器 - 断线显示: - 待机图片 - 最后一帧画面 - 在线调试: - 关闭 - - 绿 - - - - 横线 - 竖线 - 左斜线 - 右斜线 - 系统上电时间 - 物理地址 - 失败,请在尝试一次. - 保存成功 - 发送完成 - 手动调节 - 自动调节 - 当前屏幕亮度: - 当前环境亮度: - 启动自动调节 - 亮度映射表(环境亮度|屏体亮度) - 环境亮度(Lux) - 屏幕亮度(%) - 自定义 - 预设 - 快速分段 - 提示:没检测到光感探头 - - 定时调节 - 时间1 - 从: - 到: - 显示屏亮度: - 时间2 - 时间3 - 时间4 - 时间5 - - - - 预设1 - - - 启动误码率调试 - 重置误码率 - 地址 - 总包数 - 错误包 - FPGA版本: %X.%X.%X.%X - MCU版本: %X.%X - 电源状态 - 运行时间 - - - 出厂设置 - 升级接收卡 - 升级发送卡 - 数据调试(芯片) - 数据调试(发送卡) - 升级分线器 - 升级发送卡 正在建设... - 数据调试(芯片) 正在建设... - 数据调试(发送卡) 正在建设... - 已成功升级 [ %d ] 个芯片. - 升级失败,在执行步骤[%d]时,错误码:[%d] - 升级状态 - 升级结果 - 名称: %s -- 型号: %s -- ID: %s - 无效的发送卡设备,请尝试‘检测发送卡’ - 请选择需要升级的条目!!! - 升级条目为空!!!!!! - 至少选择一个CPU进行升级!!! - 未检测到接收卡存在. - 准备升级!!!!!! - [0]准备升级 - [1]关闭千兆网写保护 - [2]关闭芯片图像显示 - [3]关闭FLASH写保护 - [4]配置数据CHECK - [5]升级数据到SDRAM - [6]固化数据 - [7]检测数据 - [8]检测固化数据 - --处理中 - --查询状态 - --未获取状态 - --完成 - ---失败.错误码:[%d] - 升级完成 - 正在升级... - 中断升级... - 发送卡设备: %s\n - 接收卡卡数: 网口1卡数:%d ; 网口2卡数:%d\n - 是否确认恢复以上设备数据? - 状态: ... - 状态: 开始恢复出厂设置... - 状态: 完成 - 错误: %d . 请重试. - 失败. 地址:网口%d接收卡%d. - 状态: 开始重置不可更改数据... - 读hub数据完成 - 请移除掉多功能卡后进行升级. - 打开文件失败 - 接收卡数量: - 状态: 开始重置寄存器参数... - 升级中...请勿断电. - 通信失败. - 正在MCU写入升级数据,..请勿断电. - 通信失败,中断MCU升级.. - 中断MCU升级,错误码:%d - 检测P%d-%d升级状态. - P%d-%d->MCU升级写入升级数据,..请勿断电. - 升级FPGA固件程序,..请勿断电. - P%d-%d更新标记. - 通信失败,中断FPGA升级. - FPGA升级,写入数据中... - FPGA升级,配置CRC检测数据... - FPGA升级,镜像数据... - P%d-%d镜像固件数据. - P%d-%d查询镜像结果. - P%d-%d查询升级结果. - 开始校验[P%d-%d]请勿断电. - [P%d-%d]通讯失败,中断升级. - [P%d-%d]校验失败,中断升级.请勿断电. - 未检测到接收卡. - 升级:%d 失败: %d. - --用户文件-- - 接收卡数量:%d , 成功: %d, 错误码: %d" - - - 自定义EDID - - - 自定义Gamma调节 - 通过参数调节快速生成Gamma曲线及Gamma表 - 编辑Gamma表的值来进行微调 - 灰阶数: - X轴区间:: - Y轴区间: - 标准 - 增强 - 发送失败.错误码[%d] - - - 电源管理板时间 - 读取 - 将系统时间设置到多功能卡 - 电源控制 - 继电器名称备注 - 全部打开 - 紧急停止 - 电源自定义控制列表 - 电源路数 - 无DVI信号时电源指令 - 无千兆网信号时电源指令 - 关闭所有电源 - 传感器控制 - 传感器自定义列表 - 传感器 - 触发值区间 - 触发持续时间(S) - 板载监控数据 - 电源管理板时间: - 外接温度: - 板载温度: - 外接湿度: - 板载湿度: - 烟感: - 环境亮度: - FPGA版本: - FPGA升级 - BOOT设置 - 启动 - 停止 - 手动控制 - 定时控制 - 外接温度 - - 板载温度 - - 外接湿度 - - 板载湿度 - - 烟感 - 亮度 - - - 设备ID - 发送卡设备ID - 发送卡型号 - - 发送卡名称 - - 网口 - 串联地址 - 多功能卡名称 - - 正常 - 断开 - 状态 - 确定要移除选中选项吗 - 请等待继电器命令执行完后再操作 - 写入数据失败,升级中断,请检查连接线! - 升级失败 - 读取数据失败,升级中断,请检查连接线! - Gloden 升级成功 - 请等待设备初始化 - FPGA 升级成功 - 写寄存器失败 - 固化失败,请检查连接线! - 该卡已经存在 - - - 添加多功能卡 - 选择发送卡: - 网口: - 串联地址: - 名称:%s 型号:%s ID:%llX - 提示:请选择发送卡 - 提示:请选择发送卡网口 - 提示:请填写多功能卡串联地址 - 提示:请填写多功能卡名称 - - - 电源自定义编辑 - 电源自定义控制列表 - 开启时间: - 结束时间: - 自定义编辑区 - - 第一路 - 第二路 - 第三路 - 第四路 - 第五路 - 第六路 - 第七路 - 第八路 - - - 设备备注 - 第一路备注: - 第二路备注: - 第三路备注: - 第四路备注: - 第五路备注: - 第六路备注: - 第七路备注: - 第八路备注: - - - 传感器设置 - 选择传感器: - 下限 - 上限 - 注意:当传感器处于两个阀值限定的区间时触发命令 - 触发持续时间 - 满足条件持续 - S执行命令 - - - - 基本设置 - 启动退出 - 开机时自动启动(隐藏到托盘) - 关闭主面板时 - 隐藏到任务通知栏区域,不退出程序 - 退出程序 - 系统设置 - - - 测试工具 - 出厂设置 - 开始准备修复数据.. - 加载修复数据失败 - 请连接出厂发送卡设备! - 请连接有效的出厂发送卡设备! - 未连接发送卡! - 修复: 发送卡数量->[%d] , 接收卡数量-> [%d],是否正确? - 修复完成,重启发送卡生效. - 修复失败.错误码:%.8X? - - - 校正文件 : - 请加载校正数据文件... - 快速校正 : - 快速校正 - 颜色/补色 - 补红 - 补绿 - 补蓝 - 亮度校正 - 色度校正 - 关闭校正 - 固化数据 - 发送数据 - L1值必须小于L2 - 启用修缝 - 关闭修缝 - - 保存到灯板存储 - 从灯板存储加载 -自动启用 - - 联机 - 网络连接 - 状态:未监听 - 开始监听 - 校正系数文件接收设置 - 浏览 - 校正系数 - 高级 - 灯板FLASH数据管理(仅用于目标数据管理) - 数据写入 - 按照箱体 - 按照大屏 - 状态:--- - - 开始写入 - 数据读取 - 自动校正 - - 低灰校正补偿配置 - 启用低灰校正补偿 - 阈值: - 范围: - - 快速校正-高级配置 - 箱体批次 - 编辑批次数据: - 颜色 - - 绿 - - 补红 - 补绿 - 补蓝 - 发送当前批次 - 保存所有批次数据到接收卡 - 发送 - 固化 - 保存批次数据到本地 - 加载 - 保存 - 锁定布局 - 重置列表 - 刷新列表 - 保存 - - - 完成 - 提示 - 写入成功 - 失败 - 校正系数文件目录 - 状态:正在监听 %s:%d 已经连接 - 状状态:正在监听 %s:%d 已断开 - 停止监听 - 状态:正在监听 无连接! - 开始监听 - 状态:未监听 - 固化完成 - ccd 文件(*.ccd)|*.ccd|dat文件(*.dat)|*.dat|vu3文件(*.vu3)|*.vu3|| - - 成功 - 温馨提示 - 失败 - 补色 文件(*.clist)|*.clist|| - - - 哎呀,您的硬件数据 - 读取失败! - 插口没插稳? - 版本不正确? - 更新到最新版本 - 其他问题? - 重新连接后重试 - 帮助文档 - - - 快速分段配置 - 屏幕亮度: - 分段数: - 环境亮度上限值小于下限 - 屏幕上限值小于下限 - - - 接收卡数据巡检 - 发送卡修复 - 注意:根据发送卡中的数据来修复接收卡箱体的配置,需确认接收卡保存配置是否正确。适用于更换接收卡或者模组后的情况。 - 接收卡修复 - 固化 - 注意:根据接收卡中的数据来修复发送卡配置,适用于更换发送卡的情况。先进行接收卡自测, 观察屏幕显示是否正确 - 接收卡自测 - 修复发送卡 - 固化 - 巡检日志: - - - 获取发送卡巡检数据失败,当前发送卡可能没连接 - 获取箱体配置数据失败 - 获取箱体基本信息失败 - 发送卡与接收卡数据类型匹配 - 发送卡与接收卡数据类型部分匹配 - 发送卡与接收卡数据类型不匹配 - 获取箱体坐标数据失败 - 发送卡中没有该网口上连接箱体的坐标信息 - 发送卡保存巡检数据个数少于接收卡个数 - 正在修复箱体坐标 - 修复箱体坐标失败 - 正在修复箱体GIG坐标 - 修复箱体GIG坐标失败 - 箱体坐标及箱体GIG坐标正常 - 获取箱体数据CRC失败 - 发送卡中保存的箱体数据CRC错误 - 接收卡卡中获取的箱体数据CRC错误 - 箱体动态配置数据正常 - 正在修复箱体动态配置数据 - 修复箱体动态配置数据失败 - 当前发送卡下箱体巡检结束 - 巡检结束 - 正在从接收卡中获取巡检数据 - 从接收卡中获取巡检数据失败 - 接收卡中获取的巡检数据错误 - 异常 - 正在修复千兆网配置参数 - 修复千兆网配置参数失败 - 正在修复发送卡控制参数 - 修复发送卡控制参数失败 - 正在根据箱体坐标信息修复发送卡参数 - 巡检结束,请查看实际效果 - 巡检结束 - 固化成功 - 固化失败 - 提示 - 设备[ID:%s][型号:%s] - [网口:%d] - [接收卡:%d] - - 绿 - - - - 横线 - 竖线 - 左斜线“/” - 右斜线“\\” - 显示系统上电时间 - 显示接收卡物理地址 - 显示灰阶 - 正在显示 - 接收卡自测:%s - 完成 - 提示 - 接收卡自测结束 - 确定 - 正在巡检 - 确定要固化吗? - 提示 - 固化成功 - 固化失败 - 开始巡检,请确认接收卡自测正常! - 取消 - 正在修复发送卡 - 正在进行接收卡自测 - 确定要固化吗? - 正在固化数据... - - - 当前HUB列表: - 发送卡信息 - HUB地址 - 选择升级文件 - 升级失败 - 升级成功 - 请选择需要升级的HUB板 - 请选择升级文件 - 设备ID:%s,类型:%s,名称:%s - - - 升级发送卡固件 - 发送卡型号: - 升级FPGA: - 升级MCU: - 升级EDID: - 设备ID: - 发送卡列表: - FPGA版本 - MCU版本 - MCU升级状态 - FPGA升级状态 - 模式 - 注意:升级过程中切勿断电.升级按钮仅升级处于升级模式下的设备. - 进入正常模式 - 进入升级模式 - 参数错误或没有可升级的项目. - 没有可升级的设备.请连接设备或使设备进入升级状态. - 升级完成 - 升级失败;错误码:%d. - FPGA升级完成. - 升级FPGA... - 升级FPGA失败. - 需要进入BOOT模式升级. - 可升级. - 未在升级模式. - 型号与参数不匹配. - 升级完成. - 擦除升级标志OK. - 开始擦除升级标志... - 升级标志擦除失败... - MCU升级完成. - 升级MCU... - MCU升级失败. - EDID升级完成. - 升级EDID... - EDID升级失败. - ID升级完成. - 升级ID... - ID升级失败. - 重启OK. - 开始重启... - 重启失败... - 正常模式 - 升级模式 - 开始升级FPGA固件程序...,升级过程中请勿断电. - 开始升级MCU固件程序...,升级过程中请勿断电. - 开始升级EDID固件程序...,升级过程中请勿断电. - 开始升级设备ID固件程序...,升级过程中请勿断电. - 升级中...,请勿断电. - 自动重启固件程序. - 开始升级固件程序 - - - 请选择一个设备作为备份卡. - 设备失效了,请检查设备. - 配置成功 - 配置失败 - 备份卡(辅卡)配置 - 选择一个备份发送卡进行配置: - 提示: 选择的卡作为备份卡,进行配置后会把主卡的配置数据保存到备份卡中,同时把备份卡的网口设置为辅网口,同时删除备份卡的巡检数据. - 配置备份卡 - - - 不能为空! - 导出成功 - 制作厂家授权文件 - 管理员密码: - 显示 - 厂家授权码: - 生成 - - 一键解密 - 设备列表: - 输入解密密码: - 显示密码 - 资源无效 - 已解密%d个发送卡和%d个接收卡. - 时间: - 型号: - 名称: - 设备时间: - 状态代码: - 01. - 00. - 未初始化. - 工作状态. - - 索引 - 地址 - 运行时间 - 支持状态 - 执行状态 - 数量: - 支持 - 不支持 - 已过期 - 未过期 - - 加密配置向导 - 选择一个发送卡设置到期日期: - 到期日期: - 启用到期时间1 - 启用到期时间2 - 启用到期时间3 - 启用到期时间4 - 启用独立密码 - 设备授权 - 更新设备时间 - 读取到期日期 - 写入到期日期 - 请选择一个发送卡! - 设备未初始化! - 设备未加密! - 设备已无效! - 未授权! - 更新成功! - 未授权设备! - 时间密码%d不能为空! - 通信失败! - 设备未正常初始化! - 配置成功. - 授权状态: - 已授权 - 未授权 - 型号:---- - 名称:---- - 加密状态:---- - 接收卡数量:--;--;--;-- - 时间:2012-01-35 20:30:05 - 授权状态:未授权 - - 设备已经失效,请更新列表! - 请选择需要加密的设备! - 密码不能为空! - 密码长度不能超过32个字符! - 两次密码输入不一致! - 确认需要加密 [ %d ] 张发送卡及[ %d ]张接收卡 ? - 加密失败: 错误码: %d - 请先解密设备,在进行加密. - 加密成功,可以进行设置到期时间. - 加密配置向导 - 授权文件 - 授权文件: - 使用授权文件 - 设置加密密码 - 密码: - 确认密码:、 - 即将过期提示 - 过期提示 - 设备即将过期,请联系供应商... - 设备已达到使用期限,如需使用,请联系供应商... - 下一步 - - 控制系统加密 - 锁定系统 - 解除锁定 - 设置向导 - 系统状态 - 加密此设备 - - - - 密码不正确,请重新输入! - - - 设备状态 - 设备列表(选择设备查看状态) - - - diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock1.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock1.jpg deleted file mode 100644 index 47640cb..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock1.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock10.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock10.jpg deleted file mode 100644 index b882880..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock10.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock2.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock2.jpg deleted file mode 100644 index 0d78248..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock2.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock3.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock3.jpg deleted file mode 100644 index fa72acc..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock3.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock4.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock4.jpg deleted file mode 100644 index 8d96359..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock4.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock5.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock5.jpg deleted file mode 100644 index 8c2ef70..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock5.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock6.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock6.jpg deleted file mode 100644 index ef628a4..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock6.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock7.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock7.jpg deleted file mode 100644 index 0ab0ec0..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock7.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock8.jpg b/LedOK/res/ProgramManager/EditProgram/AClock/Aclock8.jpg deleted file mode 100644 index fada9e9..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/AClock/Aclock8.jpg and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/Audio.psd b/LedOK/res/ProgramManager/EditProgram/Audio.psd deleted file mode 100644 index ff8655d..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/Audio.psd and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignHC_s.png b/LedOK/res/ProgramManager/EditProgram/DocAlignHC_s.png deleted file mode 100644 index da8c290..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignHC_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignHC_u.png b/LedOK/res/ProgramManager/EditProgram/DocAlignHC_u.png deleted file mode 100644 index 52f2ab3..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignHC_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignHL_s.png b/LedOK/res/ProgramManager/EditProgram/DocAlignHL_s.png deleted file mode 100644 index fd7574a..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignHL_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignHL_u.png b/LedOK/res/ProgramManager/EditProgram/DocAlignHL_u.png deleted file mode 100644 index 2d422a1..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignHL_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignHR_s.png b/LedOK/res/ProgramManager/EditProgram/DocAlignHR_s.png deleted file mode 100644 index fee2858..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignHR_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignHR_u.png b/LedOK/res/ProgramManager/EditProgram/DocAlignHR_u.png deleted file mode 100644 index 8ea2934..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignHR_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignVB_s.png b/LedOK/res/ProgramManager/EditProgram/DocAlignVB_s.png deleted file mode 100644 index 3c4da95..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignVB_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignVB_u.png b/LedOK/res/ProgramManager/EditProgram/DocAlignVB_u.png deleted file mode 100644 index f7a6999..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignVB_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignVC_s.png b/LedOK/res/ProgramManager/EditProgram/DocAlignVC_s.png deleted file mode 100644 index c6a5a09..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignVC_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignVC_u.png b/LedOK/res/ProgramManager/EditProgram/DocAlignVC_u.png deleted file mode 100644 index e49e1c8..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignVC_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignVT_s.png b/LedOK/res/ProgramManager/EditProgram/DocAlignVT_s.png deleted file mode 100644 index f93312a..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignVT_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/DocAlignVT_u.png b/LedOK/res/ProgramManager/EditProgram/DocAlignVT_u.png deleted file mode 100644 index 8e2c8b5..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/DocAlignVT_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/FontBold_s.png b/LedOK/res/ProgramManager/EditProgram/FontBold_s.png deleted file mode 100644 index 32e6f72..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/FontBold_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/FontBold_u.png b/LedOK/res/ProgramManager/EditProgram/FontBold_u.png deleted file mode 100644 index 4607f37..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/FontBold_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/FontItalics_s.png b/LedOK/res/ProgramManager/EditProgram/FontItalics_s.png deleted file mode 100644 index 82c3565..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/FontItalics_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/FontItalics_u.png b/LedOK/res/ProgramManager/EditProgram/FontItalics_u.png deleted file mode 100644 index c44a833..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/FontItalics_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/FontUnderline_s.png b/LedOK/res/ProgramManager/EditProgram/FontUnderline_s.png deleted file mode 100644 index b9e98c5..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/FontUnderline_s.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/FontUnderline_u.png b/LedOK/res/ProgramManager/EditProgram/FontUnderline_u.png deleted file mode 100644 index a05de36..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/FontUnderline_u.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/RadioChecked.png b/LedOK/res/ProgramManager/EditProgram/RadioChecked.png deleted file mode 100644 index 0334e44..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/RadioChecked.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/RadioUnchecked.png b/LedOK/res/ProgramManager/EditProgram/RadioUnchecked.png deleted file mode 100644 index 3ccdf8d..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/RadioUnchecked.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/check.png b/LedOK/res/ProgramManager/EditProgram/check.png deleted file mode 100644 index 262f9a0..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/check.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/preview - 副本.png b/LedOK/res/ProgramManager/EditProgram/preview - 副本.png deleted file mode 100644 index e205a73..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/preview - 副本.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/uncheck.png b/LedOK/res/ProgramManager/EditProgram/uncheck.png deleted file mode 100644 index 4de366f..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/uncheck.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/勾.png b/LedOK/res/ProgramManager/EditProgram/勾.png deleted file mode 100644 index e04b744..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/勾.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/图层 11.png b/LedOK/res/ProgramManager/EditProgram/图层 11.png deleted file mode 100644 index b2a1323..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/图层 11.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/圆角矩形 3.png b/LedOK/res/ProgramManager/EditProgram/圆角矩形 3.png deleted file mode 100644 index 8fffceb..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/圆角矩形 3.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/圆角矩形 30.png b/LedOK/res/ProgramManager/EditProgram/圆角矩形 30.png deleted file mode 100644 index dc9779c..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/圆角矩形 30.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/矩形 17.png b/LedOK/res/ProgramManager/EditProgram/矩形 17.png deleted file mode 100644 index db71ad0..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/矩形 17.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/矩形 18.png b/LedOK/res/ProgramManager/EditProgram/矩形 18.png deleted file mode 100644 index 21a9eba..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/矩形 18.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/矩形 51 拷贝.png b/LedOK/res/ProgramManager/EditProgram/矩形 51 拷贝.png deleted file mode 100644 index e363ce4..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/矩形 51 拷贝.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/矩形 57.png b/LedOK/res/ProgramManager/EditProgram/矩形 57.png deleted file mode 100644 index 70cf53a..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/矩形 57.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/组 37.png b/LedOK/res/ProgramManager/EditProgram/组 37.png deleted file mode 100644 index 6ca23a2..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/组 37.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/组 41.png b/LedOK/res/ProgramManager/EditProgram/组 41.png deleted file mode 100644 index 1db60ea..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/组 41.png and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/组 57(1).png b/LedOK/res/ProgramManager/EditProgram/组 57(1).png deleted file mode 100644 index 5bb7270..0000000 Binary files a/LedOK/res/ProgramManager/EditProgram/组 57(1).png and /dev/null differ diff --git a/LedOK/res/RadioChecked.png b/LedOK/res/RadioChecked.png deleted file mode 100644 index 2fd260e..0000000 Binary files a/LedOK/res/RadioChecked.png and /dev/null differ diff --git a/LedOK/res/DeviceManager/Add.png b/LedOK/res/device/Add.png similarity index 100% rename from LedOK/res/DeviceManager/Add.png rename to LedOK/res/device/Add.png diff --git a/LedOK/res/DeviceManager/DeviceNum_All.png b/LedOK/res/device/DeviceNum_All.png similarity index 100% rename from LedOK/res/DeviceManager/DeviceNum_All.png rename to LedOK/res/device/DeviceNum_All.png diff --git a/LedOK/res/DeviceManager/DeviceNum_Offline.png b/LedOK/res/device/DeviceNum_Offline.png similarity index 100% rename from LedOK/res/DeviceManager/DeviceNum_Offline.png rename to LedOK/res/device/DeviceNum_Offline.png diff --git a/LedOK/res/DeviceManager/DeviceNum_Online.png b/LedOK/res/device/DeviceNum_Online.png similarity index 100% rename from LedOK/res/DeviceManager/DeviceNum_Online.png rename to LedOK/res/device/DeviceNum_Online.png diff --git a/LedOK/res/DeviceManager/DeviceNum_Unlogin.png b/LedOK/res/device/DeviceNum_Unlogin.png similarity index 100% rename from LedOK/res/DeviceManager/DeviceNum_Unlogin.png rename to LedOK/res/device/DeviceNum_Unlogin.png diff --git a/LedOK/res/DeviceManager/Equal.png b/LedOK/res/device/Equal.png similarity index 100% rename from LedOK/res/DeviceManager/Equal.png rename to LedOK/res/device/Equal.png diff --git a/LedOK/res/DeviceManager/FlashArrow.png b/LedOK/res/device/FlashArrow.png similarity index 100% rename from LedOK/res/DeviceManager/FlashArrow.png rename to LedOK/res/device/FlashArrow.png diff --git a/LedOK/res/DeviceManager/Lock.png b/LedOK/res/device/Lock.png similarity index 100% rename from LedOK/res/DeviceManager/Lock.png rename to LedOK/res/device/Lock.png diff --git a/LedOK/res/DeviceManager/O_Offline.png b/LedOK/res/device/O_Offline.png similarity index 100% rename from LedOK/res/DeviceManager/O_Offline.png rename to LedOK/res/device/O_Offline.png diff --git a/LedOK/res/DeviceManager/O_Online.png b/LedOK/res/device/O_Online.png similarity index 100% rename from LedOK/res/DeviceManager/O_Online.png rename to LedOK/res/device/O_Online.png diff --git a/LedOK/res/DeviceManager/O_Unlogin.png b/LedOK/res/device/O_Unlogin.png similarity index 100% rename from LedOK/res/DeviceManager/O_Unlogin.png rename to LedOK/res/device/O_Unlogin.png diff --git a/LedOK/res/DeviceManager/UnLock.png b/LedOK/res/device/UnLock.png similarity index 100% rename from LedOK/res/DeviceManager/UnLock.png rename to LedOK/res/device/UnLock.png diff --git a/LedOK/res/DeviceManager/bnDetail.png b/LedOK/res/device/bnDetail.png similarity index 100% rename from LedOK/res/DeviceManager/bnDetail.png rename to LedOK/res/device/bnDetail.png diff --git a/LedOK/res/DeviceManager/deviceReadbackPic.png b/LedOK/res/device/deviceReadbackPic.png similarity index 100% rename from LedOK/res/DeviceManager/deviceReadbackPic.png rename to LedOK/res/device/deviceReadbackPic.png diff --git a/LedOK/res/groupbox-checked.png b/LedOK/res/groupbox-checked.png new file mode 100644 index 0000000..0e5f0a5 Binary files /dev/null and b/LedOK/res/groupbox-checked.png differ diff --git a/LedOK/res/groupbox-unchecked.png b/LedOK/res/groupbox-unchecked.png new file mode 100644 index 0000000..8a1f440 Binary files /dev/null and b/LedOK/res/groupbox-unchecked.png differ diff --git a/LedOK/res/资源 6@10x.png b/LedOK/res/logo-raw.png similarity index 100% rename from LedOK/res/资源 6@10x.png rename to LedOK/res/logo-raw.png diff --git a/LedOK/res/next.psd b/LedOK/res/next.psd deleted file mode 100644 index 634a371..0000000 Binary files a/LedOK/res/next.psd and /dev/null differ diff --git a/LedOK/res/ProgramManager/EditProgram/AClock.png b/LedOK/res/program/AClock.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/AClock.png rename to LedOK/res/program/AClock.png diff --git a/LedOK/res/ProgramManager/EditProgram/Add.png b/LedOK/res/program/Add.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Add.png rename to LedOK/res/program/Add.png diff --git a/LedOK/res/ProgramManager/EditProgram/AddPlan.png b/LedOK/res/program/AddPlan.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/AddPlan.png rename to LedOK/res/program/AddPlan.png diff --git a/LedOK/res/ProgramManager/EditProgram/ArrayBottom.png b/LedOK/res/program/ArrayBottom.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ArrayBottom.png rename to LedOK/res/program/ArrayBottom.png diff --git a/LedOK/res/ProgramManager/EditProgram/ArrayHCenter.png b/LedOK/res/program/ArrayHCenter.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ArrayHCenter.png rename to LedOK/res/program/ArrayHCenter.png diff --git a/LedOK/res/ProgramManager/EditProgram/ArrayLeft.png b/LedOK/res/program/ArrayLeft.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ArrayLeft.png rename to LedOK/res/program/ArrayLeft.png diff --git a/LedOK/res/ProgramManager/EditProgram/ArrayRight.png b/LedOK/res/program/ArrayRight.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ArrayRight.png rename to LedOK/res/program/ArrayRight.png diff --git a/LedOK/res/ProgramManager/EditProgram/ArrayTop.png b/LedOK/res/program/ArrayTop.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ArrayTop.png rename to LedOK/res/program/ArrayTop.png diff --git a/LedOK/res/ProgramManager/EditProgram/ArrayVCenter.png b/LedOK/res/program/ArrayVCenter.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ArrayVCenter.png rename to LedOK/res/program/ArrayVCenter.png diff --git a/LedOK/res/ProgramManager/EditProgram/Audio.png b/LedOK/res/program/Audio.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Audio.png rename to LedOK/res/program/Audio.png diff --git a/LedOK/res/ProgramManager/EditProgram/Clean.png b/LedOK/res/program/Clean.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Clean.png rename to LedOK/res/program/Clean.png diff --git a/LedOK/res/ProgramManager/EditProgram/CleanPlan.png b/LedOK/res/program/CleanPlan.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/CleanPlan.png rename to LedOK/res/program/CleanPlan.png diff --git a/LedOK/res/ProgramManager/EditProgram/ColorText.png b/LedOK/res/program/ColorText.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ColorText.png rename to LedOK/res/program/ColorText.png diff --git a/LedOK/res/ProgramManager/EditProgram/Copy.png b/LedOK/res/program/Copy.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Copy.png rename to LedOK/res/program/Copy.png diff --git a/LedOK/res/ProgramManager/EditProgram/Cut.png b/LedOK/res/program/Cut.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Cut.png rename to LedOK/res/program/Cut.png diff --git a/LedOK/res/ProgramManager/EditProgram/DClock.png b/LedOK/res/program/DClock.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/DClock.png rename to LedOK/res/program/DClock.png diff --git a/LedOK/res/ProgramManager/EditProgram/DateSelect.png b/LedOK/res/program/DateSelect.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/DateSelect.png rename to LedOK/res/program/DateSelect.png diff --git a/LedOK/res/ProgramManager/EditProgram/DateSelect_e.png b/LedOK/res/program/DateSelect_e.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/DateSelect_e.png rename to LedOK/res/program/DateSelect_e.png diff --git a/LedOK/res/ProgramManager/EditProgram/DateSelect_enable.png b/LedOK/res/program/DateSelect_enable.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/DateSelect_enable.png rename to LedOK/res/program/DateSelect_enable.png diff --git a/LedOK/res/ProgramManager/EditProgram/Delete.png b/LedOK/res/program/Delete.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Delete.png rename to LedOK/res/program/Delete.png diff --git a/LedOK/res/ProgramManager/EditProgram/Gif.png b/LedOK/res/program/Gif.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Gif.png rename to LedOK/res/program/Gif.png diff --git a/LedOK/res/ProgramManager/EditProgram/GoDown.png b/LedOK/res/program/GoDown.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/GoDown.png rename to LedOK/res/program/GoDown.png diff --git a/LedOK/res/ProgramManager/EditProgram/GoUp.png b/LedOK/res/program/GoUp.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/GoUp.png rename to LedOK/res/program/GoUp.png diff --git a/LedOK/res/ProgramManager/EditProgram/LayerBottom.png b/LedOK/res/program/LayerBottom.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/LayerBottom.png rename to LedOK/res/program/LayerBottom.png diff --git a/LedOK/res/ProgramManager/EditProgram/LayerDown.png b/LedOK/res/program/LayerDown.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/LayerDown.png rename to LedOK/res/program/LayerDown.png diff --git a/LedOK/res/ProgramManager/EditProgram/LayerTop.png b/LedOK/res/program/LayerTop.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/LayerTop.png rename to LedOK/res/program/LayerTop.png diff --git a/LedOK/res/ProgramManager/EditProgram/LayerUp.png b/LedOK/res/program/LayerUp.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/LayerUp.png rename to LedOK/res/program/LayerUp.png diff --git a/LedOK/res/ProgramManager/EditProgram/Movie.png b/LedOK/res/program/Movie.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Movie.png rename to LedOK/res/program/Movie.png diff --git a/LedOK/res/ProgramManager/EditProgram/Office.png b/LedOK/res/program/Office.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Office.png rename to LedOK/res/program/Office.png diff --git a/LedOK/res/ProgramManager/EditProgram/Photo.png b/LedOK/res/program/Photo.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Photo.png rename to LedOK/res/program/Photo.png diff --git a/LedOK/res/ProgramManager/EditProgram/Rss.png b/LedOK/res/program/Rss.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Rss.png rename to LedOK/res/program/Rss.png diff --git a/LedOK/res/ProgramManager/EditProgram/Save.png b/LedOK/res/program/Save.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Save.png rename to LedOK/res/program/Save.png diff --git a/LedOK/res/ProgramManager/EditProgram/SaveAs.png b/LedOK/res/program/SaveAs.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/SaveAs.png rename to LedOK/res/program/SaveAs.png diff --git a/LedOK/res/ProgramManager/EditProgram/ScaleDown.png b/LedOK/res/program/ScaleDown.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ScaleDown.png rename to LedOK/res/program/ScaleDown.png diff --git a/LedOK/res/ProgramManager/EditProgram/ScaleOrg.png b/LedOK/res/program/ScaleOrg.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ScaleOrg.png rename to LedOK/res/program/ScaleOrg.png diff --git a/LedOK/res/ProgramManager/EditProgram/ScaleUp.png b/LedOK/res/program/ScaleUp.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/ScaleUp.png rename to LedOK/res/program/ScaleUp.png diff --git a/LedOK/res/ProgramManager/EditProgram/Send.png b/LedOK/res/program/Send.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Send.png rename to LedOK/res/program/Send.png diff --git a/LedOK/res/ProgramManager/EditProgram/Setting.png b/LedOK/res/program/Setting.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Setting.png rename to LedOK/res/program/Setting.png diff --git a/LedOK/res/ProgramManager/EditProgram/Temp.png b/LedOK/res/program/Temp.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Temp.png rename to LedOK/res/program/Temp.png diff --git a/LedOK/res/ProgramManager/EditProgram/Text.png b/LedOK/res/program/Text.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Text.png rename to LedOK/res/program/Text.png diff --git a/LedOK/res/program/TextAlignHC.png b/LedOK/res/program/TextAlignHC.png new file mode 100644 index 0000000..ac50ff3 Binary files /dev/null and b/LedOK/res/program/TextAlignHC.png differ diff --git a/LedOK/res/program/TextAlignHL.png b/LedOK/res/program/TextAlignHL.png new file mode 100644 index 0000000..169b582 Binary files /dev/null and b/LedOK/res/program/TextAlignHL.png differ diff --git a/LedOK/res/program/TextAlignHR.png b/LedOK/res/program/TextAlignHR.png new file mode 100644 index 0000000..2e66817 Binary files /dev/null and b/LedOK/res/program/TextAlignHR.png differ diff --git a/LedOK/res/program/TextAlignVB.png b/LedOK/res/program/TextAlignVB.png new file mode 100644 index 0000000..0de9f98 Binary files /dev/null and b/LedOK/res/program/TextAlignVB.png differ diff --git a/LedOK/res/program/TextAlignVC.png b/LedOK/res/program/TextAlignVC.png new file mode 100644 index 0000000..8b95526 Binary files /dev/null and b/LedOK/res/program/TextAlignVC.png differ diff --git a/LedOK/res/program/TextAlignVT.png b/LedOK/res/program/TextAlignVT.png new file mode 100644 index 0000000..fc0e4db Binary files /dev/null and b/LedOK/res/program/TextAlignVT.png differ diff --git a/LedOK/res/ProgramManager/EditProgram/TileFull.png b/LedOK/res/program/TileFull.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/TileFull.png rename to LedOK/res/program/TileFull.png diff --git a/LedOK/res/ProgramManager/EditProgram/TileH.png b/LedOK/res/program/TileH.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/TileH.png rename to LedOK/res/program/TileH.png diff --git a/LedOK/res/ProgramManager/EditProgram/TileV.png b/LedOK/res/program/TileV.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/TileV.png rename to LedOK/res/program/TileV.png diff --git a/LedOK/res/ProgramManager/EditProgram/Timer.png b/LedOK/res/program/Timer.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Timer.png rename to LedOK/res/program/Timer.png diff --git a/LedOK/res/ProgramManager/EditProgram/Weather.png b/LedOK/res/program/Weather.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Weather.png rename to LedOK/res/program/Weather.png diff --git a/LedOK/res/ProgramManager/EditProgram/Web.png b/LedOK/res/program/Web.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Web.png rename to LedOK/res/program/Web.png diff --git a/LedOK/res/ProgramManager/EditProgram/Window.png b/LedOK/res/program/Window.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/Window.png rename to LedOK/res/program/Window.png diff --git a/LedOK/res/ProgramManager/bnExport_s.png b/LedOK/res/program/bnExport_s.png similarity index 100% rename from LedOK/res/ProgramManager/bnExport_s.png rename to LedOK/res/program/bnExport_s.png diff --git a/LedOK/res/ProgramManager/bnExport_u.png b/LedOK/res/program/bnExport_u.png similarity index 100% rename from LedOK/res/ProgramManager/bnExport_u.png rename to LedOK/res/program/bnExport_u.png diff --git a/LedOK/res/ProgramManager/bnSearch.png b/LedOK/res/program/bnSearch.png similarity index 100% rename from LedOK/res/ProgramManager/bnSearch.png rename to LedOK/res/program/bnSearch.png diff --git a/LedOK/res/ProgramManager/bnSend_s.png b/LedOK/res/program/bnSend_s.png similarity index 100% rename from LedOK/res/ProgramManager/bnSend_s.png rename to LedOK/res/program/bnSend_s.png diff --git a/LedOK/res/ProgramManager/bnSend_u.png b/LedOK/res/program/bnSend_u.png similarity index 100% rename from LedOK/res/ProgramManager/bnSend_u.png rename to LedOK/res/program/bnSend_u.png diff --git a/LedOK/res/ProgramManager/EditProgram/preview.png b/LedOK/res/program/preview.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/preview.png rename to LedOK/res/program/preview.png diff --git a/LedOK/res/ProgramManager/EditProgram/previewStop.png b/LedOK/res/program/previewStop.png similarity index 100% rename from LedOK/res/ProgramManager/EditProgram/previewStop.png rename to LedOK/res/program/previewStop.png diff --git a/LedOK/res/random.png b/LedOK/res/random.png new file mode 100644 index 0000000..179728e Binary files /dev/null and b/LedOK/res/random.png differ diff --git a/LedOK/res/signal-0.png b/LedOK/res/signal-0.png new file mode 100644 index 0000000..5cf83cd Binary files /dev/null and b/LedOK/res/signal-0.png differ diff --git a/LedOK/res/signal-1.png b/LedOK/res/signal-1.png new file mode 100644 index 0000000..6e0c5f0 Binary files /dev/null and b/LedOK/res/signal-1.png differ diff --git a/LedOK/res/signal-2.png b/LedOK/res/signal-2.png new file mode 100644 index 0000000..b0ed234 Binary files /dev/null and b/LedOK/res/signal-2.png differ diff --git a/LedOK/res/signal-3.png b/LedOK/res/signal-3.png new file mode 100644 index 0000000..e1f2bf3 Binary files /dev/null and b/LedOK/res/signal-3.png differ diff --git a/LedOK/res/signal-4.png b/LedOK/res/signal-4.png new file mode 100644 index 0000000..40a9cb5 Binary files /dev/null and b/LedOK/res/signal-4.png differ diff --git a/LedOK/res/signal-5.png b/LedOK/res/signal-5.png new file mode 100644 index 0000000..df3b32d Binary files /dev/null and b/LedOK/res/signal-5.png differ diff --git a/LedOK/synctimer.cpp b/LedOK/synctimer.cpp index 47113dc..08f245b 100644 --- a/LedOK/synctimer.cpp +++ b/LedOK/synctimer.cpp @@ -1,29 +1,29 @@ -#include "synctimer.h" -#include -#include -#include - -SyncTimer::SyncTimer(int inter) { - this->inter = inter; - connect(this, &QThread::finished, this, &QThread::deleteLater); -} -void SyncTimer::run(){ - qint64 curTime; - sleep = inter; - if(sleep <= 0) return; - timeBeginPeriod(1); - msleep(sleep); - qint64 exeTime = QDateTime::currentMSecsSinceEpoch(); - while(inter > 0) { - inter = 0; - emit timeout(); - curTime = inter; - if(curTime<=0) break; - exeTime += curTime; - curTime = QDateTime::currentMSecsSinceEpoch(); - sleep = exeTime - curTime; - if(exeTime > curTime) msleep(sleep); - else exeTime = curTime; - } - timeEndPeriod(1); -} +#include "synctimer.h" +#include +#include +#include + +SyncTimer::SyncTimer(int inter) { + this->inter = inter; + connect(this, &QThread::finished, this, &QThread::deleteLater); +} +void SyncTimer::run(){ + qint64 curTime; + sleep = inter; + if(sleep <= 0) return; + timeBeginPeriod(1); + msleep(sleep); + qint64 exeTime = QDateTime::currentMSecsSinceEpoch(); + while(inter > 0) { + inter = 0; + emit timeout(); + curTime = inter; + if(curTime<=0) break; + exeTime += curTime; + curTime = QDateTime::currentMSecsSinceEpoch(); + sleep = exeTime - curTime; + if(exeTime > curTime) msleep(sleep); + else exeTime = curTime; + } + timeEndPeriod(1); +} diff --git a/LedOK/tcpsocket - 副本.cpp b/LedOK/tcpsocket - 副本.cpp index 2625806..d5feefc 100644 --- a/LedOK/tcpsocket - 副本.cpp +++ b/LedOK/tcpsocket - 副本.cpp @@ -1,128 +1,128 @@ -#include "tcpsocket.h" - -TcpSocket::TcpSocket(QObject *parent) : QTcpSocket{parent} { - connect(this, &QTcpSocket::errorOccurred, this, [this]() { - { - std::lock_guard lock(mtx); - hasErr = true; - } - cv.notify_all(); - }); - connect(this, &QTcpSocket::connected, this, [this]() { - { - std::lock_guard lock(mtx); - } - cv.notify_all(); - }); - connect(this, &QTcpSocket::disconnected, this, [this]() { - { - std::lock_guard lock(mtx); - } - cv.notify_all(); - }); - connect(this, &QTcpSocket::bytesWritten, this, [this]() { - { - std::lock_guard lock(mtx); - isWritten = true; - } - cv.notify_all(); - }); - connect(this, &QTcpSocket::readyRead, this, [this]() { - { - std::lock_guard lock(mtx); - isReadyRead = true; - } - cv.notify_all(); - }); -} - -bool TcpSocket::waitForConnected(int msecs) { - if(hasErr) return false; - if(state() == ConnectedState) return true; - { - std::unique_lock lock(mtx); - if(hasErr) return false; - if(state() == ConnectedState) return true; - auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); - auto check = until - std::chrono::milliseconds(10); - do { - cv.wait_until(lock, until); - if(hasErr) return false; - if(state() == ConnectedState) return true; - } while(std::chrono::steady_clock::now() < check); - } - hasErr = true; - setSocketError(SocketTimeoutError); - return false; -} -bool TcpSocket::waitForDisconnected(int msecs) { - if(hasErr) return false; - if(state() == UnconnectedState) return true; - { - std::unique_lock lock(mtx); - if(hasErr) return false; - if(state() == UnconnectedState) return true; - auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); - auto check = until - std::chrono::milliseconds(10); - do { - cv.wait_until(lock, until); - if(hasErr) return false; - if(state() == UnconnectedState) return true; - } while(std::chrono::steady_clock::now() < check); - } - hasErr = true; - setSocketError(SocketTimeoutError); - return false; -} -bool TcpSocket::waitForBytesWritten(int msecs) { - if(hasErr) return false; - if(isWritten) return true; - { - std::unique_lock lock(mtx); - if(hasErr) return false; - if(isWritten) return true; - auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); - auto check = until - std::chrono::milliseconds(10); - do { - cv.wait_until(lock, until); - if(hasErr) return false; - if(isWritten) return true; - } while(std::chrono::steady_clock::now() < check); - } - hasErr = true; - setSocketError(SocketTimeoutError); - return false; -} -bool TcpSocket::waitForReadyRead(int msecs) { - if(hasErr) return false; - if(isReadyRead) return true; - { - std::unique_lock lock(mtx); - if(hasErr) return false; - if(isReadyRead) return true; - auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); - auto check = until - std::chrono::milliseconds(10); - do { - cv.wait_until(lock, until); - if(hasErr) return false; - if(isReadyRead) return true; - } while(std::chrono::steady_clock::now() < check); - } - hasErr = true; - setSocketError(SocketTimeoutError); - return false; -} -qint64 TcpSocket::readData(char *data, qint64 maxlen) { - auto rtn = QTcpSocket::readData(data, maxlen); - isReadyRead = false; - return rtn; -} -qint64 TcpSocket::readLineData(char *data, qint64 maxlen) { - auto rtn = QTcpSocket::readLineData(data, maxlen); - isReadyRead = false; - return rtn; -} -qint64 TcpSocket::writeData(const char *data, qint64 len) { - isWritten = false; - return QTcpSocket::writeData(data, len); -} +#include "tcpsocket.h" + +TcpSocket::TcpSocket(QObject *parent) : QTcpSocket{parent} { + connect(this, &QTcpSocket::errorOccurred, this, [this]() { + { + std::lock_guard lock(mtx); + hasErr = true; + } + cv.notify_all(); + }); + connect(this, &QTcpSocket::connected, this, [this]() { + { + std::lock_guard lock(mtx); + } + cv.notify_all(); + }); + connect(this, &QTcpSocket::disconnected, this, [this]() { + { + std::lock_guard lock(mtx); + } + cv.notify_all(); + }); + connect(this, &QTcpSocket::bytesWritten, this, [this]() { + { + std::lock_guard lock(mtx); + isWritten = true; + } + cv.notify_all(); + }); + connect(this, &QTcpSocket::readyRead, this, [this]() { + { + std::lock_guard lock(mtx); + isReadyRead = true; + } + cv.notify_all(); + }); +} + +bool TcpSocket::waitForConnected(int msecs) { + if(hasErr) return false; + if(state() == ConnectedState) return true; + { + std::unique_lock lock(mtx); + if(hasErr) return false; + if(state() == ConnectedState) return true; + auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); + auto check = until - std::chrono::milliseconds(10); + do { + cv.wait_until(lock, until); + if(hasErr) return false; + if(state() == ConnectedState) return true; + } while(std::chrono::steady_clock::now() < check); + } + hasErr = true; + setSocketError(SocketTimeoutError); + return false; +} +bool TcpSocket::waitForDisconnected(int msecs) { + if(hasErr) return false; + if(state() == UnconnectedState) return true; + { + std::unique_lock lock(mtx); + if(hasErr) return false; + if(state() == UnconnectedState) return true; + auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); + auto check = until - std::chrono::milliseconds(10); + do { + cv.wait_until(lock, until); + if(hasErr) return false; + if(state() == UnconnectedState) return true; + } while(std::chrono::steady_clock::now() < check); + } + hasErr = true; + setSocketError(SocketTimeoutError); + return false; +} +bool TcpSocket::waitForBytesWritten(int msecs) { + if(hasErr) return false; + if(isWritten) return true; + { + std::unique_lock lock(mtx); + if(hasErr) return false; + if(isWritten) return true; + auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); + auto check = until - std::chrono::milliseconds(10); + do { + cv.wait_until(lock, until); + if(hasErr) return false; + if(isWritten) return true; + } while(std::chrono::steady_clock::now() < check); + } + hasErr = true; + setSocketError(SocketTimeoutError); + return false; +} +bool TcpSocket::waitForReadyRead(int msecs) { + if(hasErr) return false; + if(isReadyRead) return true; + { + std::unique_lock lock(mtx); + if(hasErr) return false; + if(isReadyRead) return true; + auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(msecs); + auto check = until - std::chrono::milliseconds(10); + do { + cv.wait_until(lock, until); + if(hasErr) return false; + if(isReadyRead) return true; + } while(std::chrono::steady_clock::now() < check); + } + hasErr = true; + setSocketError(SocketTimeoutError); + return false; +} +qint64 TcpSocket::readData(char *data, qint64 maxlen) { + auto rtn = QTcpSocket::readData(data, maxlen); + isReadyRead = false; + return rtn; +} +qint64 TcpSocket::readLineData(char *data, qint64 maxlen) { + auto rtn = QTcpSocket::readLineData(data, maxlen); + isReadyRead = false; + return rtn; +} +qint64 TcpSocket::writeData(const char *data, qint64 len) { + isWritten = false; + return QTcpSocket::writeData(data, len); +} diff --git a/LedOK/tcpsocket - 副本.h b/LedOK/tcpsocket - 副本.h index e753bd1..35201b2 100644 --- a/LedOK/tcpsocket - 副本.h +++ b/LedOK/tcpsocket - 副本.h @@ -1,29 +1,29 @@ -#ifndef TCPSOCKET_H -#define TCPSOCKET_H - -#include -#include - -class TcpSocket : public QTcpSocket { - Q_OBJECT -public: - explicit TcpSocket(QObject *parent = nullptr); - - bool waitForConnected(int msecs = 30000) override; - bool waitForDisconnected(int msecs = 30000) override; - bool waitForBytesWritten(int msecs = 30000) override; - bool waitForReadyRead(int msecs = 30000) override; - qint64 readData(char *data, qint64 maxlen) override; - qint64 readLineData(char *data, qint64 maxlen) override; - qint64 writeData(const char *data, qint64 len) override; - bool hasErr = false; - bool isWritten = false; - bool isReadyRead = false; - -private: - std::mutex mtx; - std::condition_variable cv; - -}; - -#endif // TCPSOCKET_H +#ifndef TCPSOCKET_H +#define TCPSOCKET_H + +#include +#include + +class TcpSocket : public QTcpSocket { + Q_OBJECT +public: + explicit TcpSocket(QObject *parent = nullptr); + + bool waitForConnected(int msecs = 30000) override; + bool waitForDisconnected(int msecs = 30000) override; + bool waitForBytesWritten(int msecs = 30000) override; + bool waitForReadyRead(int msecs = 30000) override; + qint64 readData(char *data, qint64 maxlen) override; + qint64 readLineData(char *data, qint64 maxlen) override; + qint64 writeData(const char *data, qint64 len) override; + bool hasErr = false; + bool isWritten = false; + bool isReadyRead = false; + +private: + std::mutex mtx; + std::condition_variable cv; + +}; + +#endif // TCPSOCKET_H diff --git a/LedOK/tcpsocket.cpp b/LedOK/tcpsocket.cpp deleted file mode 100644 index 6892ab7..0000000 --- a/LedOK/tcpsocket.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "tcpsocket.h" -#include -#include - -const char* socketErrKey(int value) { - static auto metaEnum = QMetaEnum::fromType(); - return metaEnum.valueToKey(value); -} - -bool TcpSocket::waitForConnected(int msecs) { - if(state() == ConnectedState) return true; - QEventLoop loop; - connect(this, &QTcpSocket::connected, &loop, &QEventLoop::quit); - return connAndExec(msecs, &loop); -} -bool TcpSocket::waitForDisconnected(int msecs) { - if(state() == UnconnectedState) return true; - QEventLoop loop; - connect(this, &QTcpSocket::disconnected, &loop, &QEventLoop::quit); - return connAndExec(msecs, &loop); -} -bool TcpSocket::waitForBytesWritten(int msecs) { - QEventLoop loop; - connect(this, &QTcpSocket::bytesWritten, &loop, &QEventLoop::quit); - return connAndExec(msecs, &loop); -} -bool TcpSocket::waitForReadyRead(int msecs) { - QEventLoop loop; - connect(this, &QTcpSocket::readyRead, &loop, &QEventLoop::quit); - return connAndExec(msecs, &loop); -} - -bool TcpSocket::connAndExec(int msecs, QEventLoop *loop) { - connect(this, &QTcpSocket::errorOccurred, loop, [loop] { - loop->exit(1); - }); - if(msecs > 0) { - connect(this, &TcpSocket::timeout, loop, &QEventLoop::exit); - if(timerId!=0) killTimer(timerId); - timerId = startTimer(msecs); - } - auto res = loop->exec(); - timerStop(); - if(res==5) setSocketError(SocketTimeoutError); - return res==0; -} diff --git a/LedOK/tcpsocket.h b/LedOK/tcpsocket.h deleted file mode 100644 index 6a266ee..0000000 --- a/LedOK/tcpsocket.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef TCPSOCKET_H -#define TCPSOCKET_H - -#include -#include -#include - -const char* socketErrKey(int value); - -class TcpSocket : public QTcpSocket { - Q_OBJECT -public: - explicit TcpSocket(QObject *parent = nullptr) : QTcpSocket{parent} {}; - ~TcpSocket() { - if(timerId!=0) killTimer(timerId); - }; - bool waitForConnected(int msecs = 30000) override; - bool waitForDisconnected(int msecs = 30000) override; - bool waitForBytesWritten(int msecs = 30000) override; - bool waitForReadyRead(int msecs = 30000) override; -protected: - void timerEvent(QTimerEvent *e) override { - if(e->timerId()!=timerId) return; - killTimer(timerId); - timerId = 0; - emit timeout(5); - }; - bool connAndExec(int msecs, QEventLoop *loop); - inline void timerStop() { - if(timerId==0) return; - killTimer(timerId); - timerId = 0; - } - int timerId = 0; -signals: - void timeout(int); -}; - -#endif // TCPSOCKET_H diff --git a/LedOK/test.cpp b/LedOK/test.cpp index 3a885ad..ab501b4 100644 --- a/LedOK/test.cpp +++ b/LedOK/test.cpp @@ -1,93 +1,93 @@ -#include -#include -#include -#include -#include -#include - -void testFont() { - QFont font("Arial", 21); - //font.setItalic(m_attr.fontItalics); - font.setStyleStrategy(QFont::NoAntialias); - QFontMetricsF metric(font); - QFontMetrics metricI(font); - qDebug()<<"QFontMetrics"; - qDebug()<<" leading"< -#include -class TestWin : public QWidget { -public: - TestWin(){ - resize(400, 100); - auto hBox = new QHBoxLayout(this); - hBox->setContentsMargins(100,0,0,0); - aaa = new QLabel("Aaaaaaaaaaaaaaaaaaaaaaaa"); - aaa->setAutoFillBackground(true); - QPalette pal; - pal.setColor(QPalette::Window, Qt::darkGreen); - aaa->setPalette(pal); - aaa->setMinimumWidth(10); - hBox->addWidget(aaa); - - bbb = new QLabel("B"); - bbb->setAutoFillBackground(true); - pal.setColor(QPalette::Window, Qt::darkCyan); - bbb->setPalette(pal); - bbb->setMinimumWidth(1); - - auto poli = aaa->sizePolicy(); - poli.setHorizontalPolicy(QSizePolicy::Expanding); - aaa->setSizePolicy(poli); - bbb->setSizePolicy(poli); - - - hBox->addWidget(bbb); - } - void mouseDoubleClickEvent(QMouseEvent *) override { - qDebug()<<"sizeHint "<sizeHint()<sizeHint(); - qDebug()<<"minHint "<minimumSizeHint()<minimumSizeHint(); - qDebug()<<"sizePolicy"<sizePolicy()<sizePolicy(); - qDebug()<<"minSize "<minimumSize()<minimumSize(); - qDebug()<<"maxSize "<maximumSize()<maximumSize(); - qDebug()<<"size "<size()<size(); - } - QWidget *aaa; - QWidget *bbb; -}; -int tttmain(int argc, char *argv[]) { - QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); - QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); - QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); - QApplication a(argc, argv); - QFont font = a.font(); - font.setPointSize(14); - a.setFont(font); - - TestWin w; - w.show(); - return a.exec(); -} - +#include +#include +#include +#include +#include +#include + +void testFont() { + QFont font("Arial", 21); + //font.setItalic(m_attr.fontItalics); + font.setStyleStrategy(QFont::NoAntialias); + QFontMetricsF metric(font); + QFontMetrics metricI(font); + qDebug()<<"QFontMetrics"; + qDebug()<<" leading"< +#include +class TestWin : public QWidget { +public: + TestWin(){ + resize(400, 100); + auto hBox = new QHBoxLayout(this); + hBox->setContentsMargins(100,0,0,0); + aaa = new QLabel("Aaaaaaaaaaaaaaaaaaaaaaaa"); + aaa->setAutoFillBackground(true); + QPalette pal; + pal.setColor(QPalette::Window, Qt::darkGreen); + aaa->setPalette(pal); + aaa->setMinimumWidth(10); + hBox->addWidget(aaa); + + bbb = new QLabel("B"); + bbb->setAutoFillBackground(true); + pal.setColor(QPalette::Window, Qt::darkCyan); + bbb->setPalette(pal); + bbb->setMinimumWidth(1); + + auto poli = aaa->sizePolicy(); + poli.setHorizontalPolicy(QSizePolicy::Expanding); + aaa->setSizePolicy(poli); + bbb->setSizePolicy(poli); + + + hBox->addWidget(bbb); + } + void mouseDoubleClickEvent(QMouseEvent *) override { + qDebug()<<"sizeHint "<sizeHint()<sizeHint(); + qDebug()<<"minHint "<minimumSizeHint()<minimumSizeHint(); + qDebug()<<"sizePolicy"<sizePolicy()<sizePolicy(); + qDebug()<<"minSize "<minimumSize()<minimumSize(); + qDebug()<<"maxSize "<maximumSize()<maximumSize(); + qDebug()<<"size "<size()<size(); + } + QWidget *aaa; + QWidget *bbb; +}; +int tttmain(int argc, char *argv[]) { + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + QApplication a(argc, argv); + QFont font = a.font(); + font.setPointSize(14); + a.setFont(font); + + TestWin w; + w.show(); + return a.exec(); +} + diff --git a/LedOK/tipdialog.cpp b/LedOK/tipdialog.cpp deleted file mode 100644 index 3619c4b..0000000 --- a/LedOK/tipdialog.cpp +++ /dev/null @@ -1,416 +0,0 @@ -#include "QStandardPaths" -#include "tipdialog.h" -#include "ui_tipdialog.h" -#include "globaldefine.h" -#include -#include -#include -#include -#include -#include - -#include -TipDialog::TipDialog(QWidget *parent) : - BaseDlg(parent), - ui(new Ui::TipDialog) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); -} -TipDialog::TipDialog(QWidget *parent,int iTipDlgType): - BaseDlg(parent), - ui(new Ui::TipDialog) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - - connect(this, SIGNAL(accepted()), this, SLOT(onAccepted())); - m_iTipDlgType=iTipDlgType; - switch(iTipDlgType) { - case ENUM_IMPORT_DLG: {//Import对话框 - ui->bnOK->setEnabled(false); - ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;"); - this->resize(600,400); - setMinimumHeight(400); - ui->bnOK->setText(tr("Import")); - ui->bnCancel->setText(tr("Done")); - ui->label->setText(tr("Import")); - QLabel *pLablePaht = new QLabel(this); - pTextPath = new QLineEdit(this); - pLablePaht->setText(tr("Path")+tr(":")); - QPushButton *pSelectButton = new QPushButton(this); - //ui->verticalSpacer->changeSize(20, 20, QSizePolicy::Preferred, QSizePolicy::Expanding); - - QRect rect; - rect = pLablePaht->geometry(); - rect.setX(rect.x()+rect.width()); - rect.setWidth(this->width()-8-pLablePaht->width()-pSelectButton->width()); - pTextPath->setGeometry(rect); - pSelectButton->setText(tr("browse")); - pSelectButton->adjustSize(); - - //创建一个水平布局,水平布局里左右留12个0空格,中间放入页部件 - m_pLayoutSelectDirPath = new QHBoxLayout(); - m_pLayoutSelectDirPath->setSpacing(2); - m_pLayoutSelectDirPath->addWidget(pLablePaht); - m_pLayoutSelectDirPath->setSpacing(2); - m_pLayoutSelectDirPath->addWidget(pTextPath); - m_pLayoutSelectDirPath->setSpacing(2); - m_pLayoutSelectDirPath->addWidget(pSelectButton); - connect(pSelectButton,SIGNAL(clicked()),this,SLOT(OnSelectDir())); - //创建一个垂直布局 - QVBoxLayout *pVLayout = new QVBoxLayout(); - pVLayout->addLayout(m_pLayoutSelectDirPath, 0);//增加路径选择区到垂直布局的0区 - pVLayout->setSpacing(0); - pVLayout->addSpacing(10); - //增加列表选型到垂直布局的1区 - //创建列表控件 - ctrlProgramList = new QTableWidget(this); - ctrlProgramList->setColumnCount(2); - ctrlProgramList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - ctrlProgramList->verticalHeader()->hide(); - QStringList starr; - starr.append(tr("Solution Name")); - starr.append(tr("Progress")); - ctrlProgramList->setHorizontalHeaderLabels(starr); - //根据节目主窗口选中的节目check选型,初始化Tree控件 - //把垂直布局的内容填充到内容区 - pVLayout->addWidget(ctrlProgramList,1); - ctrlProgramList->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - ui->horizontalLayout_content->addLayout(pVLayout); - connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(OnImportPro())); - connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(accept())); - } - break; - case ENUM_DELETE_DLG: - { - ui->label->setText(tr("Delete")); - QLabel *pLablePaht = new QLabel(this); - pLablePaht->setText(tr("You will delete the selected solution(s),are you sure?")); - ui->horizontalLayout_content->addWidget(pLablePaht); - connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(accept())); - connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(reject())); - } - break; - default: break; - } - - -} -TipDialog::TipDialog(QWidget *parent,int iTipDlgType,QStringList *listProgramName,int iTipType): - BaseDlg(parent), - ui(new Ui::TipDialog) -{ - setAttribute(Qt::WA_DeleteOnClose); - ui->setupUi(this); - - connect(this, SIGNAL(accepted()), this, SLOT(onAccepted())); - m_iTipDlgType=iTipDlgType; - switch(iTipDlgType) - { - case ENUM_EXPORT_DLG: - { - ui->bnOK->setEnabled(false); - ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;"); - this->resize(600,400); - setMinimumHeight(400); - ui->bnOK->setText(tr("Export")); - ui->bnCancel->setText(tr("Done")); - ui->label->setText(tr("Export")); - QLabel *pLablePaht = new QLabel(this); - pTextPath = new QLineEdit(this); - pLablePaht->setText(tr("Path")+tr(":")); - QPushButton *pSelectButton = new QPushButton(this); - //ui->verticalSpacer->changeSize(20, 20, QSizePolicy::Preferred, QSizePolicy::Expanding); - - QRect rect; - rect = pLablePaht->geometry(); - rect.setX(rect.x()+rect.width()); - rect.setWidth(this->width()-8-pLablePaht->width()-pSelectButton->width()); - pTextPath->setGeometry(rect); - pSelectButton->setText(tr("browse")); - pSelectButton->adjustSize(); - - //创建一个水平布局,水平布局里左右留12个0空格,中间放入页部件 - QHBoxLayout *pLayoutSelectDirPath = new QHBoxLayout(); - pLayoutSelectDirPath->setSpacing(2); - pLayoutSelectDirPath->addWidget(pLablePaht); - pLayoutSelectDirPath->setSpacing(2); - pLayoutSelectDirPath->addWidget(pTextPath); - pLayoutSelectDirPath->setSpacing(2); - pLayoutSelectDirPath->addWidget(pSelectButton); - connect(pSelectButton,SIGNAL(clicked()),this,SLOT(OnSelectDir())); - //创建一个垂直布局 - QVBoxLayout *pVLayout = new QVBoxLayout(); - pVLayout->addLayout(pLayoutSelectDirPath, 0);//增加路径选择区到垂直布局的0区 - pVLayout->setSpacing(0); - pVLayout->addSpacing(10); - //增加列表选型到垂直布局的1区 - //创建列表控件 - ctrlProgramList = new QTableWidget(this); - ctrlProgramList->setRowCount(listProgramName->count()); - ctrlProgramList->setColumnCount(2); - ctrlProgramList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - ctrlProgramList->verticalHeader()->hide(); - - QStringList starr; - starr.append(tr("Solution Name")); - starr.append(tr("Progress")); - ctrlProgramList->setHorizontalHeaderLabels(starr); - //根据节目主窗口选中的节目check选型,初始化Tree控件 - for (int i = 0; i < listProgramName->count(); i++) - { - //progresss.append(progress); - wExportProgramItem *topLevelItem = new wExportProgramItem(ctrlProgramList,listProgramName->at(i),i); //创建一个 TreeItem 容器用于后来装载控件 - ctrlProgramList->setItem(i,0,topLevelItem); - } - //把垂直布局的内容填充到内容区 - pVLayout->addWidget(ctrlProgramList,1); - ctrlProgramList->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - ui->horizontalLayout_content->addLayout(pVLayout); - connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(OnExportButton())); - connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(accept())); - } - break; - case ENUM_SELECT_NETWORK: - { - setMinimumHeight(400); - ui->bnOK->setText(tr("OK")); - ui->bnCancel->setText(tr("Cancel")); - ui->label->setText(tr("Select the network to connect to the device")); - - //创建一个垂直布局 - QVBoxLayout *pVLayout = new QVBoxLayout(); - //增加列表选型到垂直布局的1区 - //创建列表控件 - QTableWidget *ctrlNetworkList = new QTableWidget(this); - ctrlNetworkList->setRowCount(listProgramName->count()); - ctrlNetworkList->setColumnCount(1); - ctrlNetworkList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - ctrlNetworkList->verticalHeader()->hide(); - - QStringList starr; - starr.append(tr("Network name")); - // starr.append(tr("hardware")); - ctrlNetworkList->setHorizontalHeaderLabels(starr); - //根据节目主窗口选中的节目check选型,初始化Tree控件 - for (int i = 0; i < listProgramName->count(); i++) - { - QTableWidgetItem *topLevelItem = new QTableWidgetItem(); //创建一个 TreeItem 容器用于后来装载控件 - topLevelItem->setData(0,listProgramName->at(i)); - //topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsEditable); - topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEditable); - - //topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable); - /*上面用到的两个枚举中:~Qt::ItemIsEnabled可以保证单击该Item时不会被选中,但是在启用Ctrl + A时,全选操作会导致Item被选中。 - * ~Qt::ItemIsSelectable的使用可以保证全选状态下也不会被选中,但是在单独使用时出现了虚线框,没有真正实现“不存在”的效果。所以必须两个同用。*/ - ctrlNetworkList->setItem(i,0,topLevelItem); - - } - //把垂直布局的内容填充到内容区 - pVLayout->addWidget(ctrlNetworkList,0); - ctrlNetworkList->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - ui->horizontalLayout_content->addLayout(pVLayout); - ui->label_2->setWordWrap(true); - ui->label_2->setAlignment(Qt::AlignTop); - if(iTipType==0) - ui->label_2->setText(tr("This operation will only set cable network to static IP,are you sure?")); - else if(iTipType==1) - ui->label_2->setText(tr("Do you want set IP of cable network to DHCP")+"?"); - ui->label_2->setText(tr("This operation will only set cable network to static IP,are you sure?")); - connect(ctrlNetworkList,SIGNAL(itemSelectionChanged()),this,SLOT(OnNetworkListSelectChanged())); - connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(accept())); - connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(reject())); - } - break; - default: - break; - - } - - -} -TipDialog::~TipDialog() -{ - if(ctrlProgramList!=nullptr) - delete ctrlProgramList; - delete ui; -} -void TipDialog::onAccepted() -{ - switch(m_iTipDlgType) - { - case ENUM_IMPORT_DLG://Import对话框 - { - if(iImportAtLeastOneSuccessFlag) - { - emit sigAcceptData(pTextPath->text(),""); - - } - else { - emit sigAcceptData("",""); - - } - } - break; - case ENUM_EXPORT_DLG: - { - emit sigAcceptData(pTextPath->text(),""); - } - break; - case ENUM_DELETE_DLG: - { - emit sigAcceptData("",""); - } - break; - case ENUM_SELECT_NETWORK: - { - if(m_strLineEditText.isEmpty()) - { - - X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("Please select the network to connect to the Led controller"),this,0); - dlg->exec(); - } - else { - emit sigAcceptData(m_strLineEditText,""); - } - } - break; - default: - break; - } -} - -void TipDialog::OnSelectDir() -{ - - QString strDir = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), - "/home", - QFileDialog::ShowDirsOnly - | QFileDialog::DontResolveSymlinks); - - pTextPath->setText(strDir); - if(!strDir.isEmpty()) - { - if(m_iTipDlgType==ENUM_IMPORT_DLG) - { - QDir root_dir(strDir); - QStringList pro_list = root_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); - QStringList listProgramName; - foreach(QString pro_name, pro_list) { - QDir pro_dir(strDir + MACRO_FENGEFU + pro_name); - if(pro_dir.exists("pro.json")) { - QFile fPro(pro_dir.path() + MACRO_FENGEFU+"pro.json"); - fPro.open(QIODevice::ReadOnly); - QJsonDocument pro = QJsonDocument::fromJson(fPro.readAll()); - fPro.close(); - QString strProgramName=pro["name"].toString(); - listProgramName.append(strProgramName); - } - } - ctrlProgramList->setRowCount(listProgramName.count()); - for(int i=0;isetItem(i,0,topLevelItem); - - } - - } - - ui->bnOK->setEnabled(true); - - ui->bnOK->setStyleSheet("background-color:rgba(28,154,210);"); - - } - else { - ui->bnOK->setEnabled(false); - ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;"); - - } - -} -void TipDialog::OnExportButton() -{ - QString strDestPath=pTextPath->text(); - if(!strDestPath.isEmpty()){ - QDir qDirDest(pTextPath->text()); - if(qDirDest.exists()){ - QString doc_path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); - if(!doc_path.isEmpty()) { - QString app_path = doc_path + "/" + QApplication::applicationName(); - QString strSourceDir = app_path + "/NPrograms"; - for(int i=0;irowCount();i++) - { - wExportProgramItem *pItem= static_cast(ctrlProgramList->item(i,0)); - pItem->ExportPro(strDestPath,strSourceDir); - qDebug()<exec(); - - } - -} -void TipDialog::OnImportPro() -{ - QString strSourcePath=pTextPath->text(); - if(!strSourcePath.isEmpty()) - { - //查找当前目录下发现的导出节目项,加入到列表, - QString doc_path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); - QString app_path = doc_path + "/" + QApplication::applicationName(); - QString strDestPath = app_path + "/NPrograms"; - if(strSourcePath.contains(strDestPath,Qt::CaseInsensitive)) - { - X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("The imported directory is already in the working directory, so there is no need to import it again!"),this,0); - dlg->exec(); - return; - } - - if(ctrlProgramList->rowCount()>0)//如果列表大于0,说明有符合的项目 - { - if(!doc_path.isEmpty()) { - QDir qDirDest(strDestPath); - - if(qDirDest.exists()) - { - - for(int i=0;irowCount();i++) - { - wExportProgramItem *pItem= static_cast(ctrlProgramList->item(i,0)); - if(pItem->ExportPro(strDestPath,strSourcePath)) - { - iImportAtLeastOneSuccessFlag=true; - ui->bnClose->setVisible(false); - } - //qDebug()<exec(); - - } - - } - else - { - X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("Please select the network to connect to the Led controller"),this,0); - dlg->exec(); - - } -} - -void TipDialog::OnNetworkListSelectChanged() -{ - QTableWidget *pl = findChild(); - m_strLineEditText=pl->selectedItems()[0]->text(); -} diff --git a/LedOK/tipdialog.h b/LedOK/tipdialog.h deleted file mode 100644 index f69b2e2..0000000 --- a/LedOK/tipdialog.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef TIPDIALOG_H -#define TIPDIALOG_H -#include -#include -#include -#include -namespace Ui { -class TipDialog; -} - -class TipDialog : public BaseDlg -{ - Q_OBJECT - -public: - explicit TipDialog(QWidget *parent = nullptr); - TipDialog(QWidget *parent,int iTipDlgType); - TipDialog(QWidget *parent,int iTipDlgType,QStringList *list,int iTipType); - ~TipDialog(); - -public: - QLineEdit *pTextPath; - QString m_strLineEditText; -signals: - void sigAcceptData(QString string1, QString string2); -protected slots: - void onAccepted(); - void OnSelectDir(); - void OnExportButton(); - void OnImportPro(); - void OnNetworkListSelectChanged(); -private: - Ui::TipDialog *ui; - int m_iTipDlgType; - QTableWidget *ctrlProgramList=nullptr; - QHBoxLayout *m_pLayoutSelectDirPath=nullptr; - bool iImportAtLeastOneSuccessFlag=false; -}; - -#endif // TIPDIALOG_H diff --git a/LedOK/tipdialog.ui b/LedOK/tipdialog.ui deleted file mode 100644 index 774bb7a..0000000 --- a/LedOK/tipdialog.ui +++ /dev/null @@ -1,210 +0,0 @@ - - - TipDialog - - - - 0 - 0 - 378 - 149 - - - - - - - - - - - - QLayout::SetMaximumSize - - - 0 - - - - - - 0 - 0 - - - - font-size:16px; - - - TextLabel - - - Qt::AlignCenter - - - - - - - - 31 - 24 - - - - - 31 - 16777215 - - - - X - - - - - - - - - - 0 - 1 - - - - - 0 - 1 - - - - border-top: 1.5px solid gray; - - - 6 - - - 1 - - - Qt::Horizontal - - - - - - - 0 - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - false - - - border-top: 1px solid gray; - - - 0 - - - 0 - - - Qt::Horizontal - - - - - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - OK - - - - - - - Cancel - - - - - - - - - - - - - - - - bnClose - clicked() - TipDialog - close() - - - 445 - 21 - - - 239 - 159 - - - - - diff --git a/LedOK/tools.cpp b/LedOK/tools.cpp index 71e2528..91aab47 100644 --- a/LedOK/tools.cpp +++ b/LedOK/tools.cpp @@ -1,18 +1,10 @@ #include "tools.h" #include "cfg.h" #include "globaldefine.h" -#include "wProgramManager/pagelistitem.h" +#include "program/pagelistitem.h" #include "base/x_uimsgboxok.h" -#include -#include -#include #include #include -extern "C"{ -#include -#include -#include -} void Tools::timerEvent(QTimerEvent *event) { if(timer_id==event->timerId()) emit sTick(); @@ -43,244 +35,7 @@ QString Tools::addSufix(QString path) { while(QFileInfo::exists(path = prefix+QString::number(i)+sufix)) i++; return path; } -QString Tools::videoInfo(QByteArray url, QImage &img, int64_t *dur, AVCodecID *codec_id) { - AVFormatContext *fmt_ctx = avformat_alloc_context(); - QString err; - { - if(avformat_open_input(&fmt_ctx, url.constData(), nullptr, nullptr) != 0) { - err = "Couldn't open input stream"; - goto free; - } - if(avformat_find_stream_info(fmt_ctx, nullptr) < 0) { - err = "Couldn't find stream information"; - goto free; - } - if(dur!=nullptr) *dur = fmt_ctx->duration; - int vi_idx = -1; - for(uint ss=0; ssnb_streams; ss++) if(fmt_ctx->streams[ss]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) vi_idx = ss; - if(vi_idx == -1) { - err = "Didn't find a Video Stream"; - goto free; - } - auto codecpar = fmt_ctx->streams[vi_idx]->codecpar; - if(codec_id!=nullptr) *codec_id = codecpar->codec_id; - qDebug()<<"codec_id"<codec_id<codec_id); - if(av_seek_frame(fmt_ctx, -1, 1000000, AVSEEK_FLAG_BACKWARD) < 0) { - err = "av_seek_frame fail"; - goto free; - } - const AVCodec *decoder = avcodec_find_decoder(codecpar->codec_id); - if(decoder==nullptr) { - err = "Could not found Video Decoder"; - goto free; - } - auto vcCtx = avcodec_alloc_context3(decoder); - avcodec_parameters_to_context(vcCtx, codecpar); - if(avcodec_open2(vcCtx, decoder, nullptr) < 0) { - err = "Could not open Video Codec Ctx"; - avcodec_free_context(&vcCtx); - goto free; - } - auto sws_ctx = sws_getContext(vcCtx->width, vcCtx->height, vcCtx->pix_fmt, vcCtx->width, vcCtx->height, AV_PIX_FMT_RGB32, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr); - auto packet = av_packet_alloc(); - auto frm = av_frame_alloc(); - while(1) { - if(av_read_frame(fmt_ctx, packet) < 0) break; - if(packet->stream_index != vi_idx) continue; - int res = avcodec_send_packet(vcCtx, packet); - if(res < 0) break; - while((res = avcodec_receive_frame(vcCtx, frm)) != AVERROR(EAGAIN)) { - if(res < 0) goto free2; - img = QImage(vcCtx->width, vcCtx->height, QImage::Format_ARGB32); - uint8_t *dst[4]{img.bits()}; - int dstStride[4]{img.bytesPerLine()}; - sws_scale(sws_ctx, frm->data, frm->linesize, 0, vcCtx->height, dst, dstStride); - goto free2; - } - } - free2: - av_frame_free(&frm); - av_packet_free(&packet); - avcodec_free_context(&vcCtx); - sws_freeContext(sws_ctx); - } - free: - avformat_close_input(&fmt_ctx); - return err; -} -QString trans(int sw, int sh, int dw, int dh, int cnt, QPointF pos, QByteArray file) { - AVFormatContext *in_fmt = avformat_alloc_context(), *out_fmt = 0; - AVCodecContext *de_ctx = 0, *en_ctx = 0; - QString err; - char buf[AV_ERROR_MAX_STRING_SIZE]; - int ret; - { - if((ret = avformat_open_input(&in_fmt, file.constData(), nullptr, nullptr)) < 0) { - err = QString("Couldn't open input stream. ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free; - } - if((ret = avformat_find_stream_info(in_fmt, nullptr)) < 0) { - err = QString("Couldn't find stream information. ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free; - } - auto outfile = file+"-square.mp4"; - if((ret = avformat_alloc_output_context2(&out_fmt, 0, "mp4", outfile.constData())) < 0) { - err = QString("avformat_alloc_output_context2 fail. ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free; - } - int vi_idx = -1; - for(int ss=0; ssnb_streams; ss++) { - AVStream *stream = in_fmt->streams[ss]; - AVStream *newStream = avformat_new_stream(out_fmt, 0); - if((ret = avcodec_parameters_copy(newStream->codecpar, stream->codecpar)) < 0) { - err = QString("avcodec_parameters_copy fail. ") + av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free; - } - //LOGD("fourcc %s",av_fourcc2str(newStream->codecpar->codec_tag)); - if(vi_idx == -1 && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) vi_idx = ss; - } - if(vi_idx == -1) { - err = "Didn't find a Video Stream"; - goto free; - } - auto codecpar = in_fmt->streams[vi_idx]->codecpar; - qDebug()<<"codec_id"<codec_id<codec_id); - - auto decoder = avcodec_find_decoder(codecpar->codec_id); - if(decoder==0) { - err = "Could not found Video Decoder"; - goto free; - } - de_ctx = avcodec_alloc_context3(decoder); - avcodec_parameters_to_context(de_ctx, codecpar); - if(avcodec_open2(de_ctx, decoder, 0) < 0) { - err = "Could not open Video Codec Ctx"; - goto free; - } - auto sws_ctx = sws_getContext(de_ctx->width, de_ctx->height, de_ctx->pix_fmt, sw, sh, AV_PIX_FMT_ARGB, SWS_FAST_BILINEAR, 0, 0, 0); - - auto encoder = avcodec_find_encoder(AV_CODEC_ID_H264); - if(encoder==0) { - fprintf(stderr, "Codec not found\n"); - goto free; - } - en_ctx = avcodec_alloc_context3(encoder); - avcodec_parameters_to_context(en_ctx, codecpar); - if(avcodec_open2(en_ctx, encoder, 0) < 0) { - err = "Could not open Video Codec Ctx"; - goto free; - } - en_ctx->pix_fmt = AV_PIX_FMT_ARGB; - en_ctx->bit_rate = dw*dh/150000; //码率 清晰度有关 - en_ctx->width = dw; - en_ctx->height = dh; - qDebug()<<"gop_size"<gop_size; - qDebug()<<"max_b_frames"<max_b_frames; - if (avcodec_open2(en_ctx, encoder, 0) < 0) { - fprintf(stderr, "Could not open codec\n"); - goto free; - } - avcodec_parameters_from_context(out_fmt->streams[vi_idx]->codecpar, en_ctx); - - if(out_fmt->flags & AVFMT_NOFILE) qDebug()<<"AVFMT_NOFILE"; - else if((ret = avio_open(&out_fmt->pb, outfile.constData(), AVIO_FLAG_WRITE)) < 0) { - err = QString("avio_open fail. ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free; - } - if((ret = avformat_write_header(out_fmt, 0)) < 0) { - err = QString("avformat_write_header fail. ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free; - } - - auto packet = av_packet_alloc(); - auto frm = av_frame_alloc(); - while(1) { - if((ret = av_read_frame(in_fmt, packet)) < 0) { - if(ret!=AVERROR_EOF) { - err = QString("Read packet fail: ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - break; - } - ret = avcodec_send_packet(de_ctx, 0); - } else { - if(packet->stream_index != vi_idx) { - av_write_frame(out_fmt, packet); - continue; - } - ret = avcodec_send_packet(de_ctx, packet); - } - if(ret < 0) break; - while((ret = avcodec_receive_frame(de_ctx, frm)) != AVERROR(EAGAIN)) { - if(ret < 0) { - if(ret!=AVERROR_EOF) { - err = QString("Receive frame fail: ")+av_strerror(ret, buf, AV_ERROR_MAX_STRING_SIZE); - goto free2; - } - ret = avcodec_send_frame(en_ctx, 0); - } else { - QImage img(sw, sh, QImage::Format_ARGB32); - uint8_t *dst[4]{img.bits()}; - int dstStride[4]{img.bytesPerLine()}; - sws_scale(sws_ctx, frm->data, frm->linesize, 0, de_ctx->height, dst, dstStride); - auto out_frm = av_frame_alloc(); - av_image_alloc(out_frm->data, out_frm->linesize, dw, dh, AV_PIX_FMT_ARGB, 8); - av_frame_copy_props(out_frm, frm); - out_frm->width = dw; - out_frm->height = dh; - out_frm->format = AV_PIX_FMT_ARGB; - QImage out_img(out_frm->data[0], dw, dh, out_frm->linesize[0], QImage::Format_ARGB32); - QPainter painter(&out_img); - painter.drawImage(pos, img); - for(int i=1; iduration; - } - free: - avformat_close_input(&fmt_ctx); - return err; -} QString Tools::readErrStr(QImageReader::ImageReaderError err) { if(err==QImageReader::UnknownError) return "UnknownError"; if(err==QImageReader::FileNotFoundError) return "FileNotFoundError"; @@ -301,30 +56,33 @@ QString Tools::fileMd5(QString filePath) { file.close(); return QString::fromLatin1(cryptoHash.result().toHex()); } -void Tools::mergeFormat(QTextEdit *textEdit, const QTextCharFormat &format) { +void Tools::mergeFormat(QTextEdit *textEdit, const QTextCharFormat &fmt) { QTextCursor cursor = textEdit->textCursor(); if(! cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - textEdit->mergeCurrentCharFormat(format); + cursor.mergeCharFormat(fmt); } void Tools::saveImg(const QString& dir, const QFontMetrics& metric, const QFont& font, const QColor& color, QJsonObject& imgs, const QString& str, const QString& name) { if(str.isEmpty()) return; QImage img(metric.horizontalAdvance(str), metric.lineSpacing(), QImage::Format_ARGB32); img.fill(Qt::transparent); - QPainter painter(&img); - painter.setFont(font); - painter.setPen(color); - QTextOption opt(Qt::AlignCenter); - opt.setWrapMode(QTextOption::NoWrap); - painter.drawText(QRectF(0, 0, img.width(), img.height()), str, opt); - QBuffer buf; - if(! img.save(&buf, "PNG")) return; + { + QPainter painter(&img); + painter.setFont(font); + painter.setPen(color); + QTextOption opt(Qt::AlignCenter); + opt.setWrapMode(QTextOption::NoWrap); + painter.drawText(QRectF(0, 0, img.width(), img.height()), str, opt); + } + QByteArray data; + QBuffer buffer(&data); + buffer.open(QIODevice::WriteOnly); + if(! img.save(&buffer, "PNG")) return; QCryptographicHash cryptoHash(QCryptographicHash::Md5); - cryptoHash.addData(buf.data()); + cryptoHash.addData(data); auto md5 = QString::fromLatin1(cryptoHash.result().toHex()); QFile file(dir+"/"+md5); if(! file.open(QFile::WriteOnly)) return; - file.write(buf.data()); + file.write(data); file.close(); imgs.insert(name, md5); } @@ -336,22 +94,26 @@ void Tools::saveImg2(const QString& dir, const QFontMetrics& metric, const QFont if(! str.isEmpty()) { QImage img(metric.horizontalAdvance(str), metric.lineSpacing(), QImage::Format_ARGB32); img.fill(Qt::transparent); - QPainter painter(&img); - painter.setFont(font); - painter.setPen(color); - QTextOption opt(Qt::AlignCenter); - opt.setWrapMode(QTextOption::NoWrap); - painter.drawText(QRectF(0, 0, img.width(), img.height()), str, opt); - QBuffer buf; - if(img.save(&buf, "PNG")) { + { + QPainter painter(&img); + painter.setFont(font); + painter.setPen(color); + QTextOption opt(Qt::AlignCenter); + opt.setWrapMode(QTextOption::NoWrap); + painter.drawText(QRectF(0, 0, img.width(), img.height()), str, opt); + } + QByteArray data; + QBuffer buffer(&data); + buffer.open(QIODevice::WriteOnly); + if(img.save(&buffer, "PNG")) { obj.insert("picWidth", img.width()); obj.insert("picHeight", img.height()); QCryptographicHash cryptoHash(QCryptographicHash::Md5); - cryptoHash.addData(buf.data()); + cryptoHash.addData(data); auto md5 = QString::fromLatin1(cryptoHash.result().toHex()); QFile file(dir+"/"+md5); if(file.open(QFile::WriteOnly)) { - file.write(buf.data()); + file.write(data); file.close(); obj.insert("id", md5); } @@ -385,34 +147,3 @@ QColor Tools::int2Color(int value) { QString Tools::selectStr(bool f, const QString &s0, const QString &s1) { return f ? s0 : s1; } - -QString Tools::convertFileSize(const qint64 & bytes){ - float num = bytes; - QStringList list; - list << "KB" << "MB" << "GB" << "TB"; - - QStringListIterator i(list); - QString unit("bytes"); - - while(num >= 1024.0 && i.hasNext()) - { - unit = i.next(); - num /= 1024.0; - } - return QString().setNum(num,'f',2)+" "+unit; -} -QString Tools::styleSheet() { - QStringList qsses = QDir(":/qss").entryList(QStringList{"*.css"}); - std::sort(qsses.begin(), qsses.end(), [](const QString &a, const QString &b) { - return a < b; - }); - QString qss; - foreach(QString qss_name, qsses) { - QFile f(":/qss/" + qss_name); - if(f.exists() && f.open(QFile::ReadOnly)) { - qss += f.readAll(); - f.close(); - } - } - return qss; -} diff --git a/LedOK/tools.h b/LedOK/tools.h index 7f4ec12..28d7c08 100644 --- a/LedOK/tools.h +++ b/LedOK/tools.h @@ -2,8 +2,8 @@ #define TOOLS_H #include "devicepanel.h" -#include "wProgramManager/progitem.h" -#include "wDevicesManager/ledcard.h" +#include "program/progitem.h" +#include "device/ledcard.h" #include #include #include @@ -14,9 +14,7 @@ #include #include #include -extern "C"{ -#include -} + const QString str0_9[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; extern QWidget *gMainWin; extern DevicePanel *gDevicePanel; @@ -25,6 +23,7 @@ extern QTextEdit *gFdResInfo; extern QString gFileHome; extern QWidget *gProgEditorWin; extern ProgItem *gProgItem; +extern QString css; class Tools : public QObject { Q_OBJECT @@ -37,9 +36,6 @@ public: static QRectF centerRect(qreal, qreal, int, int); static QString addSufix(QString); static void mergeFormat(QTextEdit *textEdit, const QTextCharFormat &format); - static QString videoInfo(QByteArray url, QImage &, int64_t *dur, AVCodecID *); - static QString trans(int sw, int sh, int dw, int dh, int cnt, QPointF pos, QByteArray file); - static QString audioInfo(QByteArray url, int64_t *dur); static QString readErrStr(QImageReader::ImageReaderError); static QString fileMd5(QString); static void saveImg(const QString&, const QFontMetrics&, const QFont&, const QColor&, QJsonObject&, const QString&, const QString&); @@ -48,8 +44,6 @@ public: static int color2Int(const QColor& color); static QBrush getBrush(const QColor& color); static QString selectStr(bool f, const QString &s0, const QString &s1 = ""); - static QString convertFileSize(const qlonglong & bytes); - static QString styleSheet(); ~Tools() { killTimer(timer_id); } diff --git a/LedOK/translations/app_en.ts b/LedOK/translations/app_en.ts index da3b515..2228255 100644 --- a/LedOK/translations/app_en.ts +++ b/LedOK/translations/app_en.ts @@ -71,1339 +71,202 @@ Password changed successfully - - ControlEncryptWidget - - - Form - Form - - - - - Entrypt Configuration - Entrypt configuration - - - - Original password - Original password - - - - - - original password - original password - - - - - - New password - New password - - - - - Repeat new password - Repeat new password - - - - - - - Set encryption - Set encryption - - - - - Cancel encryption - Cancel encryption - - - - - Enter password - Enter password - - - - Enter again - Enter again - - - - - - - - - Tip - Tip - - - - NoSelectedController - Please select screen first - - - - - InputOriginalPasswordTip - Please input original password - - - - InputNewPasswordTip - Please input new password - - - - InputRepeatPasswordTip - Please input repeat password - - - - InputRepeatPasswordNotSameTip - The two passwords are inconsistent - - - - Tip Info - Tip Info - - - - After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? - After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? - - - - - SetControllerPassword - Set password - - - - Readback - Readback - - - - - - Success - Success - - - - - - failed - failed - - - - - Modify password - Modify password - - - - OriginalPasswordErrorTip - The original password is wrong - - - - ControlHdmiSchedule - - - Form - Form - - - - - Add - Add - - - - - Delete - Delete - - - - - Clear - Clear - - - - - Import - Import - - - - - Export - Export - - - - By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period - By default, asynchronous content is played, and synchronous hdmi-in port input content is played in a fixed time period - - - - - Apply - Apply - - - - Readback - Readback - - - - SYNC HDMI - HDMI-IN video - - - - Start Time - Start Time - - - - End Time - End Time - - - - SUN - SUN - - - - MON - MON - - - - TUE - TUE - - - - WED - WED - - - - THU - THU - - - - FRI - FRI - - - - SAT - SAT - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - - On - On - - - - SyncSchedule (*.syncs) - - - - - Save File - Save file - - - - Sync Schedule (*.syncs) - - - - - - Tip - Tip - - - - - NoSelectedController - Please select screen first - - - - SetTimingHdmiInTask - Set video source form HDMI-IN schedule task - - - - GetTimingHdmiInTask - Get video source form HDMI-IN schedule task - - - - - Success - Success - - - - - failed - failed - - - - ControlHdmiWidget - - - HDMI Configuration - Video source configuration - - - - Manual - Manual - - - - Schedule - Schedule - - - - - Tip - Tip - - - - - NoSelectedController - Please select screen first - - - - - SyncSwitch - Switch video source from HDMI-IN port - - - - - AnSyncSwitch - Switch video source from Async box - - - - - IsSync - Readback video source - - - - Error - Error - - - - HDMI IN - HDMI IN - - - - Async - Async - - - - Readback - Readback - - - - ControlNetConfigWidget - - - Wire Enther(RJ45) Configuration - Wire Enther(RJ45) Configuration - - - - - DHCP - - - - - - Specify IP - Specify IP - - - - - IP Address - IP Address - - - - Mask Address - Subnet mask - - - - - Gateway - Gateway - - - - - DNS Address - DNS Address - - - - - - - - - - Set - Set - - - - - - - - - Readback - Readback - - - - - WIFI Configuration - WiFi Configuration - - - - - WiFi On/Off - WiFi On/Off - - - - Input Ap name - Input ap name - - - - - 4G/5G Configuration - Cellular Configuration - - - - - Open 4G/5G - Enable cellular data - - - - APN: - - - - - - Get cellular network status information - Get cellular network status information - - - - - Check SIM can automatically match to MCC, and then select carrier get apn param,if not found carrier,you can check the CUSTOM checkbox,then enter custom param. - Through the chcek status button, you can automatically match the country code MCC, and then select "operator" to get the response APN information. If you can't find the operator, you can select the "custom" check box, and then enter the APN information manually. - - - - - Readback APN Info - Readback APN Info - - - - - Set Apn Info,Check SIM can automatically match to MCC, and then select carrier get apn param - Set the APN information - - - - - CUSTOM - CUSTOM - - - - - Check SIM - chcek SIM Info - - - - - - -> - - - - - - Country ID(mcc): - Country ID(mcc): - - - - - Carrier Name - Carrier Name - - - - - APN: - Carrier APN: - - - - - APN(Required) - APN(Required) - - - - - User: - User Name: - - - - - - - Not required - Not required - - - - - Password: - Password: - - - - Set Apn:iot.cargo - - - - - - Flight Mode - Flight Mode - - - - - WiFi name - WiFi name - - - - - - - Password - Password - - - - - - - Input password - Input password - - - - - Scan - Scan - - - - - Ap Mode - AP - - - - Ap name - AP name - - - - OFF - OFF - - - - ON - ON - - - - AP name - AP name - - - - Subnet mask - Subnet mask - - - - Input ap name - Input AP name - - - - - - - - - - - - - - - Success - Success - - - - - - - - - - - - - - - failed - failed - - - - - - - Tip - Tip - - - - - NoSelectedController - Please select screen first - - - - - SetEthernet - Set wire nether - - - - - - - - - - - Attention - Attention - - - - Please input IP address! - Please input IP address! - - - - Your IP Address is Invalid! - IP Address is invalid! - - - - Please input Mask address! - Please input Mask address! - - - - Your Mask Address is Invalid! - Mask Address is Invalid! - - - - Please input Gateway address! - Please input Gateway address! - - - - Your Gateway Address is Invalid! - Gateway Address is Invalid! - - - - Please input DNS address! - Please input DNS address! - - - - Your DNS Address is Invalid! - DNS Address is Invalid! - - - - - GetEthernet - Get wire ethernet - - - - DHCP IP - DHCP IP - - - - STATIC IP - STATIC IP - - - - Error - Error - - - - - - - - - SignalPower - Signal strength - - - - - ConfigurationWiFi - Configuration WiFi - - - - IsPortableHotSpot - Get AP or WiFi - - - - GetWifiList - Scan WiFi list - - - - ConfigurationHotSpot - Configuration AP HotSpot - - - - GetCurrentAPN - Get Current Apn - - - - - GetSIMStatus - Get SIM Status - - - - SetAPN - Set APN - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - 状态: - Status: - - - - 未知 - unknown - - - - 锁定状态,需要用户的PIN码解锁 - Lock status, need user's pin code to unlock - - - - 锁定状态,需要用户的PUK码解锁 - In the locked state, the PUK code of the user is required to be unlocked - - - - 锁定状态,需要网络的PIN码解锁 - In the locked state, the PIN code of the user is required to be unlocked - - - - 就绪 - be ready - - - - no checked sim card - no checked sim card - - - - 国家码: - MCC: - - - - 号码: - number: - - - - 用户: - User name: - - - - 信号: - Signal: - - - - 信号正常 - Signal OK - - - - 不在服务区 - Not in service area - - - - 仅限紧急呼叫 - Emergency call only - - - - 射频已经关闭 - RF off - - - - 网络: - Network type: - - - - 网络类型未知 - unKnown - - - - GPRS网络 - GPRS - - - - EDGE网络 - EDGE - - - - UMTS网络 - UMTS - - - - CDMA网络,IS95A 或 IS95B. - CDM - - - - EVDO网络, revision 0. - EVDO,revision 0. - - - - EVDO网络, revision A. - EVDO,revision A. - - - - 1xRTT网络 - 1xRTT - - - - HSDPA网络 - HSDPA - - - - HSUPA网络 - HSUPA - - - - HSPA网络 - HSPA - - - - 漫游: - roam: - - - - Yes - Yes - - - - No - No - - - - 数据连接状态: - Data connection status: - - - - 断开 - OFF - - - - 正在连接 - connecting - - - - 已连接 - Connected - - - - 暂停 - suspend - - - - 数据活动休眠状态: - Data active sleep state: - - - - 活动,但无数据发送和接收 - Active, but no data sent and received - - - - 活动,正在接收数据 - Activity, receiving data - - - - 活动,正在发送数据 - Activity, sending data - - - - 活动,正在接收和发送数据 - Activity, receiving and sending data - - - - 休眠状态 - Sleep state - - - - 信号强度: - Signal strength: - - - - SetSwitchSimData - SetSwitchSimData - - - - ContrFlightMode - Set flight mode - - - - GetFlightModeState - Readback flight mode state - - - - ControlPowerManual - - - Form - Form - - - - - POWER - Power - - - - - - Readback - Readback - - - - OFF - OFF - - - - ON - ON - - - - - Tip - Tip - - - - - NoSelectedController - Please select screen first - - - - IsScreenOn - Read power status - - - - - - SetScreenOn - Set power - - - - - - - Success - Success - - - - - on - ON - - - - - - - failed - failed - - - - - off - OFF - - - - - SetScreenOff - SetScreenOff - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - ControlPowerSchedule - + Form Form - + Edit area Edit area - - + + Add Add - - + + Delete Delete - - + + Clear Clear - - + + Import Import - - + + Export Export - + It is power off state outside the schedule time period It is power off state outside the schedule time period - + Send command Command area - - + + Apply Apply - + Clear Schedule Cancel Schedule - + Readback Readback - + Power On State Power On State - + Start Time Start Time - + End Time End Time - + SUN SUN - + MON MON - + TUE TUE - + WED WED - + THU THU - + FRI FRI - + SAT SAT - - + + DeviceItem OnProHttpResponse 解析json文件错误! - - + + On On - - + + PowerSchedule (*.pjs) PowerSchedule (*.pjs) - + Save File Save file - - - + + + Tip Tip - - - + + + NoSelectedController Please select screen first - - + + Tip Info Tip Info - - + + Clear schedule task? Clear schedule task? - - + + CleanTimingScreenTask Clear schedule task - + SetTimingScreenTask Set schedule task of screen power - - - - + + + + Success Success - - - - + + + + failed failed - + GetTimingScreenTask Get schedule task of screen power @@ -1411,678 +274,378 @@ ControlPowerWidget - - Form - Form + + + Off + - - + + + On + On + + + + + Tip + Tip + + + + + NoSelectedController + Please select screen first + + + + + SetScreenOn + Set Screen On + + + + + SetScreenOff + Set Screen Off + + + + + IsScreenOn + Read power status + + + Power Configuration Power configuration - - + Manual Manual - - + Schedule Schedule + + + Power + Power + + + + Readback + Readback + ControlTestWidget - + Form Form - - + + Test Screen Test Screen - - + + Line test Line test - - - - - - - + + + + + + + Red Red - - - - - - - + + + + + + + Green Green - - - - - - - + + + + + + + Blue Blue - - - - - - - + + + + + + + White White - - + + Vertical Vertical - - + + Slash Oblique line - - - + + + Horizontal Horizontal - - - - + + + + Speed Speed - - + + ms(>10) - - + + Line Distance Line Distance - + px px - - - - - + + + + + Test Test - - + + Gradation test Gradation test - - + + Only the gray value is displayed Only the gray value is displayed - + (>10) - - + + GrayValue Gray value - + (0-255) - - + + Color test Color test - - + + Gradient Gradient - + 8 8 - + 2 2 - + 3 3 - + 6 6 - + 4 4 - + 5 5 - + 1 1 - + 9 9 - + 7 7 - + 0 0 - - + + Clear Clear - - + + Reset Loop - - - - + + + + Anycast Anycast - - + + Stop Stop - - - - - - - - + + + + + + + + Tip Tip - - - - - + + + + + NoSelectedController Please select screen first - - - + + + StartTest Start test - - - - + + + + Success Success - - - - + + + + failed failed - + StopTest Stop test - + loopback mode loopback mode - + Connect timeout Connect timeout - + Reset loop mode Reset loop mode - - + + success success - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse json error! - - - - CtrlVerifyClockPanel - - - Form - Form - - - - English - English - - - - 中文 - - - - - Verify Clock Configuration - Verify clock configuration - - - - Verify to Computer time - Verify to Computer time - - - - - Cur time of controller - Cur time of controller - - - - LAN - LAN - - - - (min/time) - (min/time) - - - - Sync identificationCode - Sync identificationCode - - - - - identification code - identification code - - - - - Time offset(msec) - Time offset(msec) - - - - - Brightness - Screen Brightness - - - - - Volume - Volume - - - - - Screen on/off - Screen On/Off - - - - - Slave - Slave - - - - Master - Master - - - - - NTP Server - NTP Server - - - - - - - NTP Server address - NTP Server address - - - - - - - TimeZone - Time zone - - - - - - - - - - - - - - - Set - Set - - - - - Language: - Language: - - - - - Enable Synchronous playing - Enable Synchronous playing - - - - Lora - - - - - GPS - - - - - NTP - - - - - Time zone - Time zone - - - - - - - Sync time interval - Sync time interval - - - - Verify clock configuration - Verify clock configuration - - - - - - - - - - - - - - Readback - Readback - - - - Master - Master - - - - Sync clock to computer time - Calibrate clock to computer time - - - - Identification Code - Identification Code - - - - - - - - - - - - - - Success - Success - - - - - - - - - - - - - - failed - failed - - - - SetNtpServer - SetNtpServer - - - - MasterSwitch - Set as master device - - - - SlaveSwitch - Set as slave device - - - - IsMasterSlave - Read back the identity of master and slave - - - - GetControllerDate - Get date time - - - - SetingSyncMethod - Set sync method - - - - SyncTime - SyncTime - - - - GetNtpServer - GetNtpServer - - - - GetingSyncMethod - Geting Sync Method - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - SetTimezone - Set Timezone - - - - ControlVolumeManual - - - Form - Form - - - - Volume(0-15) - Volume(0-15) - - - - - - Readback - Readback - - - - SetVolume - Set Volume - - - - - - Success - Success - - - - - - failed - failed - - - - Volume(min:0-max:15) - Volume(min:0-max:15) - - - - GetVolume - Get Volume - - - - + + DeviceItem OnProHttpResponse 解析json文件错误! DeviceItem OnProHttpResponse json error! @@ -2090,174 +653,174 @@ ControlVolumeSchedule - + Defalut volume tip Reminder: the brightness within the fixed time period is displayed according to the timing brightness, and the default brightness value is not set for other time periods - - + + Add Add - - + + Delete Delete - - + + Clear Clear - + Default Volume Default Volume - + (0-15) - - + + Import Import - - + + Export Export - - + + Apply Apply - + Readback Readback - + Volume value Volume value - + Start Time Start Time - + End Time End Time - + SUN SUN - + MON MON - + TUE TUE - + WED WED - + THU THU - + FRI FRI - + SAT SAT - + Default volume tip Reminder: the display screen is the default brightness outside the fixed time period - + Default volume Default volume - - + + DeviceItem OnProHttpResponse 解析json文件错误! DeviceItem OnProHttpResponse json error! - + 10 10 - - + + Volume Schedule (*.vols) - + Save File Save file - - + + Tip Tip - - + + NoSelectedController Please select screen first - + SetAutoVolumeTask Set volume schedule - - + + Success Success - - + + failed failed - + GetAutoVolumeTask Get volume schedule @@ -2265,1187 +828,2504 @@ ControlVolumeWidget - - Form - Form + + + Tip + Tip - - + + + NoSelectedController + Please select screen first + + + + + SetVolume + Set Volume + + + + + GetVolume + Get Volume + + + Volume Control Volume Control - - + Manual Manual - - + Schedule Schedule + + + Volume + Volume + + + + Readback + Readback + CtrlAdvancedPanel - - Advanced parameters - Advanced parameters + + Advanced + Advanced - + Screen Width(pixel) Screen Width(pixel) - + Width Width - - + + Height Height - - - - - - - + + + + + + + + + + + + + + + Set Set - + Alias Alias - + Web Server Address: Web Server Address: - + www.m2mled.net - + www.ledaips.com - + https://www.taxihub.cn:2340 - + https://www.ledaips.com:2340 - + https://www.36taxi.com:2340 - + www.tlzxled.com - + + MCU Uploading + + + + + Traffic screen settings + + + + + Setting protocol ... + + + + + Set protocol + + + + + Getting protocol ... + + + + + Get protocol + + + + + + Port + + + + Realtimer Server Address: Realtimer Server Address: - + + Firmware Management + + + + + update or uninstall + + + + Clear Clear - - Apk upgrade - Apk upgrade - - - + Check Apk Check Apk - + Uninstall Uninstall - + Running check Running check - - FPGA version check - FPGA version check + + Restart + Restart - - Sync FPGA version - Sync FPGA version - - - - Restart led controller system - Restart led controller system - - - + Check Log Check Log - + Start LedSet4 Start LedSet4.0 (Apk Display2.0 and higher) - + Open ADB Open ADB debugging function - + Post Custom JSON Post Custom JSON - - - - - - - - + + + + + + + + Clear Program Clear Program - + www.ledokcloud.com/realtime - - M80 configuration - M80 configuration + + Config + Config - + Refresh Refresh - + Restore to default Restore to default - + Taxi top screen configuration Taxi top screen configuration - + + Service:High Out of service:Low Service:High Out of service:Low - + + Service:Low Out of service:High Service:Low Out of service:High - + Start LedSet3.0 configure LED module Start LedSet3.0 configure LED module (used by manufacturer's professionals) - + Binding *.ic account indentity voucher Binding *.ic account indentity voucher - + Rotate Rotate - - 0 degrees - 0 degrees - - - - 90 degrees - 90 degrees - - - - 180 degrees - 180 degrees - - - - 270 degrees - 270 degrees - - - + Min brightness Min brightness - - (min:1) - (min:1) - - - - - + + + Readback Readback - - - + Send Send - + Max brightness Max brightness - - (max:255) - (max:255) - - - - + + SetScreenSize Set Screen Size - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Success Success - + Compant ID: Company ID - - FPGA Upgrade - FPGA Upgrade - - - + Compant ID Company ID - + InputWebServerAddressTip Please enter web server address - + InputCompanyIdTip Please enter company ID - + Do you want to modify webserveraddress and companyId? Are you sure you want to configure the server address and company ID? - - - - - - - - - - - - - - - - - - - - - - failed - failed - - - - + + SetOnlineAddr Set Web server address - + + ClearRealtimeServer Clear - - InputRealTimeAddressTip - Please enter the realtimer address - - - + + SetRealtimeServer Set realtimer address - - - - + + + + Tip Info Tip Info - - - + + + Can not find LedSet3.0.exe,down you need download and install it Can not find LedSet3.0.exe,down you need download and install it - + + RestartAndroid Restart - - FPGA Version - FPGA Version - - - - + + running running - - + + no running no running - + Check Apk Version Check Apk Version - - + + UninstallSoftware Uninstall - - - IsSoftwareRunning - Check apk running status - - - - apk package (*.rpd) + + + Check apk running status - - CheckHardwareVersions - Check FPGA version - - - - - - SynchronousHardwareVersion - Sync FPGA version - - - - Check Screen untile fpga update finished - Watch the progress of screen upgrade until the upgrade is finished - - - + + OpenAdb Open ADB debugging function - + indentity voucher (*.ic) indentity voucher (*.ic) - - - - - + + + + + InvokeTaxiAppFunction Binding certificate - - Json format is error! - - - - - + + AliIotSetting - - apk package (*.apk *.zip) - - - - + Software Version Info - + Package - + Version - - - UpgradeSoftware - Upgrade firmware - - - - This screen is encrypted,Please decrypt and upgrade APK! - This screen is encrypted,Please decrypt and upgrade APK! - - - - + + Package name is null - + Clearing Program - - - - + + + + Timeout Timeout - - - - + + + + Failed - + Getting Log - - - - - - - - - + + + + + + + + + + + Error Error - + + Setting Timing Reboot + + + + + Set Timing Reboot + + + + + Getting Timing Reboot + + + + + Get Timing Reboot + + + + + totalResolution + FPGA total resoltuion + + + + strCurDisplayResolution + Cur display resolution + + + + File not exist + + + + + Uploading + + + + + + Set Display Mode + + + + + + Get Display Mode + + + + + + Set Screen Offset + + + + + + Get Screen Offset + + + + Open file Failed Open file Failed - + Setting Wallpaper - - + + Set Wallpaper - + System Updating - - + + System Update - + + Getting MCU Version + + + + + + MCU Version + + + + Select File Select File - + Setting player background - - + + Set player background - + Clearing player background - - - - - - - - + + + + + + + + Clear player background - + Setting Baud Rate - + Set Baud Rate - + Getting Baud Rate - + Get Baud Rate - + + Text is empty + + + + + Json Parse Error + + + + + Json isn't an Object + + + + + Setting card work mode ... + + + + + Set card work mode + + + + + Getting card work mode ... + + + + + Get card work mode + + + + + Resolution Config + + + + + Full screen + + + + + Part + + + + + Display Mode + + + + + Screen Position + + + + + Offset + + + + Hidden Settings - + Click right button to hide - + + + Update MCU + + + + + Get MCU Version + + + + Baud Config - + Model - + Uart - + Baud - + + + + + + Get - - - - + + Timing Reboot + + + + + Protocol + + + + + Server + + + + + Client + + + + + SetScreenRotation Set screen rotation - + + SetMinBrightness Set min brightness value - + + SetMaxBrightness Set maximum brightness value - + + GetMinBrightness Get min brightness - + + GetMaxBrightness Get maximum brightness - + + + Card work mode + + + + + SetSpecialResolution Set Special Resolution - + + GetSpecialResolution Get Special Resolution - + + CleanDisplayScreenSize Restore to default relolution - + + SetHighForBusy Set level for busy - + + GetStateForBusy Get level of busy - - install start... - Start installation... - - - + InputAliasTip Please input alias - - + + SetCardAlias Set alias - - Uploadding - Uploading - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tip Tip - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NoSelectedController Please select screen first - + InputWidthTip Please enter the correct width pixel value - + InputHeightTip Please enter the correct height pixel value - + Password is error Password is error - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse json error! - CtrlBrightPanel - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + Tip Tip - - - - - - - - - - - + + + + + + + + + + + NoSelectedController Please select screen first - - + + SetBrightnessSensitivity Set brightness sensitivity - - + + GetBrightnessSensitivity Get brightness sensitivity - - + + SetMinBrightness Set min brightness value - - + + GetMinBrightness Get min brightness - - + + NeedSelectSensorTypeTip Please select sensor type first - + Open file dialog - + Not found current worksheet - - + + SensorBrightnessTable Set sensor brightness table - + GetSensorBrightnessTable Get sensor bright table - + no sensorBrightnessTable no sensor brightnessTable in controller - + Save file Save file - - + + GetCurrentSensorBrightness Get Current Brightness - - + + SetBrightness Set brightness - + GetBrightness Get brightness - + Brightness Screen Brightness - - + + BrightnessSchedule (*.bjs) - + Import File - + Save File Save file - + BrightnessValue Brightness Value - + Start Time Start Time - + End Time End Time - - + + SetAutoBrightnessTask Send brightness schedule table - + GetAutoBrightnessTask Get brightness schedule - - - - + + Error Error - + Brightness Configuration Brightness configuration - + Auto Auto - + Manual Manual - + Schedule Schedule - + + Adapt to Old Devices + + + + BrightTip1 If the maximum brightness is 64, the minimum brightness can be configured as 1% or appropriate value; if the maximum brightness is 255, the minimum brightness must be configured as 36% or above, otherwise the brightness will be low. - + BrightTip2 When uploading the file, please confirm to select the correct sensor type, otherwise it will be invalid! - + Sensitivity Sensitivity - + Minbrightness Minimum Brightness - - - + + + Set Set - + Upload Upload file - - - - + + + + Readback Readback - + ReadbackTable Readback - + Refresh Refresh - + Cur Brigntness Cur Brigntness - + Brightness value Brightness value - + Default brightness Default brightness - + Add Add - + Clear Clear - + Delete Delete - + Import Import - + Export Export - + Apply Apply - + Default brightness tip - Tip: within the setting time is the setting brightness, and outside the setting time is the default brightness. For example, set the default brightness to 80, set the brightness to 180, and the time range to 8:00-17:00, then the brightness in the time range is 180, and the default brightness in other times is 80! + Tip: within the setting time is the setting brightness, and outside the setting time is the default brightness. For example, set the default brightness to 50%, set the brightness to 80%, and the time range to 8:00-17:00, then the brightness in the time range is 80%, and the default brightness in other times is 50% + + + + CtrlHdmiPanel + + + HDMI Configuration + Video source configuration + + + + Manual + Manual + + + + Schedule + Schedule + + + + + + + Tip + Tip + + + + + + + NoSelectedController + Please select screen first + + + + + SyncSwitch + Switch video source from HDMI-IN port + + + + + AnSyncSwitch + Switch video source from Async box + + + + IsSync + Readback video source + + + + Import File + + + + + Save File + Save file + + + + + Sync Schedule + + + + + + SetTimingHdmiInTask + Set video source form HDMI-IN schedule task + + + + GetTimingHdmiInTask + Get video source form HDMI-IN schedule task + + + + + Async + Async + + + + + Readback + Readback + + + + Start Time + Start Time + + + + End Time + End Time + + + + SUN + SUN + + + + MON + MON + + + + TUE + TUE + + + + WED + WED + + + + THU + THU + + + + FRI + FRI + + + + SAT + SAT + + + + Add + Add + + + + + Apply + Apply + + + + Clear + Clear + + + + Delete + Delete + + + + Import + Import + + + + Export + Export + + + + By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period + By default, asynchronous content is played, and synchronous hdmi-in port input content is played in a fixed time period + + + + CtrlNetworkPanel + + + Wire Enther(RJ45) Configuration + Wire Enther(RJ45) Configuration + + + + DHCP + + + + + Specify IP + Specify IP + + + + IP Address + IP Address + + + + Gateway + Gateway + + + + DNS Address + DNS Address + + + + + + Set + Set + + + + + + + Readback + Readback + + + + WIFI Configuration + WiFi Configuration + + + + WiFi Mode + WiFi Mode + + + + Cellular Config + Cellular Config + + + + Enable Cellular Data + Enable Cellular Data + + + + Get cellular network status information + Get cellular network status information + + + + Through the check status button + Through the "check status" button, you can automatically match the country code MCC, and then select "operator" to get the corresponding APN information. + + + + Country ID(mcc): + Country ID(mcc): + + + + + Carrier Name + Carrier Name + + + + APN(Required) + APN(Required) + + + + Flight Mode + Flight Mode + + + + WiFi name + WiFi name + + + + + + Password + Password + + + + + Input password + Input password + + + + Scan + Scan + + + + Ap Mode + AP + + + + OFF + OFF + + + + ON + ON + + + + AP name + AP name + + + + Subnet mask + Subnet mask + + + + Input ap name + Input AP name + + + + + + + + + + + + + + + Tip + Tip + + + + + + + + + + + + + + NoSelectedController + Please select screen first + + + + + SetEthernet + Set wire nether + + + + + + + + + + + Attention + Attention + + + + Please input IP address! + Please input IP address! + + + + Your IP Address is Invalid! + IP Address is invalid! + + + + Please input Mask address! + Please input Mask address! + + + + Your Mask Address is Invalid! + Mask Address is Invalid! + + + + Please input Gateway address! + Please input Gateway address! + + + + Your Gateway Address is Invalid! + Gateway Address is Invalid! + + + + Please input DNS address! + Please input DNS address! + + + + Your DNS Address is Invalid! + DNS Address is Invalid! + + + + + GetEthernet + Get wire ethernet + + + + DHCP IP + DHCP IP + + + + STATIC IP + STATIC IP + + + + + ConfigurationWiFi + Configuration WiFi + + + + + IsPortableHotSpot + Get AP or WiFi + + + + GetWifiList + Scan WiFi list + + + + + ConfigurationHotSpot + Configuration AP HotSpot + + + + success + success + + + + WifiName + WifiName + + + + ApName + Ap Name + + + + + GetCurrentAPN + Get Current Apn + + + + GetSIMStatus + Get SIM Status + + + + + SetAPN + Set APN + + + + 状态: + Status: + + + + 未知 + unknown + + + + 锁定状态,需要用户的PIN码解锁 + Lock status, need user's pin code to unlock + + + + 锁定状态,需要用户的PUK码解锁 + In the locked state, the PUK code of the user is required to be unlocked + + + + 锁定状态,需要网络的PIN码解锁 + In the locked state, the PIN code of the user is required to be unlocked + + + + 就绪 + be ready + + + + no checked sim card + no checked sim card + + + + 国家码: + MCC: + + + + 号码: + number: + + + + 用户: + User name: + + + + 信号: + Signal: + + + + 信号正常 + Signal OK + + + + 不在服务区 + Not in service area + + + + 仅限紧急呼叫 + Emergency call only + + + + 射频已经关闭 + RF off + + + + 网络: + Network type: + + + + 网络类型未知 + unKnown + + + + GPRS网络 + GPRS + + + + EDGE网络 + EDGE + + + + UMTS网络 + UMTS + + + + CDMA网络,IS95A 或 IS95B. + CDM + + + + EVDO网络, revision 0. + EVDO,revision 0. + + + + EVDO网络, revision A. + EVDO,revision A. + + + + 1xRTT网络 + 1xRTT + + + + HSDPA网络 + HSDPA + + + + HSUPA网络 + HSUPA + + + + HSPA网络 + HSPA + + + + 漫游: + roam: + + + + Yes + Yes + + + + No + No + + + + 数据连接状态: + Data connection status: + + + + 断开 + OFF + + + + 正在连接 + connecting + + + + 已连接 + Connected + + + + 暂停 + suspend + + + + 数据活动休眠状态: + Data active sleep state: + + + + 活动,但无数据发送和接收 + Active, but no data sent and received + + + + 活动,正在接收数据 + Activity, receiving data + + + + 活动,正在发送数据 + Activity, sending data + + + + 活动,正在接收和发送数据 + Activity, receiving and sending data + + + + 休眠状态 + Sleep state + + + + 信号强度: + Signal strength: + + + + Set APN Info + + + + + User + + + + + Type + + + + + Server + + + + + Port + + + + + Proxy + + + + + MMS Port + + + + + MMS Proxy + + + + + + SetSwitchSimData + SetSwitchSimData + + + + + ContrFlightMode + Set flight mode + + + + + GetFlightModeState + Readback flight mode state + + + + CtrlPwdPanel + + + Set Password + Set Password + + + + Original password + Original password + + + + original password + original password + + + + + New password + New password + + + + Repeat new password + Repeat new password + + + + + + + Set encryption + Set encryption + + + + Cancel encryption + Cancel encryption + + + + Enter again + Enter again + + + + + + + + + + + + Tip + Tip + + + + + NoSelectedController + Please select screen first + + + + + InputOriginalPasswordTip + Please input original password + + + + InputNewPasswordTip + Please input new password + + + + InputRepeatPasswordTip + Please input repeat password + + + + InputRepeatPasswordNotSameTip + The two passwords are inconsistent + + + + Tip Info + Tip Info + + + + After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? + After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? + + + + + + + SetControllerPassword + Set password + + + + + Error + Error + + + + + Success + Success + + + + + + Modify password + Modify password + + + + + + + OriginalPasswordErrorTip + The original password is wrong + + + + CtrlVerifyClockPanel + + + Verify Clock Configuration + Verify clock configuration + + + + + Verify to Computer time + Verify to Computer time + + + + Cur time of controller + Cur time of controller + + + + + LAN + LAN + + + + + + + + + + + + + + Tip + Tip + + + + + + + + + + + + + + NoSelectedController + Please select screen first + + + + screenSwitch + Switch Screen + + + + + + YES + On + + + + + + NO + Close + + + + volume + Volume + + + + brightness + brightnenss + + + + + identificationCode + Identification Code + + + + + delaySync + Time offset + + + + + msec + msec + + + + + + + OtherSyncItem + Other sync items + + + + + + + lastSynchronousTime + Last Synchronous Time + + + + checkNtpTime + Synchronization interval + + + + Lora identity + Lora identity + + + + (min/time) + (min/time) + + + + identification code + identification code + + + + Time offset(msec) + Time offset(msec) + + + + Brightness + Screen Brightness + + + + Volume + Volume + + + + Screen on/off + Screen On/Off + + + + + Slave + Slave + + + + NTP Server + NTP Server + + + + + NTP Server address + NTP Server address + + + + TimeZone + Time zone + + + + + + + + Set + Set + + + + Language: + Language: + + + + Enable Synchronous playing + Enable Synchronous playing + + + + + Sync time interval + Sync time interval + + + + + + + + Readback + Readback + + + + + Master + Master + + + + Identification Code + Identification Code + + + + + SetNtpServer + SetNtpServer + + + + + MasterSwitch + Set as master device + + + + + SlaveSwitch + Set as slave device + + + + IsMasterSlave + Read back the identity of master and slave + + + + + GetControllerDate + Get date time + + + + + SetingSyncMethod + Set sync method + + + + + SyncTime + SyncTime + + + + + GetNtpServer + GetNtpServer + + + + + GetingSyncMethod + Geting Sync Method + + + + + SetTimezone + Set Timezone Def - - - + Connection Timeout - - - - - - - + + + + + Device replied - - + + + Success Success - - - - Error - Error - - - - Tip Info - Tip Info - - - - + Fail Fail @@ -3453,666 +3333,314 @@ DeviceCtrlPanel - - - + + + + Current Screen Current screen - - + + none none - - + + Clear Clear - - - single screen operation - single screen operation - - - + + Multi screen operation Multi screen operation - + + selected num Selected number - + Brightness Adjustment Brightness Adj. - + Power Control Power Control - + Net Config Network Config - - Time Synchronization + + Time Sync Time Sync - + Video source Video Source - - Encrypt - Encrypt + + Password + Password - - Advanced parameters + + Advanced Advanced - - Current Screen: - - - - + Test Test - - Volume Adjustment - Volume Adj. + + Volume Adj. + Volume DeviceItem - + GetScreenDetailInfo Get more detail info - + ReadbackPic Screenshot - + Input password Input password - + GetScreenshotFull readback screenshot - + cur brightness: Current Brightness: - + android version: Android Version: - + IMEI: - + HardWard Version: FPGA Version: - + MAX Brightness level: Brightness Level: - + Android OS Resolution: Android OS Resolution: - + Firmware Version: Firmware Version: - + Player Version: Player firmware version: - + Detail Info Detail Info - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + receive Receive - - SetScreenOn - Set power - - - + AliIotSetting - - + + GetScreenStatus GetScreenStatus - - + + Status Status - + Tip Info Tip Info - + password is wrong password is wrong - + GetBrightness Get brightness - - - + brightness brightnenss - - MasterSlaveSwitch - Configure master slave identity - - - - SetBrightness - Set brightness - - - - - SetMinBrightness - Set min brightness value - - - - GetBrightnessSensitivity - Get brightness sensitivity - - - - sensitivity - sensitivity - - - - GetMinBrightness - Get min brightness - - - - SetSensorBrightnessTable - SetSensorBrightnessTable - - - - SetSwitchWiFi - Set WiFi on/off - - - - ConfigurationWiFi - Configuration WiFi - - - - ConfigurationHotSpot - Configuration AP HotSpot - - - - GetSwitchWiFi - GetSwitchWiFi - - - + SetAutoBrightnessTask Send brightness schedule table - + SetAutoVolumeTask Set volume schedule - + SetVolume Set Volume - + GetVolume Get Volume - + SetTimingScreenTask Set schedule task of screen power - - GetControllerDate - Get date time - - - - SetHighForBusy - Set level for busy - - - - - GetStateForBusy - Get level of busy - - - - Service:Low Out of service:High - Service:Low Out of service:High - - - - Service:High Out of service:Low - Service:High Out of service:Low - - - - - - IsPortableHotSpot - Get AP or WiFi - - - - WifiName - WifiName - - - - ApName - Ap Name - - - + TestScreen Test screen - + SetOnlineAddr Set Web server address - + SetRealtimeServer Set realtimer address - - GetOnlineAddr - Get web server address - - - - GetRealtimeServer - Get realtime server address - - - - SetNtpServer - SetNtpServer - - - - GetNtpServer - GetNtpServer - - - - SyncTime - SyncTime - - - - DelPrograms - Clear program - - - - SetingSyncMethod - Set sync method - - - + GetCurrentSensorBrightness Get Current Brightness - + Cur brightness Cur brightness - - SetSpecialResolution - Set Special Resolution - - - - GetSpecialResolution - Get Special Resolution - - - - totalResolution - FPGA total resoltuion - - - - strCurDisplayResolution - Cur display resolution - - - - CleanDisplayScreenSize - Restore to default relolution - - - - SetMaxBrightness - Set maximum brightness value - - - - GetMaxBrightness - Get maximum brightness - - - - screenSwitch - Switch Screen - - - - - - YES - On - - - - - - NO - Close - - - - LAN - LAN - - - + Connect Connect - + timeout timeout - + Anycast Anycast - - + volume Volume - - - - - - - GetingSyncMethod - Geting Sync Method - - - - - identificationCode - Identification Code - - - - - delaySync - Time offset - - - - - msec - msec - - - - - - - OtherSyncItem - Other sync items - - - - - - - lastSynchronousTime - Last Synchronous Time - - - - checkNtpTime - Synchronization interval - - - - Uploadding - Uploadding - - - + Success Success - + failed failed - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + success success - - - Lora identity - Lora identity - - - - Master - Master - - - - Slave - Slave - - - - SetBrightnessSensitivity - Set brightness sensitivity - - - - - + + + on ON - - - + + + off OFF @@ -4121,116 +3649,116 @@ DevicePanel - + All ALL ALL - + Online Online Online - - + + Refresh Refresh Refresh - - - + + + Specify IP Specify IP Specify IP - + Current Screen Current screen - + none none - + Specify IP list - + Search Search - - + + Attention Attention - - + + Please input IP address! Please input IP address! - + Cancel Cancel - + Screen ID Screen ID - + Screen IP Screen IP - + Screen Size Screen Size - + Remark Name Alias - + readback pic Screenshot - + send send - + More Info More Info - + Cur Brightness Screen Current Brightness - + Power Status Power Status - + Security encryption @@ -4407,39 +3935,156 @@ - EAudio + EAClock - + Basic Properties Basic properties - - File - File + + Time Zone + Time Zone - + + Custom Dial + Custom Dial + + + + Select + Select + + + + Select Dail file + Select dial file + + + + Hour Mark + Hour Scale + + + + + Circular + Circle + + + + + Rectangle + Rectangle + + + + Number + Number + + + + + + T + + + + + Min Mark + Minute Scale + + + + Color + + + + + Length + + + + + Width + Width + + + + Hour Hand + + + + + Min Hand + + + + + Sec Hand + + + + + Show + + + + + Text + Text + + + Play Properties - + Play Duration Play Duration - + + s + s + + + + EAudio + + + Basic Properties + Basic properties + + + + File + File + + + + Play Properties + + + + + Play Duration + Play Duration + + + Select File Select File - + s s - + Audio Audio @@ -4447,233 +4092,373 @@ EBase - + Area Area(px) - + X X - + Y Y - + W W - + H H - + Border Border - - + + None None - + Effect Effect - + Rotate Rotate - + Blink Blink - + Speed Speed - + Slow Slow - + Moderate Moderate - + Fast Fast - EEnviron + EDClock - - - - - - - - north - north + + MON + MON - - - - - - - - east - east + + TUE + TUE - - - - - - - - south - south + + WED + WED - - - - - - - - west - west + + THU + THU - - - Temperature - Temperature + + FRI + FRI - - - Humidity - Humidity + + SAT + SAT - - - Noise - Noise + + SUN + SUN - - Wind Speed - Wind Speed + + + AM + AM - - Wind Direction - Wind Direction + + + PM + PM - + Basic Properties Basic properties - - Title - Title + + Time Zone + Time Zone - - Compensation - Compensation + + Year + Year - - Wind speed - Wind speed + + Month + Month - - Wind direction - Wind direction + + Day + Day - - Left - Left + + Hour + Hour - - Center - Center + + Min. + Min. - - Right - Right + + Sec. + Sec. - - Single scroll - Single scroll + + Weekly + Day of Week - - Speed - Speed + + Full Year + 4-Digit Year - - ms/pixel - ms/pixel + + 12-Hour + 12-Hour - - Back Color - Back Color + + Date Style + Date Format - + + Time Style + Time format + + + + Display Style + Display style + + + + Multiline + Multiline + + + Play Properties - - Refresh Cycle - Refresh cycle - - - - min. - min. - - - + Play Duration Play Duration - + + s + s + + + + EEnviron + + + + + + + + + north + north + + + + + + + + + + east + east + + + + + + + + + + south + south + + + + + + + + + + west + west + + + + + Temperature + Temperature + + + + + Humidity + Humidity + + + + + Noise + Noise + + + + Wind Speed + Wind Speed + + + + Wind Direction + Wind Direction + + + + Basic Properties + Basic properties + + + + Title + Title + + + + Compensation + Compensation + + + + Wind speed + Wind speed + + + + Wind direction + Wind direction + + + + Left + Left + + + + Center + Center + + + + Right + Right + + + + Single scroll + Single scroll + + + + Speed + Speed + + + + ms/pixel + ms/pixel + + + + Back Color + Back Color + + + + Play Properties + + + + + Refresh Cycle + Refresh cycle + + + + min. + min. + + + + Play Duration + Play Duration + + + s s @@ -4681,37 +4466,37 @@ EGif - + Basic Properties Basic properties - + File File - + Select File Select File - + Play Properties - + Play Duration Play Duration - + s s - + Play Times Play Times @@ -4719,73 +4504,73 @@ EMultiWin - + Please add media on the right Please add media on the right. You can add multiple different media. The LED display will play in the order of the list - + Media List Media List - - - + + + Text Text - - - + + + Photo Photo - - - + + + Video Video - - - + + + Gif Gif - - - + + + DClock Clock - - - + + + AClock Analog Clock - - - + + + Select File Select File - - + + Environment Environmental Monitoring - - + + Timer Timer @@ -4793,118 +4578,118 @@ EPhoto - + Basic Properties Basic properties - + File File - + Select File Select File - + Image Read Error Image Read Error - + Play Properties - + Play Duration Play Duration - - + + s s - + Enter Style Entrance Effect - + None None - + Alpha_In ALPHA_IN - + Moving to left MOVING_TO_LEFT - + Moving to right MOVE_TO_RIGHT - + Moving to top MOVING_TO_TOP - + Move to bottom MOVE_TO_BOTTOM - + Zoom in ZOOM_IN - + Zoom in to left_bottom ZOOM_IN_LEFT_BOTTOM - + Zoom in to left_top ZOOM_IN_LEFT_TOP - + Zoom in to right_top ZOOM_IN_RIGHT_TOP - + Zoom in to right bottom ZOOM_IN_RIGHT_BOTTOM - + Rotate to right ROTATE_TO_RIGHT - + Rotate to left ROTATE_TO_LEFT - + Enter Duration Effect Duration - + Images (*.png *.jpg *.jpeg *.bmp) @@ -4912,191 +4697,191 @@ EText - + Enter your text Enter your text - + Basic Properties Basic properties - - Font Color - Font Color - - - + Back Color Back Color - + Kerning Kerning - + Line Spacing Line Spacing - + PageCount: PageCount: - + page Page - + Import txt File - + Select File Select File - + Fail Fail - + File Open Fail - + Play Properties - + Flip Flip - + Scroll Scroll - + Static Static - - - + + + Play Duration Play Duration - + Duration/Page Duration/Page - + Effect time effect duration - - + + Tip Info Tip Info - - + + Effect time cannot be longer than duration time Effect time cannot be longer than duration time - + s s - + + Text Color + + + + + Colorful Text + + + + Entrance Effect Entrance Effect - + no no - + random random - + right to left right to left - + bottom to top bottom to top - + left to right left to right - + top to bottom top to bottom - - Head-Tail Connected - Head to Tail - - - + Head-Tail Spacing Spacing - + Scroll Style Direction - + Right -> Left From right to left - + Bottom -> Top From bottom to top - + Left -> Right From left to right - + Top -> Bottom Frome top to bottom - + Scroll Speed Scrolling speed @@ -5104,87 +4889,87 @@ ETimer - + day Days - + hour Hours - + min Mins - + sec Secs - + Basic Properties Basic properties - + Count Down Count Down - + Count Up Count Up - + Time Target Time - + Day Day - + Hour Hour - + Min Min - + Sec Sec - + Multiline Multiline - + Text Text - + Play Properties - + Play Duration Play Duration - + s s @@ -5192,64 +4977,64 @@ EVideo - + Basic Properties Basic properties - + File File - + Play Properties - + Play Duration Play Duration - + Select File Select File - + s s - + Play Times Play Times - + Video Transcoding - - + + Video Transcoding Progress - - + + Error Error - + Video Video - + Flash Flash @@ -5257,17 +5042,17 @@ EWeb - + Basic Properties Basic properties - + Play Duration Play Duration - + s s @@ -5295,10 +5080,93 @@ Secs + + GenTmpThread + + + Preparing ... + Preparing ... + + + + MON + MON + + + + TUE + TUE + + + + WED + WED + + + + THU + THU + + + + FRI + FRI + + + + SAT + SAT + + + + SUN + SUN + + + + AM + AM + + + + PM + PM + + + + day + Days + + + + hour + Hours + + + + min + Mins + + + + sec + Secs + + + + Create json ... + Create json ... + + + + Scan program ... + Scan program ... + + LoColorSelector - + Transparent Transparent @@ -5341,186 +5209,230 @@ MainWindow - + Language Language - + Help Help - - + + Check for updates Check for updates - - + + firmware manager Firmware management - - - Software Configuration - Software Configuration + + + Software Config + Software Config - - + + Info - - + + About About - - + + Setting Setting - - Device - Termianls + + Software Update + Software Update - + + CurVersion + CurVersion + + + + Update + Update + + + + LatestVersion: + LatestVersion: + + + + + Update log: + Update log: + + + + The current version is already the latest version + The current version is already the latest version + + + + Device + Terminals + + + Program Solutions - + Control Terminal Control - + GuangYinPin Lora screen - + Check card Detect - + Tip Info Tip Info - + RestoreLedCardIpByUdpTip This operation will fix all the control cards in the LAN that are not in the same network segment as the computer IP. Please be careful! + + Net + + + Connection Timeout + + + + + Error + Error + + PageEditor - + Zoom In Zoom In - + Zoom Out Zoom Out - + Original size Origianl Size - + Delete the secect media Delete the seleted media - + Clear all media Clear all media - + Move layer up Move layer up(shortcut key PgUp) - + Send backward Send backward(shortcut key PgDn) - + Bring to front Bring to front(shortcut key home) - + Move to the bottom layer Move to the bottom layer(shortcut key end) - + Fill the entire screen Fill the entire screen - + Fill the screen horizontally Fill the screen horizontally - + Fill the screen vertically Fill the screen vertically - + Align top Align up - + Center vertically Center vertically - + Bottom align Bottom up - + Align left Align left - + Center horizontally Center horizontally - + Align right Align right - + Tip Info Tip Info - + Clear all medias? @@ -5528,79 +5440,84 @@ PageListItem - + times Times - + Page name Program name - + New New - + Play times Play times - + + Sources Repeat + + + + Audios - + Total Dur - - + + s s - + Select File Select File - + Duration - + Vol - + Valid Date Valid date - - + + Warning Warning - + Start Time can't be later than End Time - + End Time can't be earlier than Start Time - + Plan Plan @@ -5629,17 +5546,17 @@ PlayWin - + Move to Top Left Move to Top Left - + Set Position - + Close Close @@ -5647,12 +5564,12 @@ PlayerBackSendThread - + Open file failed Open file failed - + Read file failed Read file failed @@ -5673,47 +5590,47 @@ ProgCreateDlg - + Resolution Resolution - + Solution Information Solution Information - + Solution Name Solution Name - + Width Width - + Height Height - + Remarks Remarks - - 节目超宽需要打折, 请输入打折宽度 - + + 每段打折宽度 (用空格分隔) + Each part width (split with space) - + OK Ok - + Cancel Cancel @@ -5721,221 +5638,200 @@ ProgEditorWin - + Save Save - - + + Save as Save as - + Setting Setting - + Text Text - + Photo Photo - + Video Video - + Gif Gif - + Clock Clock - + Analog Clock Analog Clock - + Environment Environmental Monitoring - + Web Web page - + MuliContentWindow Multi material window - + In this window, a plurality of different program materials can be added and played according to the order of joining the list; In this window, a plurality of different program materials can be added and played according to the order of joining the list - + Timer Timer - + Play - + Stop Stop - + Publish Publish - - - - + + + + Select File Select File - + program Program - + Add page Add page - + Copy page Copy page - + Delete page Delete page - - + + Tip Info Tip Info - + Are you sure you want to delete this program page? Are you sure you want to delete this program page? - + Move up Move up - + Move down Move down - + widget properties Widget properties - + Page properties Program properties - + Do you want to save the modifications? Do you want to save the modifications? - - + + Saving... Saving... - - + + Success Success - - + Save failed Save failed - + Convertering Convertering - - Converter Successed - Converter Successed - - - - Converter TimeOut - Converter TimeOut - - - + Generate preview data Generate preview data - - Ready - Ready - - - - Generate TimeOut - Generate TimeOut - - - - + + Error Error - + Rename fail when saving - + Remove Recursively fail when saving - + Warning Warning @@ -5943,155 +5839,177 @@ ProgItem - - + + ExportButtonTip USB playback - - + + SendButtonTip Publish - - + + Convertering Convertering - - - USB Export Successed - USB disk exported successfully - - - - USB Export TimeOut - USB disk export failed - - - - Converter Successed - Converter Successed - - - - Converter TimeOut - Converter TimeOut - ProgPanel - - + + New New - - + + Edit Edit - - + + Delete Delete - - + + + Import Import - - + + + Export Export - - + + Send Send - - + + Publish Publish - - + + Name Name - - + + + Choose Directory + Choose Directory + + + + Tip + Tip + + + + The imported directory is already in the working directory, so there is no need to import it again! + The imported directory is already in the working directory, so there is no need to import it again! + + + + :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? + :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? + + + + Play - - + + Stop Stop - - + + Resolution Resolution - - + + File Size File Size - - + + Last Modify Last Modified - - + + Usb playback USB playback - + Program name conflicted Program name conflicted - + Warning Warning - + You will delete the selected solution(s),are you sure? You will delete the selected solution(s),are you sure? - + + Tip Info Tip Info + + ProgPortDlg + + + Solution Name + Solution Name + + + + Progress + Progress + + + + Done + Done + + QObject - + Setting up the LedOK Express... Setting up the LedOK Express... @@ -6099,18 +6017,18 @@ SendProgThread - - + + Program is empty Program is empty - + Open file failed Open file failed - + Read file failed Read file failed @@ -6118,73 +6036,73 @@ SendProgramDialog - - + + Publish Publish - + success info - + Refresh Refresh - + Cancel Cancel - + Screen ID Screen ID - + Remark Name Alias - + Online Online - + Screen IP Screen IP - + Screen Size Screen Size - + Security encryption - + Progress Progress - + Remarks Remarks - + This screen is encrypted This screen is encrypted - + All ALL @@ -6192,12 +6110,12 @@ SoftConfigDialog - - Software Configuration - Software Configuration + + Software Config + Software Config - + Video compress to Video compress to @@ -6207,200 +6125,31 @@ Video transcoding to - + Text antialiasing Text antialiasing - + TextAntilaTip (Note: this option is suitable for screens with small spacing and large size. If this option is selected, the shadow on the edge of the text will be smooth; it is not recommended for small size screens and single and double color screens.) - + GuangYinPin Lora screen - + + Width Split + + + + OK Ok - - SpecialDlg - - Specify IP - Specify IP - - - Search - Search - - - Cancel - Cancel - - - Attention - Attention - - - Please input IP address! - Please input IP address! - - - Your IP Address is Invalid! - IP Address is invalid! - - - Error - Error - - - - ThreadUpgradeApk - - - Uploadding - Uploadding - - - - TipDialog - - - TextLabel - - - - - - OK - Ok - - - - - Cancel - Cancel - - - - X - - - - - - Import - Import - - - - - Path - Path - - - - - : - - - - - - browse - Browse - - - - You will delete the selected solution(s),are you sure? - You will delete the selected solution(s), are you sure? - - - - - Export - Export - - - - - Done - Done - - - - - Solution Name - Solution Name - - - - - Progress - Progress - - - - Delete - Delete - - - - Select the network to connect to the device - Please select the network to connect to the LED controller - - - - Network name - Network name - - - - - This operation will only set cable network to static IP,are you sure? - This operation will only set cable network to static IP,are you sure? - - - - Do you want set IP of cable network to DHCP - Do you want set the network to automatically get IP through DHCP - - - - - - - - Tip - Tip - - - - - - Please select the network to connect to the Led controller - Please select the network to connect to the LED controller - - - - Choose Directory - Choose Directory - - - - The imported directory is already in the working directory, so there is no need to import it again! - The imported directory is already in the working directory, so there is no need to import it again! - - - - no find program can be imported - no find program can be imported - - UpdateLedset3Dialog @@ -6473,262 +6222,315 @@ Congratulations! You are running the latest version of %1 - - UpdaterDialog - - - Software Update - Software Update - - - - X - X - - - - V1.0 - - - - - Update - Update - - - - CurVersion - CurVersion - - - - LatestVersion: - LatestVersion: - - - - - Update log: - Update log: - - - - The current version is already the latest version - The current version is already the latest version - - UpgradeApkDialog - - - Upgrade apk - Upgrade apk + + Update APK + Update APK - - 口 - - - - - X - X - - - - + Select apk Select apk - - - - + Upgrade Upgrade - - - APK: - - - - - + Uninstall Uninstall - - + check running state check running state - - + Select Fpga Select Fpga - - - success info + + Installing - - + Refresh Refresh - - + Cancel Cancel - + Screen ID Screen ID - + Remark Name Alias - + Online Online - + Screen IP Screen IP - + Security encryption - + Progress Progress - + xixunplayer - + cardsystem - + taxiapp - + starter - + connection - + displayer - + FPGA FPGA - + update - + State State - - - + + All ALL - + + This screen is encrypted + This screen is encrypted + + + + + Select Online APK + + + + + No Files + + + + + Name + Name + + + + Size + + + + + Create Time + + + + + + + Tip + Tip + + + + Is upgrading now. Please wait + + + + + NoSelectedController + Please select screen first + + + + + Downloading Online File + + + + + + Error + Error + + + + Online file is empty + + + + + Uploading + + + + + Upload error + + + + + Install error + + + + + Install success + + + + + Reminder + + + + + Reminder: Uninstalling this program may cause the device to offline, cannot be found, lost configs and have a black screen. Please uninstall with caution! + + + + + Do you want to continue? + + + + + Uninstalling + Uninstalling + + + + Uninstall error + + + + + Uninstall success + + + + + Check apk running status + + + + + Check error + + + + + Running + Running + + + + Not running + + + + The encrypted control card can be upgraded directly The encrypted control card can be upgraded directly - - - apk package (*.rpd) - - - - - apk package (*.apk *.zip) - - UsbDetectDialog - + Usb upgrade program Usb upgrade program - + Password Password - + OK Ok - + Input password Input password - - + + Tip Tip - + No checked USB device No checked USB device - + please select usb device in list please select usb device in list - + Cancel Cancel @@ -6736,7 +6538,7 @@ WaitingDlg - + Success Success @@ -6765,331 +6567,6 @@ Cancel - - eAClock - - - Basic Properties - Basic properties - - - - Time Zone - Time Zone - - - - Custom Dial - Custom Dial - - - - Select - Select - - - - Select Dail file - Select dial file - - - - Hour Mark - Hour Scale - - - - - Circular - Circle - - - - - Rectangle - Rectangle - - - - Number - Number - - - - - - T - - - - - Min Mark - Minute Scale - - - - Hand Color - Hand Color - - - - H - H - - - - M - M - - - - S - - - - - Text - Text - - - - Play Properties - - - - - Play Duration - Play Duration - - - - s - s - - - - eDClock - - - MON - MON - - - - TUE - TUE - - - - WED - WED - - - - THU - THU - - - - FRI - FRI - - - - SAT - SAT - - - - SUN - SUN - - - - - AM - AM - - - - - PM - PM - - - - Basic Properties - Basic properties - - - - Time Zone - Time Zone - - - - Year - Year - - - - Month - Month - - - - Day - Day - - - - Hour - Hour - - - - Min. - Min. - - - - Sec. - Sec. - - - - Weekly - Day of Week - - - - Full Year - 4-Digit Year - - - - 12-Hour - 12-Hour - - - - Date Style - Date Format - - - - Time Style - Time format - - - - Display Style - Display style - - - - Multiline - Multiline - - - - Play Properties - - - - - Play Duration - Play Duration - - - - s - s - - - - GenTmpThread - - - Preparing ... - Preparing ... - - - - MON - MON - - - - TUE - TUE - - - - WED - WED - - - - THU - THU - - - - FRI - FRI - - - - SAT - SAT - - - - SUN - SUN - - - - AM - AM - - - - PM - PM - - - - day - Days - - - - hour - Hours - - - - min - Mins - - - - sec - Secs - - - - Create json ... - Create json ... - - - - Scan program ... - Scan program ... - - mGuangYingPinWidget @@ -7494,68 +6971,55 @@ OpenPort COM failed - - wExportProgramItem - - - Tip Info - Tip Info - - - - :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? - :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? - - wPlanItem - + Form Form - + 1 1 - + Every week: Every week: - + M M - + Tu Tu - + W W - + Th Th - + F F - + Sa Sa - + Su Su @@ -7563,30 +7027,30 @@ wProgramPublishItem - + Input password Input password - - - + + + Error Error - - + + Tip Info Tip Info - + Fail Fail - + password is wrong password is wrong @@ -7594,92 +7058,24 @@ wUpgradeApkItem - + Input password Input password - - uninstalling - Uninstalling + + Error + Error - - - IsSoftwareRunning - Check apk running status - - - - - This screen is encrypted - This screen is encrypted - - - - - Start upgrading - Start upgrade - - - - - Timeout - Timeout - - - - install start... - Start installation... - - - - - SynchronousHardwareVersion - Sync FPGA - - - + Tip Info Tip Info - + password is wrong password is wrong - - - - UninstallSoftware - Uninstall - - - - - Success - Success - - - - Running - Running - - - - NoRunning - Not running - - - - install success - Install success - - - - - Fail - Fail - diff --git a/LedOK/translations/app_ja.ts b/LedOK/translations/app_ja.ts index adc3371..2efe21e 100644 --- a/LedOK/translations/app_ja.ts +++ b/LedOK/translations/app_ja.ts @@ -71,1339 +71,202 @@ パスワードが正常に変更 - - ControlEncryptWidget - - - Form - リフレッシュ - - - - - Entrypt Configuration - セキュリティ設定 - - - - Original password - 元のパスワード - - - - - - original password - 元のパスワード - - - - - - New password - 新しいパスワード - - - - - Repeat new password - 繰り返し入力 - - - - - - - Set encryption - 暗号化 - - - - - Cancel encryption - 暗号化を解除 - - - - - Enter password - パスワードを入力 - - - - Enter again - 再入力 - - - - - - - - - Tip - 提示 - - - - NoSelectedController - 先に大きいスクリーンを選んでください - - - - - InputOriginalPasswordTip - オリジナルのパスワードを入力してください - - - - InputNewPasswordTip - 新しいパスワードを入力してください - - - - InputRepeatPasswordTip - 新しいパスワードを繰り返して入力してください - - - - InputRepeatPasswordNotSameTip - 二回入力したパスワードが一致しません - - - - Tip Info - ヒント - - - - After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? - パスワードを設定した後、パスワードを覚えて、それを記録してください。パスワードを忘れた場合は、デバイスが動作することができなくなります。この操作を続行しますか? - - - - - SetControllerPassword - 暗号化の設定 - - - - Readback - 読み戻し - - - - - - Success - 成功 - - - - - - failed - 失敗 - - - - - Modify password - パスワードを変更 - - - - OriginalPasswordErrorTip - 元のパスワードが間違っています - - - - ControlHdmiSchedule - - - Form - リフレッシュ - - - - - Add - 追加 - - - - - Delete - 削除 - - - - - Clear - クリア - - - - - Import - インポート - - - - - Export - 出力 - - - - By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period - 非同期のコンテンツをデフォルトで再生し、同期のHMI-INポートに入力します - - - - - Apply - 適用 - - - - Readback - 読み戻し - - - - SYNC HDMI - HDMI-IN - - - - Start Time - 開始時間 - - - - End Time - 終了時間 - - - - SUN - 日曜日 - - - - MON - 月曜日 - - - - TUE - 火曜日 - - - - WED - 水曜日 - - - - THU - 木曜日 - - - - FRI - 金曜日 - - - - SAT - 土曜日 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - - On - 開く - - - - SyncSchedule (*.syncs) - - - - - Save File - 保存 - - - - Sync Schedule (*.syncs) - - - - - - Tip - 提示 - - - - - NoSelectedController - 先に大きいスクリーンを選んでください - - - - SetTimingHdmiInTask - 同期モードタイミングタスクの設定 - - - - GetTimingHdmiInTask - 同期モードタイミングタスクの取得 - - - - - Success - 成功 - - - - - failed - 失敗 - - - - ControlHdmiWidget - - - HDMI Configuration - ビデオソースの設定 - - - - Manual - 手動 - - - - Schedule - スケジュール - - - - - Tip - 提示 - - - - - NoSelectedController - 先に大きいスクリーンを選んでください - - - - - SyncSwitch - スイッチのビデオソースをHDMI-IN - - - - - AnSyncSwitch - 異ステップモードを切り替え - - - - - IsSync - 同じ非同期モードを読み返す - - - - Error - エラー - - - - HDMI IN - HDMI IN - - - - Async - アシュリン - - - - Readback - 読み戻し - - - - ControlNetConfigWidget - - - Wire Enther(RJ45) Configuration - 有線ネットワークの設定 - - - - - DHCP - - - - - - Specify IP - 指定IP - - - - - IP Address - IPアドレス - - - - Mask Address - サブネットマスク - - - - - Gateway - ゲートウェイ - - - - - DNS Address - DNSアドレス - - - - - - - - - - Set - セット - - - - - - - - - Readback - 読み戻し - - - - - WIFI Configuration - WiFiの設定 - - - - - WiFi On/Off - WiFi機能 - - - - Input Ap name - 入力AP名 - - - - - 4G/5G Configuration - セルラーデータ構成 - - - - - Open 4G/5G - セルラーデータを有効にする - - - - APN: - - - - - - Get cellular network status information - セルラーネットワーク状態情報を取得する - - - - - Check SIM can automatically match to MCC, and then select carrier get apn param,if not found carrier,you can check the CUSTOM checkbox,then enter custom param. - チェックシムは自動的にMCCに一致することができますし、キャリアー取得APNパームを選択し、キャリアが見つからない場合は、カスタムチェックボックスをチェックし、カスタムパームを入力します。 - - - - - Readback APN Info - APN情報を読み返す - - - - - Set Apn Info,Check SIM can automatically match to MCC, and then select carrier get apn param - APN情報を設定する - - - - - CUSTOM - カスタム - - - - - Check SIM - SIM情報の照会 - - - - - - -> - - - - - - Country ID(mcc): - 国号(mcc): - - - - - Carrier Name - 運営者 - - - - - APN: - キャリアAPN: - - - - - APN(Required) - APN(必ず記入) - - - - - User: - ユーザ名: - - - - - - - Not required - 必要でない - - - - - Password: - パスワード: - - - - Set Apn:iot.cargo - - - - - - Flight Mode - 飛行モード - - - - - WiFi name - WiFiの名前 - - - - - - - Password - パスワード - - - - - - - Input password - パスワードを入力 - - - - - Scan - スキャン - - - - - Ap Mode - APエネルギー - - - - Ap name - APの名前 - - - - OFF - オフ - - - - ON - オン - - - - AP name - AP名 - - - - Subnet mask - サブネットマスク - - - - Input ap name - APの名前を入力 - - - - - - - - - - - - - - - Success - 成功 - - - - - - - - - - - - - - - failed - 失敗 - - - - - - - Tip - 提示 - - - - - NoSelectedController - 先に大きいスクリーンを選んでください - - - - - SetEthernet - 有線網を設置する - - - - - - - - - - - Attention - 注意 - - - - Please input IP address! - IPアドレスを入力してください! - - - - Your IP Address is Invalid! - IPアドレスが無効です! - - - - Please input Mask address! - サブネットマスクの住所を入力してください! - - - - Your Mask Address is Invalid! - マスクアドレスが無効です! - - - - Please input Gateway address! - ゲートウェイのアドレスを入力してください! - - - - Your Gateway Address is Invalid! - ゲートウェイアドレスが無効です! - - - - Please input DNS address! - DNSアドレスを入力してください! - - - - Your DNS Address is Invalid! - DNSアドレスを入力してください! - - - - - GetEthernet - 有線ネットワークの設定を取得 - - - - DHCP IP - DHCP IP - - - - STATIC IP - 静的IP - - - - Error - エラー - - - - - - - - - SignalPower - 信号強度 - - - - - ConfigurationWiFi - WiFiの設定 - - - - IsPortableHotSpot - ホットスポットとWiFiモードの取得 - - - - GetWifiList - スキャンWiFi - - - - ConfigurationHotSpot - ホットスポットの設定 - - - - GetCurrentAPN - APN情報の取得 - - - - - GetSIMStatus - SIM状態を取得 - - - - SetAPN - APNの設定 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - 状态: - 状態: - - - - 未知 - 不明 - - - - 锁定状态,需要用户的PIN码解锁 - ロック状態は、ユーザのPINコードのロック解除が必要です - - - - 锁定状态,需要用户的PUK码解锁 - ロック状態は、ユーザのPUKコードのアンロックが必要です - - - - 锁定状态,需要网络的PIN码解锁 - ロック状態は、ユーザのPINコードのアンロックが必要です - - - - 就绪 - 準備完了 - - - - no checked sim card - simカードが検出されませんでした - - - - 国家码: - 国号: - - - - 号码: - 番号: - - - - 用户: - ユーザ: - - - - 信号: - 信号: - - - - 信号正常 - 信号が正常である - - - - 不在服务区 - サービスエリアにはいません - - - - 仅限紧急呼叫 - 緊急呼び出しのみ - - - - 射频已经关闭 - 無線周波数はすでに閉鎖されました - - - - 网络: - ネットワークタイプ: - - - - 网络类型未知 - 不明 - - - - GPRS网络 - GPRS - - - - EDGE网络 - EDGE - - - - UMTS网络 - UMTS - - - - CDMA网络,IS95A 或 IS95B. - CDM - - - - EVDO网络, revision 0. - EVDO,revision 0. - - - - EVDO网络, revision A. - EVDO,revision A. - - - - 1xRTT网络 - 1xRTT - - - - HSDPA网络 - HSDPA - - - - HSUPA网络 - HSUPA - - - - HSPA网络 - HSPA - - - - 漫游: - ローミング: - - - - Yes - - - - - No - いいえ - - - - 数据连接状态: - データ接続状態: - - - - 断开 - 切断 - - - - 正在连接 - 接続中 - - - - 已连接 - 接続済み - - - - 暂停 - 一時停止 - - - - 数据活动休眠状态: - データアクティビティの休止状態: - - - - 活动,但无数据发送和接收 - アクティブですが、データ送信と受信はありません - - - - 活动,正在接收数据 - アクティブ、データ受信中 - - - - 活动,正在发送数据 - イベント、データ送信中 - - - - 活动,正在接收和发送数据 - イベント、データ受信と送信中 - - - - 休眠状态 - スリープ状態 - - - - 信号强度: - 信号の強度: - - - - SetSwitchSimData - 4G/5Gスイッチの設定 - - - - ContrFlightMode - 飛行モードの設定 - - - - GetFlightModeState - 飛行モード状態を取得 - - - - ControlPowerManual - - - Form - リフレッシュ - - - - - POWER - パワー - - - - - - Readback - 読み戻し - - - - OFF - オフ - - - - ON - オン - - - - - Tip - 提示 - - - - - NoSelectedController - 先に大きいスクリーンを選んでください - - - - IsScreenOn - スイッチ状態を読み出します - - - - - - SetScreenOn - 電源の設定 - - - - - - - Success - 成功 - - - - - on - オン - - - - - - - failed - 失敗 - - - - - off - オフ - - - - - SetScreenOff - スクリーンスイッチの設定 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - ControlPowerSchedule - + Form リフレッシュ - + Edit area 編集エリア - - + + Add 追加 - - + + Delete 削除 - - + + Clear クリア - - + + Import インポート - - + + Export 出力 - + It is power off state outside the schedule time period 定時の時間帯にはモニターがオンになり、他の時間はオフになります - + Send command 指令エリア - - + + Apply 適用 - + Clear Schedule タイミング指令をクリア - + Readback 読み戻し - + Power On State スクリーンスイッチ状態 - + Start Time 開始時間 - + End Time 終了時間 - + SUN 日曜日 - + MON 月曜日 - + TUE 火曜日 - + WED 水曜日 - + THU 木曜日 - + FRI 金曜日 - + SAT 土曜日 - - + + DeviceItem OnProHttpResponse 解析json文件错误! - - + + On 開く - - + + PowerSchedule (*.pjs) スイッチパネルタイミング(*.pjs) - + Save File 保存 - - - + + + Tip 提示 - - - + + + NoSelectedController 先に大きいスクリーンを選んでください - - + + Tip Info ヒント - - + + Clear schedule task? スケジュールのタスクをキャンセル? - - + + CleanTimingScreenTask スケジュールのタスクをキャンセル - + SetTimingScreenTask 画面タイミングスイッチタスクの設定 - - - - + + + + Success 成功 - - - - + + + + failed 失敗 - + GetTimingScreenTask 画面タイミングスイッチタスクの取得 @@ -1411,678 +274,378 @@ ControlPowerWidget - - Form - リフレッシュ + + + Off + 閉じる - - + + + On + 開く + + + + + Tip + ヒント + + + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + + SetScreenOn + 画面の電源を入れる + + + + + SetScreenOff + 画面の電源を切る + + + + + IsScreenOn + スイッチ状態を読み出します + + + Power Configuration スイッチパネル制御 - - + Manual 手動 - - + Schedule スケジュール + + + Power + 電源 + + + + Readback + 読み戻し + ControlTestWidget - + Form リフレッシュ - - + + Test Screen テスト画面 - - + + Line test 線テスト - - - - - - - + + + + + + + Red - - - - - - - + + + + + + + Green - - - - - - - + + + + + + + Blue - - - - - - - + + + + + + + White - - + + Vertical 縦線 - - + + Slash 斜線 - - - + + + Horizontal 水平線 - - - - + + + + Speed スピード - - + + ms(>10) ミリ秒(>10) - - + + Line Distance 線の間隔 - + px px - - - - - + + + + + Test テスト - - + + Gradation test グレースケールテスト - - + + Only the gray value is displayed 色の値のみを表示 - + (>10) - - + + GrayValue グレースケール値 - + (0-255) - - + + Color test カラーテスト - - + + Gradient グラデーション - + 8 8 - + 2 2 - + 3 3 - + 6 6 - + 4 4 - + 5 5 - + 1 1 - + 9 9 - + 7 7 - + 0 0 - - + + Clear クリア - - + + Reset ループ - - - - + + + + Anycast リクエスト - - + + Stop 停止 - - - - - - - - + + + + + + + + Tip 提示 - - - - - + + + + + NoSelectedController 先に大きいスクリーンを選んでください - - - + + + StartTest テストを開始します - - - - + + + + Success 成功 - - - - + + + + failed 失敗 - + StopTest テストを中止します - + loopback mode サイクルモード - + Connect timeout 接続タイムアウト - + Reset loop mode ループを設定 - - + + success 成功 - - - DeviceItem OnProHttpResponse 解析json文件错误! - jsonファイルの解析エラー! - - - - CtrlVerifyClockPanel - - - Form - リフレッシュ - - - - English - - - - - 中文 - - - - - Verify Clock Configuration - 検証クロック設定 - - - - Verify to Computer time - コンピュータ時刻の確認 - - - - - Cur time of controller - ディスプレイの現在の時間 - - - - LAN - LAN - - - - (min/time) - (分/回) - - - - Sync identificationCode - 同期IDコード - - - - - identification code - 識別コード - - - - - Time offset(msec) - タイム・オフセット( msec ) - - - - - Brightness - スクリーン輝度 - - - - - Volume - 体積 - - - - - Screen on/off - スクリーンスイッチ - - - - - Slave - から - - - - Master - - - - - - NTP Server - NTPサーバ - - - - - - - NTP Server address - NTPサーバのアドレス - - - - - - - TimeZone - タイムゾーン - - - - - - - - - - - - - - - Set - セット - - - - - Language: - 言語: - - - - - Enable Synchronous playing - 画面を同期させる機能 - - - - Lora - - - - - GPS - - - - - NTP - - - - - Time zone - タイムゾーン - - - - - - - Sync time interval - 同期時間間隔 - - - - Verify clock configuration - 検証クロック設定 - - - - - - - - - - - - - - Readback - 読み戻し - - - - Master - - - - - Sync clock to computer time - 校正クロックからコンピュータ時間まで - - - - Identification Code - 識別コード - - - - - - - - - - - - - - Success - 成功 - - - - - - - - - - - - - - failed - 失敗 - - - - SetNtpServer - NTPサービスの設定 - - - - MasterSwitch - メインデバイスの設定 - - - - SlaveSwitch - スレーブデバイスとして設定 - - - - IsMasterSlave - 主従の身分を読み返す - - - - GetControllerDate - 日付時間の取得 - - - - SetingSyncMethod - set syncメソッド - - - - SyncTime - キャリブレーション時間 - - - - GetNtpServer - NTPサービス情報を取得する - - - - GetingSyncMethod - 同期方式を取得 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - SetTimezone - タイムゾーンを設定 - - - - ControlVolumeManual - - - Form - リフレッシュ - - - - Volume(0-15) - 音量(0-15) - - - - - - Readback - 読み戻し - - - - SetVolume - 音量調節 - - - - - - Success - 成功 - - - - - - failed - 失敗 - - - - Volume(min:0-max:15) - 音量(0-15) - - - - GetVolume - 現在の音量を取得 - - - - + + DeviceItem OnProHttpResponse 解析json文件错误! jsonファイルの解析エラー! @@ -2090,174 +653,174 @@ ControlVolumeSchedule - + Defalut volume tip 注意:時間帯の明るさは、定時輝度で表示されます。他の設定されていない時間帯は、デフォルトの輝度値です - - + + Add 追加 - - + + Delete 削除 - - + + Clear クリア - + Default Volume デフォルトの音量 - + (0-15) - - + + Import インポート - - + + Export 出力 - - + + Apply 適用 - + Readback 読み戻し - + Volume value 音量値 - + Start Time 開始時間 - + End Time 終了時間 - + SUN 日曜日 - + MON 月曜日 - + TUE 火曜日 - + WED 水曜日 - + THU 木曜日 - + FRI 金曜日 - + SAT 土曜日 - + Default volume tip 注意:時間帯以外の時間表示はデフォルトの明るさです - + Default volume デフォルトの音量値 - - + + DeviceItem OnProHttpResponse 解析json文件错误! jsonファイルの解析エラー! - + 10 10 - - + + Volume Schedule (*.vols) - + Save File 保存 - - + + Tip 提示 - - + + NoSelectedController 先に大きいスクリーンを選んでください - + SetAutoVolumeTask 設定タイミング音量表 - - + + Success 成功 - - + + failed 失敗 - + GetAutoVolumeTask タイミング音量表の取得 @@ -2265,1187 +828,2504 @@ ControlVolumeWidget - - Form - リフレッシュ + + + Tip + ヒント - - + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + + SetVolume + 音量調節 + + + + + GetVolume + 現在の音量を取得 + + + Volume Control 音量調節 - - + Manual 手動 - - + Schedule スケジュール + + + Volume + 音量 + + + + Readback + 読み戻し + CtrlAdvancedPanel - - Advanced parameters + + Advanced 上級パラメータ - + Screen Width(pixel) 画面幅(ピクセル) - + Width - - + + Height 高さ - - - - - - - + + + + + + + + + + + + + + + Set セット - + Alias 別名 - + Web Server Address: Webサーバのアドレス: - + www.m2mled.net - + www.ledaips.com - + https://www.taxihub.cn:2340 - + https://www.ledaips.com:2340 - + https://www.36taxi.com:2340 - + www.tlzxled.com - + + MCU Uploading + + + + + Traffic screen settings + + + + + Setting protocol ... + + + + + Set protocol + + + + + Getting protocol ... + + + + + Get protocol + + + + + + Port + ポート + + + Realtimer Server Address: Realtimerアドレス: - + + Firmware Management + ファームウェア管理 + + + + update or uninstall + 更新またはアンインストール + + + Clear クリア - - Apk upgrade - APKアップグレード - - - + Check Apk APKを検出 - + Uninstall アンマウント - + Running check 運転状態モニタ - - FPGA version check - FPGAバージョンクエリ - - - - Sync FPGA version - 同期FPGAバージョン - - - - Restart led controller system + + Restart 再起動 - + Check Log ログを見る - + Start LedSet4 - + Open ADB ADBデバッグ機能を開く - + Post Custom JSON Post Custom JSON - - - - - - - - + + + + + + + + Clear Program 番組をクリア - + www.ledokcloud.com/realtime - - M80 configuration - M 80の設定 + + Config + の設定 - + Refresh 更新 - + Restore to default 標準の値を復元 - + Taxi top screen configuration タクシートップ画面の設定 - + + Service:High Out of service:Low 客がいます:高 客がいません:低 - + + Service:Low Out of service:High 客がいます:低 客がいません:高 - + Start LedSet3.0 configure LED module LedSet 3.0を使ってLEDモジュールを配置する(メーカーの専門家が使用する) - + Binding *.ic account indentity voucher テーピングtaxihubプラットフォームのユーザーID証明書 - + Rotate 回転 - - 0 degrees - 0度 - - - - 90 degrees - 90度 - - - - 180 degrees - 180度 - - - - 270 degrees - 270度 - - - + Min brightness 最低輝度 - - (min:1) - (最小:1) - - - - - + + + Readback 読み戻し - - - + Send 送信 - + Max brightness 最高輝度 - - (max:255) - (マックス:255) - - - - + + SetScreenSize スクリーンのピクセルサイズを設定 - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Success 成功 - + Compant ID: 会社ID: - - FPGA Upgrade - FPGAアップグレード - - - + Compant ID 会社ID - + InputWebServerAddressTip Webサーバのアドレスを入力してください - + InputCompanyIdTip 会社IDを入力してください - + Do you want to modify webserveraddress and companyId? 設定サーバアドレスと会社IDを確認しますか? - - - - - - - - - - - - - - - - - - - - - - failed - 失敗 - - - - + + SetOnlineAddr ウェブサーバのアドレスを設定 - + + ClearRealtimeServer クリア - - InputRealTimeAddressTip - RealTimerアドレスを入力してください - - - + + SetRealtimeServer RealTimerアドレスを設定 - - - - + + + + Tip Info ヒント - - - + + + Can not find LedSet3.0.exe,down you need download and install it LEDSET 3.0 . exeを見つけることができません。ダウンロードしてインストールする必要があります - + + RestartAndroid 再起動 - - FPGA Version - FPGAバージョン - - - - + + running 実行中 - - + + no running 実行されていません - + Check Apk Version チェック APK バージョン - - + + UninstallSoftware アンマウント - - - IsSoftwareRunning + + + Check apk running status APK運転状態監視 - - apk package (*.rpd) - - - - - CheckHardwareVersions - お問い合わせFPGAバージョン - - - - - - SynchronousHardwareVersion - ハードウェアバージョンの同期 - - - - Check Screen untile fpga update finished - 画面のアップグレードの進捗を確認します - - - + + OpenAdb ADBデバッグ機能を開く - + indentity voucher (*.ic) 身分証明書(*.ic) - - - - - + + + + + InvokeTaxiAppFunction 証明書をバインド - - Json format is error! - - - - - + + AliIotSetting - - apk package (*.apk *.zip) - - - - + Software Version Info - + Package - + Version バージョン - - - UpgradeSoftware - ファームウェアをアップグレードする - - - - This screen is encrypted,Please decrypt and upgrade APK! - この画面は、暗号化され、復号化し、アップグレードAPK! - - - - + + Package name is null パッケージ名は空です - + Clearing Program プログラムクリア - - - - + + + + Timeout タイムアウト - - - - + + + + Failed 失敗 - + Getting Log - + ログを取得中 - - - - - - - - - + + + + + + + + + + + Error エラー - + + Setting Timing Reboot + スケジュール再起動を設定中 + + + + Set Timing Reboot + スケジュール再起動の設定 + + + + Getting Timing Reboot + スケジュール再起動を取得中 + + + + Get Timing Reboot + スケジュール再起動の取得 + + + + totalResolution + トータル解像度 + + + + strCurDisplayResolution + 表示解像度 + + + + File not exist + ファイルが存在しません + + + + Uploading + アップロード中 + + + + + Set Display Mode + + + + + + Get Display Mode + + + + + + Set Screen Offset + + + + + + Get Screen Offset + + + + Open file Failed ファイルのオープンに失敗しました - + Setting Wallpaper - - + + Set Wallpaper - + System Updating - - + + System Update - + + Getting MCU Version + + + + + + MCU Version + + + + Select File ファイルを選択 - + Setting player background - - + + Set player background - + Clearing player background - - - - - - - - + + + + + + + + Clear player background - + Setting Baud Rate - + Set Baud Rate - + Getting Baud Rate - + Get Baud Rate - + + Text is empty + + + + + Json Parse Error + + + + + Json isn't an Object + + + + + Setting card work mode ... + + + + + Set card work mode + + + + + Getting card work mode ... + + + + + Get card work mode + + + + + Resolution Config + 解像度設定 + + + + Full screen + フルスクリーン + + + + Part + セクション + + + + Display Mode + 表示モード + + + + Screen Position + + + + + Offset + + + + Hidden Settings - + Click right button to hide - + + + Update MCU + + + + + Get MCU Version + + + + Baud Config - + Model - + Uart - + Baud - + + + + + + Get - + 得る - - - - + + Timing Reboot + スケジュール再起動 + + + + Protocol + プロトコル + + + + Server + サービス + + + + Client + クライアント + + + + SetScreenRotation 画面の回転を設定する - + + SetMinBrightness 最小輝度値を設定します - + + SetMaxBrightness 輝度最大値を設定 - + + GetMinBrightness 輝度最小値を取得 - + + GetMaxBrightness 輝度最大値を取得 - + + + Card work mode + + + + + SetSpecialResolution 解像度を設定 - + + GetSpecialResolution 読み込み解像度 - + + CleanDisplayScreenSize デフォルトの解像度を復元 - + + SetHighForBusy 客レベルの設定 - + + GetStateForBusy ゲストレベルを取得 - - install start... - インストールを開始します... - - - + InputAliasTip エイリアスを入力してください - - + + SetCardAlias エイリアスの設定 - - Uploadding - アップロード - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tip 提示 - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NoSelectedController 先に大きいスクリーンを選んでください - + InputWidthTip 正しい幅のピクセル値を入力してください - + InputHeightTip 正しい高さのピクセル値を入力してください - + Password is error パスワード - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - jsonファイルの解析エラー! - CtrlBrightPanel - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + Tip 提示 - - - - - - - - - - - + + + + + + + + + + + NoSelectedController 先に大きいスクリーンを選んでください - - + + SetBrightnessSensitivity 輝度センサ感度を設定する - - + + GetBrightnessSensitivity 明るさ感を得る - - + + SetMinBrightness 最小輝度値を設定します - - + + GetMinBrightness 輝度最小値を取得 - - + + NeedSelectSensorTypeTip センサータイプを選択してください - + Open file dialog - + - + Not found current worksheet - - + + SensorBrightnessTable 輝度センサ設定テーブルの設定 - + GetSensorBrightnessTable センサーブライトテーブル - + no sensorBrightnessTable コントロールカードに輝度設定表が見つかりませんでした - + Save file 保存 - - + + GetCurrentSensorBrightness 現在の明るさを取得する - - + + SetBrightness 輝度を設定する - + GetBrightness 輝度値を取得 - + Brightness スクリーン輝度 - + Import File インポートファイル - - + + BrightnessSchedule (*.bjs) - + Save File 保存 - + BrightnessValue 輝度値 - + Start Time 開始時間 - + End Time 終了時間 - - + + SetAutoBrightnessTask 送信タイミング輝度表 - + GetAutoBrightnessTask 取得タイミング輝度表 - - - - + + Error エラー - + Brightness Configuration 輝度の設定 - + Auto 自動 - + Manual 手動 - + Schedule スケジュール - + + Adapt to Old Devices + 古い設備に適合する + + + BrightTip1 最大輝度が64であるならば、最小の明るさは1%または適切な値として構成されることができます;最大の明るさが255であるならば、最小の明るさは36%かそれ以上として構成されなければなりません、さもなければ、明るさは低くなります。 - + BrightTip2 ファイルをアップロードする時、正しいセンサータイプを選択してください。でないと、無効です。 - + Sensitivity 感度 - + Minbrightness 最小輝度 - - - + + + Set セット - + Upload ファイルのアップロード - - - - + + + + Readback 読み戻し - + ReadbackTable 読み戻し - + Refresh 更新 - + Cur Brigntness カールの明るさ - + Brightness value 輝度値 - + Default brightness 標準の明るさ - + Add 追加 - + Clear クリア - + Delete 削除 - + Import インポート - + Export 出力 - + Apply 適用 - + Default brightness tip - ヒント:この設定時間内は明るさを設定し、設定時間外はデフォルトの明るさとなります。例えば、デフォルトの輝度を80とし、設定輝度は180とし、時間範囲は8:00〜17:00とすると、時間範囲は180となり、他の時間はデフォルトの輝度80となる。 + ヒント:この設定時間内は明るさを設定し、設定時間外はデフォルトの明るさとなります。例えば、デフォルトの輝度を50%とし、設定輝度は80%とし、時間範囲は8:00〜17:00とすると、時間範囲は80%となり、他の時間はデフォルトの輝度50%となる。 + + + + CtrlHdmiPanel + + + HDMI Configuration + ビデオソースの設定 + + + + Manual + 手動 + + + + Schedule + スケジュール + + + + + + + Tip + 提示 + + + + + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + + SyncSwitch + スイッチのビデオソースをHDMI-IN + + + + + AnSyncSwitch + 異ステップモードを切り替え + + + + IsSync + 同じ非同期モードを読み返す + + + + Import File + インポートファイル + + + + Save File + 保存 + + + + + Sync Schedule + 同期モードタイミングタスク + + + + + SetTimingHdmiInTask + 同期モードタイミングタスクの設定 + + + + GetTimingHdmiInTask + 同期モードタイミングタスクの取得 + + + + + Async + アシュリン + + + + + Readback + 読み戻し + + + + Start Time + 開始時間 + + + + End Time + 終了時間 + + + + SUN + 日曜日 + + + + MON + 月曜日 + + + + TUE + 火曜日 + + + + WED + 水曜日 + + + + THU + 木曜日 + + + + FRI + 金曜日 + + + + SAT + 土曜日 + + + + Add + 追加 + + + + + Apply + 適用 + + + + Clear + クリア + + + + Delete + 削除 + + + + Import + インポート + + + + Export + 出力 + + + + By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period + 非同期のコンテンツをデフォルトで再生し、同期のHMI-INポートに入力します + + + + CtrlNetworkPanel + + + Wire Enther(RJ45) Configuration + 有線ネットワークの設定 + + + + DHCP + + + + + Specify IP + 指定IP + + + + IP Address + IPアドレス + + + + Gateway + ゲートウェイ + + + + DNS Address + DNSアドレス + + + + + + Set + セット + + + + + + + Readback + 読み戻し + + + + WIFI Configuration + WiFiの設定 + + + + WiFi Mode + WiFi機能 + + + + Cellular Config + セルラーデータ構成 + + + + Enable Cellular Data + セルラーデータを有効にする + + + + Get cellular network status information + セルラーネットワーク状態情報を取得する + + + + Through the check status button + 「ステータスを取得」ボタンを使用すると、国コードに自動的に一致し、対応するAPN情報を取得するには「事業者」を選択します。 + + + + Set APN Info + APN情報を設定する + + + + Country ID(mcc): + 国号(mcc): + + + + + Carrier Name + 運営者 + + + + APN(Required) + APN(必ず記入) + + + + Flight Mode + 飛行モード + + + + WiFi name + WiFiの名前 + + + + + + Password + パスワード + + + + + Input password + パスワードを入力 + + + + Scan + スキャン + + + + Ap Mode + APエネルギー + + + + OFF + オフ + + + + ON + オン + + + + AP name + AP名 + + + + Subnet mask + サブネットマスク + + + + Input ap name + APの名前を入力 + + + + + + + + + + + + + + + Tip + 提示 + + + + + + + + + + + + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + + SetEthernet + 有線網を設置する + + + + + + + + + + + Attention + 注意 + + + + Please input IP address! + IPアドレスを入力してください! + + + + Your IP Address is Invalid! + IPアドレスが無効です! + + + + Please input Mask address! + サブネットマスクの住所を入力してください! + + + + Your Mask Address is Invalid! + マスクアドレスが無効です! + + + + Please input Gateway address! + ゲートウェイのアドレスを入力してください! + + + + Your Gateway Address is Invalid! + ゲートウェイアドレスが無効です! + + + + Please input DNS address! + DNSアドレスを入力してください! + + + + Your DNS Address is Invalid! + DNSアドレスを入力してください! + + + + + GetEthernet + 有線ネットワークの設定を取得 + + + + DHCP IP + DHCP IP + + + + STATIC IP + 静的IP + + + + + ConfigurationWiFi + WiFiの設定 + + + + + IsPortableHotSpot + ホットスポットとWiFiモードの取得 + + + + GetWifiList + スキャンWiFi + + + + + ConfigurationHotSpot + ホットスポットの設定 + + + + success + 成功 + + + + WifiName + Wifiの名前 + + + + ApName + AP名前 + + + + + GetCurrentAPN + APN情報の取得 + + + + GetSIMStatus + SIM状態を取得 + + + + + SetAPN + APNの設定 + + + + 状态: + 状態: + + + + 未知 + 不明 + + + + 锁定状态,需要用户的PIN码解锁 + ロック状態は、ユーザのPINコードのロック解除が必要です + + + + 锁定状态,需要用户的PUK码解锁 + ロック状態は、ユーザのPUKコードのアンロックが必要です + + + + 锁定状态,需要网络的PIN码解锁 + ロック状態は、ユーザのPINコードのアンロックが必要です + + + + 就绪 + 準備完了 + + + + no checked sim card + simカードが検出されませんでした + + + + 国家码: + 国号: + + + + 号码: + 番号: + + + + 用户: + ユーザ: + + + + 信号: + 信号: + + + + 信号正常 + 信号が正常である + + + + 不在服务区 + サービスエリアにはいません + + + + 仅限紧急呼叫 + 緊急呼び出しのみ + + + + 射频已经关闭 + 無線周波数はすでに閉鎖されました + + + + 网络: + ネットワークタイプ: + + + + 网络类型未知 + 不明 + + + + GPRS网络 + GPRS + + + + EDGE网络 + EDGE + + + + UMTS网络 + UMTS + + + + CDMA网络,IS95A 或 IS95B. + CDM + + + + EVDO网络, revision 0. + EVDO,revision 0. + + + + EVDO网络, revision A. + EVDO,revision A. + + + + 1xRTT网络 + 1xRTT + + + + HSDPA网络 + HSDPA + + + + HSUPA网络 + HSUPA + + + + HSPA网络 + HSPA + + + + 漫游: + ローミング: + + + + Yes + + + + + No + いいえ + + + + 数据连接状态: + データ接続状態: + + + + 断开 + 切断 + + + + 正在连接 + 接続中 + + + + 已连接 + 接続済み + + + + 暂停 + 一時停止 + + + + 数据活动休眠状态: + データアクティビティの休止状態: + + + + 活动,但无数据发送和接收 + アクティブですが、データ送信と受信はありません + + + + 活动,正在接收数据 + アクティブ、データ受信中 + + + + 活动,正在发送数据 + イベント、データ送信中 + + + + 活动,正在接收和发送数据 + イベント、データ受信と送信中 + + + + 休眠状态 + スリープ状態 + + + + 信号强度: + 信号の強度: + + + + User + ユーザー + + + + Type + タイプ + + + + Server + サービス + + + + Port + ポート + + + + Proxy + プロキシ + + + + MMS Port + MMS ポート + + + + MMS Proxy + MMS プロキシ + + + + + SetSwitchSimData + 4G/5Gスイッチの設定 + + + + + ContrFlightMode + 飛行モードの設定 + + + + + GetFlightModeState + 飛行モード状態を取得 + + + + CtrlPwdPanel + + + Set Password + パスワードの設定 + + + + Original password + 元のパスワード + + + + original password + 元のパスワード + + + + + New password + 新しいパスワード + + + + Repeat new password + 繰り返し入力 + + + + + + + Set encryption + 暗号化 + + + + Cancel encryption + 暗号化を解除 + + + + Enter again + 再入力 + + + + + + + + + + + + Tip + 提示 + + + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + + InputOriginalPasswordTip + オリジナルのパスワードを入力してください + + + + InputNewPasswordTip + 新しいパスワードを入力してください + + + + InputRepeatPasswordTip + 新しいパスワードを繰り返して入力してください + + + + InputRepeatPasswordNotSameTip + 二回入力したパスワードが一致しません + + + + Tip Info + ヒント + + + + After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? + パスワードを設定した後、パスワードを覚えて、それを記録してください。パスワードを忘れた場合は、デバイスが動作することができなくなります。この操作を続行しますか? + + + + + + + SetControllerPassword + 暗号化の設定 + + + + + Error + エラー + + + + + Success + 成功 + + + + + + Modify password + パスワードを変更 + + + + + + + OriginalPasswordErrorTip + 元のパスワードが間違っています + + + + CtrlVerifyClockPanel + + + Verify Clock Configuration + 検証クロック設定 + + + + + Verify to Computer time + コンピュータ時刻の確認 + + + + Cur time of controller + ディスプレイの現在の時間 + + + + + LAN + LAN + + + + + + + + + + + + + + Tip + ヒント + + + + + + + + + + + + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + screenSwitch + スクリーンの切り替え + + + + + + YES + 開く + + + + + + NO + オフ + + + + volume + 音量 + + + + brightness + 明るさ + + + + + identificationCode + 識別コード + + + + + delaySync + 時間オフセット + + + + + msec + ミリ秒 + + + + + + + OtherSyncItem + その他の同期項目 + + + + + + + lastSynchronousTime + 最終同期時間 + + + + checkNtpTime + 同期間隔 + + + + Lora identity + ロラの身分 + + + + (min/time) + (分/回) + + + + identification code + 識別コード + + + + Time offset(msec) + タイム・オフセット( msec ) + + + + Brightness + スクリーン輝度 + + + + Volume + 体積 + + + + Screen on/off + スクリーンスイッチ + + + + + Slave + から + + + + NTP Server + NTPサーバ + + + + + NTP Server address + NTPサーバのアドレス + + + + TimeZone + タイムゾーン + + + + + + + + Set + セット + + + + Language: + 言語: + + + + Enable Synchronous playing + 画面を同期させる機能 + + + + + Sync time interval + 同期時間間隔 + + + + + + + + Readback + 読み戻し + + + + + Master + + + + + Identification Code + 識別コード + + + + + SetNtpServer + NTPサービスの設定 + + + + + MasterSwitch + メインデバイスの設定 + + + + + SlaveSwitch + スレーブデバイスとして設定 + + + + IsMasterSlave + 主従の身分を読み返す + + + + + GetControllerDate + 日付時間の取得 + + + + + SetingSyncMethod + set syncメソッド + + + + + SyncTime + キャリブレーション時間 + + + + + GetNtpServer + NTPサービス情報を取得する + + + + + GetingSyncMethod + 同期方式を取得 + + + + + SetTimezone + タイムゾーンを設定 Def - - - + Connection Timeout 接続タイムアウト - - - - - - - + + + + + Device replied - + デバイス応答 - - + + + Success 成功 - - - - Error - エラー - - - - Tip Info - ヒント - - - - + Fail 失敗 @@ -3453,666 +3333,314 @@ DeviceCtrlPanel - - - + + + + Current Screen 現在のスクリーン - - + + none なし - - + + Clear クリア - - - single screen operation - シングルスクリーン操作 - - - + + Multi screen operation マルチスクリーン操作 - + + selected num 選択された数 - + Brightness Adjustment 輝度設定 - + Power Control 電源コントロール - + Net Config ネット配置 - - Time Synchronization + + Time Sync タイマ配置 - + Video source ビデオソース - - Encrypt - 暗号化する + + Password + ひそかに言う - - Advanced parameters + + Advanced 上級パラメータ - - Current Screen: - 現在のスクリーン: - - - + Test テスト - - Volume Adjustment + + Volume Adj. 音量調節 DeviceItem - + GetScreenDetailInfo 詳細 - + ReadbackPic 回読画面 - + Input password パスワードを入力 - + GetScreenshotFull 回読画面 - + cur brightness: 現在の明るさ: - + android version: Androidバージョン: - + IMEI: - + HardWard Version: FPGAバージョン: - + MAX Brightness level: 輝度レベル: - + Android OS Resolution: Androidの解像度: - + Firmware Version: ファームウェアバージョン: - + Player Version: プレーヤーファームウェアバージョン: - + Detail Info 詳細 - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + receive 受信 - - SetScreenOn - 電源の設定 - - - + AliIotSetting - - + + GetScreenStatus スクリーン状態を取得 - - + + Status 状態 - + Tip Info ヒント - + password is wrong パスワードが間違っている - + GetBrightness 輝度値を取得 - - - + brightness 明るさ - - MasterSlaveSwitch - メインの個人情報を設定 - - - - SetBrightness - 輝度を設定する - - - - - SetMinBrightness - 最小輝度値を設定します - - - - GetBrightnessSensitivity - 明るさ感を得る - - - - sensitivity - 感度 - - - - GetMinBrightness - 輝度最小値を取得 - - - - SetSensorBrightnessTable - センサーパラメータの設定表 - - - - SetSwitchWiFi - WiFiスイッチの設定 - - - - ConfigurationWiFi - WiFiの設定 - - - - ConfigurationHotSpot - ホットスポットの設定 - - - - GetSwitchWiFi - WiFi状態を取得 - - - + SetAutoBrightnessTask 送信タイミング輝度表 - + SetAutoVolumeTask 設定タイミング音量表 - + SetVolume 音量調節 - + GetVolume 現在の音量を取得 - + SetTimingScreenTask 画面タイミングスイッチタスクの設定 - - GetControllerDate - 日付時間の取得 - - - - SetHighForBusy - 客レベルの設定 - - - - - GetStateForBusy - ゲストレベルを取得 - - - - Service:Low Out of service:High - 客がいます:低 客がいません:高 - - - - Service:High Out of service:Low - 客がいます:高 客がいません:低 - - - - - - IsPortableHotSpot - ホットスポットとWiFiモードの取得 - - - - WifiName - Wifiの名前 - - - - ApName - AP名前 - - - + TestScreen テスト画面 - + SetOnlineAddr ウェブサーバのアドレスを設定 - + SetRealtimeServer RealTimerアドレスを設定 - - GetOnlineAddr - ウェブサーバのアドレスを取得 - - - - GetRealtimeServer - realtimeサーバのアドレスを取得します - - - - SetNtpServer - NTPサービスの設定 - - - - GetNtpServer - NTPサービス情報を取得する - - - - SyncTime - キャリブレーション時間 - - - - DelPrograms - 番組をクリア - - - - SetingSyncMethod - set syncメソッド - - - + GetCurrentSensorBrightness 現在の明るさを取得する - + Cur brightness カールの明るさ - - SetSpecialResolution - 解像度を設定 - - - - GetSpecialResolution - 読み込み解像度 - - - - totalResolution - FPGAトータル解像度 - - - - strCurDisplayResolution - 表示解像度 - - - - CleanDisplayScreenSize - デフォルトの解像度を復元 - - - - SetMaxBrightness - 輝度最大値を設定 - - - - GetMaxBrightness - 輝度最大値を取得 - - - - screenSwitch - スクリーンの切り替え - - - - - - YES - 開く - - - - - - NO - オフ - - - - LAN - LAN - - - + Connect 接続 - + timeout タイムアウト - + Anycast リクエスト - - + volume 音量 - - - - - - - GetingSyncMethod - 同期方式を取得 - - - - - identificationCode - 識別コード - - - - - delaySync - 時間オフセット - - - - - msec - ミリ秒 - - - - - - - OtherSyncItem - その他の同期項目 - - - - - - - lastSynchronousTime - 最終同期時間 - - - - checkNtpTime - 同期間隔 - - - - Uploadding - アップロード - - - + Success 成功 - + failed 失敗 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + success 成功 - - - Lora identity - ロラの身分 - - - - Master - - - - - Slave - から - - - - SetBrightnessSensitivity - 輝度センサ感度を設定する - - - - - + + + on オン - - - + + + off オフ @@ -4121,115 +3649,115 @@ DevicePanel - + All トータル トータル - + Online オンライン中 - - + + Refresh 更新 更新 - - - + + + Specify IP 指定IP 指定IP - + Current Screen 現在のスクリーン - + none なし - + Specify IP list - + 指定 IP リスト - + Search 検索 - - + + Attention 注意 - - + + Please input IP address! IPアドレスを入力してください! - + Cancel キャンセル - + Screen ID ターミナルID - + Screen IP ターミナルIP - + Screen Size スクリーンサイズ - + Remark Name 別名 - + readback pic 読み戻し - + send 送信 - + More Info 詳細 - + Cur Brightness 現在の画面の明るさ - + Power Status 画面切り替えステータス - + Security 暗号化 @@ -4406,39 +3934,156 @@ - EAudio + EAClock - + Basic Properties 基本的な属性 - - File - ファイル + + Time Zone + タイムゾーン - + + Custom Dial + ユーザー定義の文字盤 + + + + Select + 選択 + + + + Select Dail file + 文字盤の画像を選択 + + + + Hour Mark + 時間目盛り + + + + + Circular + 円形 + + + + + Rectangle + 矩形 + + + + Number + デジタル + + + + + + T + + + + + Min Mark + 分目盛り + + + + Color + カラー + + + + Length + 長さ + + + + Width + + + + + Hour Hand + 時針 + + + + Min Hand + 分針 + + + + Sec Hand + 秒針 + + + + Show + 表示 + + + + Text + テキスト + + + Play Properties 再生方法 - + Play Duration 再生時間 - + + s + + + + + EAudio + + + Basic Properties + 基本的な属性 + + + + File + ファイル + + + + Play Properties + 再生方法 + + + + Play Duration + 再生時間 + + + Select File ファイルを選択 - + s - + Audio オーディオ @@ -4446,233 +4091,373 @@ EBase - + Area 領域(px) - + X X - + Y Y - + W W - + H H - + Border ボーダー - - + + None なし - + Effect 特効 - + Rotate 回転 - + Blink きらめき - + Speed スピード - + Slow 遅い - + Moderate - + Fast 速い - EEnviron + EDClock - - - - - - - - north - 北の方 + + MON + 月曜日 - - - - - - - - east - + + TUE + 火曜日 - - - - - - - - south - 南の方 + + WED + 水曜日 - - - - - - - - west - 西の方 + + THU + 木曜日 - - - Temperature - 温度 + + FRI + 金曜日 - - - Humidity - 湿度 + + SAT + 土曜日 - - - Noise - ノイズ + + SUN + 日曜日 - - Wind Speed - 風速 + + + AM + 午前 - - Wind Direction - 風向 + + + PM + 午後 - + Basic Properties 基本的な属性 - - Title - タイトル + + Time Zone + タイムゾーン - - Compensation - 補償 + + Year + - - Wind speed - 風速 + + Month + - - Wind direction - 風向 + + Day + - - Left - 左に寄る + + Hour + - - Center - 中央にある + + Min. + - - Right - 右に寄る + + Sec. + - - Single scroll - 1行スクロール + + Weekly + 曜日 - - Speed - スピード + + Full Year + 四桁数の年 - - ms/pixel - ミリ秒/ピクセル + + 12-Hour + 12時 - - Back Color - 背景色 + + Date Style + 日付スタイル - + + Time Style + タイムスタイル + + + + Display Style + 表示スタイル + + + + Multiline + 複数行表示 + + + Play Properties 再生方法 - - Refresh Cycle - リフレッシュサイクル - - - - min. - - - - + Play Duration 再生時間 - + + s + + + + + EEnviron + + + + + + + + + north + 北の方 + + + + + + + + + + east + + + + + + + + + + + south + 南の方 + + + + + + + + + + west + 西の方 + + + + + Temperature + 温度 + + + + + Humidity + 湿度 + + + + + Noise + ノイズ + + + + Wind Speed + 風速 + + + + Wind Direction + 風向 + + + + Basic Properties + 基本的な属性 + + + + Title + タイトル + + + + Compensation + 補償 + + + + Wind speed + 風速 + + + + Wind direction + 風向 + + + + Left + 左に寄る + + + + Center + 中央にある + + + + Right + 右に寄る + + + + Single scroll + 1行スクロール + + + + Speed + スピード + + + + ms/pixel + ミリ秒/ピクセル + + + + Back Color + 背景色 + + + + Play Properties + 再生方法 + + + + Refresh Cycle + リフレッシュサイクル + + + + min. + + + + + Play Duration + 再生時間 + + + s @@ -4680,37 +4465,37 @@ EGif - + Basic Properties 基本的な属性 - + File ファイル - + Select File ファイルを選択 - + Play Properties 再生方法 - + Play Duration 再生時間 - + s - + Play Times 再生回数 @@ -4718,73 +4503,73 @@ EMultiWin - + Please add media on the right 右側にメディアを追加してください。複数のメディアに参加できます。LEDディスプレイはリスト順に再生されます - + Media List メディアリスト - - - + + + Text テキスト - - - + + + Photo 写真 - - - + + + Video 動画リスト - - - + + + Gif アニメーション - - - + + + DClock デジタル時計 - - - + + + AClock アナログ時計 - - - + + + Select File ファイルを選択 - - + + Environment 環境モニタリング - - + + Timer タイマー @@ -4792,118 +4577,118 @@ EPhoto - + Basic Properties 基本的な属性 - + File ファイル - + Select File ファイルを選択 - + Image Read Error 画像読み込みエラー - + Play Properties 再生方法 - + Play Duration 再生時間 - - + + s - + Enter Style 開始効果 - + None なし - + Alpha_In 淡入 - + Moving to left 連続する左シフト - + Moving to right 連続右シフト - + Moving to top 連続アップコンバート - + Move to bottom 連続的下向 - + Zoom in 拡大 - + Zoom in to left_bottom 左下の拡大 - + Zoom in to left_top 左上の角を大きく - + Zoom in to right_top 右上拡大 - + Zoom in to right bottom 右下隅を大きく - + Rotate to right 右回り - + Rotate to left 左回り - + Enter Duration 効果時間 - + Images (*.png *.jpg *.jpeg *.bmp) 写真(*.png *.jpg *.jpeg *.bmp) @@ -4911,191 +4696,191 @@ EText - + Enter your text 内容を入力してください - + Basic Properties 基本的な属性 - - Font Color - フォント色 - - - + Back Color 背景色 - + Kerning 字の間隔 - + Line Spacing 間隔 - + PageCount: 総ページ数: - + page ページ - + Import txt File インポート txt ファイル - + Select File ファイルを選択 - + Fail 失敗 - + File Open Fail - + Play Properties 再生方法 - + Flip 次頁 - + Scroll スクロール - + Static スタティック - - - + + + Play Duration 再生時間 - + Duration/Page ページごとの再生時間 - + Effect time 効果時間 - - + + Tip Info ヒント - - + + Effect time cannot be longer than duration time 効果の長さはプレイ時間より長くできません - + s - + + Text Color + テキスト色 + + + + Colorful Text + まばゆい文字 + + + Entrance Effect 開始効果 - + no なし - + random ランダム - + right to left 左へ連続移動 - + bottom to top 連続して上に移動 - + left to right 右へ連続移動 - + top to bottom 連続して下に移動 - - Head-Tail Connected - 首尾接続 - - - + Head-Tail Spacing 首尾間隔 - + Scroll Style スクロール方向 - + Right -> Left 左へ - + Bottom -> Top 上へ - + Left -> Right 右へ - + Top -> Bottom 下へ - + Scroll Speed スクロールスピード @@ -5103,87 +4888,87 @@ ETimer - + day - + hour - + min - + sec - + Basic Properties 基本的な属性 - + Count Down カウントダウン - + Count Up カウントアップ - + Time 目標時間 - + Day - + Hour - + Min - + Sec - + Multiline 複数行表示 - + Text テキスト - + Play Properties 再生方法 - + Play Duration 再生時間 - + s @@ -5191,64 +4976,64 @@ EVideo - + Basic Properties 基本的な属性 - + File ファイル - + Play Properties 再生方法 - + Play Duration 再生時間 - + Select File ファイルを選択 - + s - + Play Times 再生回数 - + Video Transcoding - - + + Video Transcoding Progress ビデオ変換の進歩 - - + + Error エラー - + Video ビデオ - + Flash Flash @@ -5256,17 +5041,17 @@ EWeb - + Basic Properties 基本的な属性 - + Play Duration 再生時間 - + s @@ -5294,10 +5079,93 @@ + + GenTmpThread + + + Preparing ... + 準備... + + + + MON + 月曜日 + + + + TUE + 火曜日 + + + + WED + 水曜日 + + + + THU + 木曜日 + + + + FRI + 金曜日 + + + + SAT + 土曜日 + + + + SUN + 日曜日 + + + + AM + 午前 + + + + PM + 午後 + + + + day + + + + + hour + + + + + min + + + + + sec + + + + + Create json ... + クリエイトjson... + + + + Scan program ... + スキャン番組… + + LoColorSelector - + Transparent 透明な @@ -5340,186 +5208,230 @@ MainWindow - + Language 言語 - + Help ヘルプ - - + + Check for updates アップデートをチェック - - + + firmware manager ファームウェア管理 - - - Software Configuration + + + Software Config ソフトウェアの設定 - - + + Info 情報 - - + + About 当ソフトウェアについて - - + + Setting 設置 - + + Software Update + ソフトウェアの更新 + + + + CurVersion + 現在のバージョン + + + + Update + 更新 + + + + LatestVersion: + 最新バージョン: + + + + + Update log: + 更新ログ: + + + + The current version is already the latest version + すでに最新バージョンです。 + + + Device 端末管理 - + Program コンテンツ管理 - + Control ターミナルコントロール - + GuangYinPin スクリーン - + Check card ワンタッチ修復 - + Tip Info ヒント - + RestoreLedCardIpByUdpTip この操作はLAN内のすべてのコンピュータIPと同じセグメントにないコントロールカードを固定IPに修正します。慎重に操作してください。 + + Net + + + Connection Timeout + 接続タイムアウト + + + + Error + エラー + + PageEditor - + Zoom In 拡大 - + Zoom Out 縮小 - + Original size オリジナル割合 - + Delete the secect media 選んで削除する - + Clear all media コンテンツをすべてクリアする - + Move layer up 前面にする(ショートカットキーPgUp) - + Send backward 背面にする(ショートカットキーPgDn) - + Bring to front 最前面にする(ショートカットキーHome) - + Move to the bottom layer 写真を最背面にする(ショートカットキーEnd) - + Fill the entire screen 全画面塗りつぶし - + Fill the screen horizontally 行塗りつぶし - + Fill the screen vertically 列塗りつぶし - + Align top 縦位置 上詰め - + Center vertically 縦位置 中央揃え - + Bottom align 縦位置 下詰め - + Align left 横位置 左詰め - + Center horizontally 横位置 中央揃え - + Align right 横位置 右詰め - + Tip Info ヒント - + Clear all medias? @@ -5527,79 +5439,84 @@ PageListItem - + times - + Page name プログラム名 - + New 新規 - + Play times 再生回数 - + + Sources Repeat + ソースの繰り返し + + + Audios オーディオ - + Total Dur 全期間 - - + + s - + Select File ファイルを選択 - + Duration 期間 - + Vol 音量 - + Valid Date 有効期間 - - + + Warning 警告 - + Start Time can't be later than End Time 開始時間は終了時間より後にようにしてください - + End Time can't be earlier than Start Time 終了時間は開始時間より遅いようにしてください - + Plan タイムスケジュール @@ -5628,17 +5545,17 @@ PlayWin - + Move to Top Left 左上隅に移動 - + Set Position 設定位置 - + Close 閉じる @@ -5646,12 +5563,12 @@ PlayerBackSendThread - + Open file failed ファイルのオープンに失敗しました - + Read file failed ファイルの読み込みに失敗しました @@ -5672,47 +5589,47 @@ ProgCreateDlg - + Resolution 解像度 - + Solution Information スケジュール情報 - + Solution Name リスト名 - + Width - + Height 高さ - + Remarks 備考 - - 节目超宽需要打折, 请输入打折宽度 + + 每段打折宽度 (用空格分隔) - + OK 確定 - + Cancel キャンセル @@ -5720,221 +5637,200 @@ ProgEditorWin - + Save 保存 - - + + Save as 名前を付けて保存 - + Setting 設置 - + Text テキスト - + Photo 写真 - + Video ビデオ - + Gif アニメーション - + Clock デジタル時計 - + Analog Clock アナログ時計 - + Environment 環境モニタリング - + Web ウェブページ - + MuliContentWindow マルチ素材ウィンドウ - + In this window, a plurality of different program materials can be added and played according to the order of joining the list; このウィンドウには、複数の異なる番組素材を追加して、リストに追加した順に再生することができます - + Timer タイマー - + Play 再生 - + Stop 停止 - + Publish 転送 - - - - + + + + Select File ファイルを選択 - + program 番組リスト - + Add page ページを追加 - + Copy page コピーページ - + Delete page ページを削除 - - + + Tip Info ヒント - + Are you sure you want to delete this program page? 本当にこの番組ページを削除しますか? - + Move up 前へ - + Move down 次頁 - + widget properties パッケージプロパティ - + Page properties プログラムのプロパティ - + Do you want to save the modifications? 変更された内容を保存してもよろしいですか? - - + + Saving... 保存中、少々お待ちください... - - + + Success 成功 - - + Save failed 保存に失敗 - + Convertering データを整理する - - Converter Successed - 整理に成功しました - - - - Converter TimeOut - 整理タイムアウト - - - + Generate preview data プレビューデータの生成 - - Ready - 準備が完了しました - - - - Generate TimeOut - タイムアウトを生成 - - - - + + Error エラー - + Rename fail when saving - + Remove Recursively fail when saving - + Warning 警告 @@ -5942,155 +5838,177 @@ ProgItem - - + + ExportButtonTip USBメモリで再生する - - + + SendButtonTip 転送 - - + + Convertering データを整理する - - - USB Export Successed - USBメモリのエクスポートに成功しました - - - - USB Export TimeOut - USBメモリのエクスポートに失敗しました - - - - Converter Successed - 整理に成功しました - - - - Converter TimeOut - 整理タイムアウト - ProgPanel - - + + New 新規 - - + + Edit 編集 - - + + Delete 削除 - - + + + Import インポート - - + + + Export 出力 - - + + Send 送信 - - + + Publish 転送 - - + + Name 名前 - - + + + Choose Directory + ディレクトリを選択 + + + + Tip + ヒント + + + + The imported directory is already in the working directory, so there is no need to import it again! + このインポートしたディレクトリはすでにワークディレクトリの下にあります。再インポートする必要はありません! + + + + :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? + 解決策は既に存在します。既存の解決策を上書きしたいと思いますか? + + + + Play 再生 - - + + Stop 停止 - - + + Resolution 解像度 - - + + File Size サイズ - - + + Last Modify 最終更新日 - - + + Usb playback USBメモリで再生する - + Program name conflicted 番組名が重なる - + Warning 警告 - + You will delete the selected solution(s),are you sure? 是否确认删除选中的节目? - + + Tip Info ヒント + + ProgPortDlg + + + Solution Name + リスト名 + + + + Progress + 程度 + + + + Done + 完了 + + QObject - + Setting up the LedOK Express... 初期化LedOK Express… @@ -6098,18 +6016,18 @@ SendProgThread - - + + Program is empty プログラムは空です - + Open file failed ファイルのオープンに失敗しました - + Read file failed ファイルの読み込みに失敗しました @@ -6117,73 +6035,73 @@ SendProgramDialog - - + + Publish 転送 - + success info - + Refresh 更新 - + Cancel キャンセル - + Screen ID ターミナルID - + Remark Name 別名 - + Online オンライン中 - + Screen IP ターミナルIP - + Screen Size スクリーンサイズ - + Security 暗号化 - + Progress 程度 - + Remarks 備考 - + This screen is encrypted スクリーンは暗号化されています - + All トータル @@ -6191,12 +6109,12 @@ SoftConfigDialog - - Software Configuration + + Software Config ソフトウェアの設定 - + Video compress to ビデオ圧縮 to @@ -6206,200 +6124,31 @@ トランスコード to - + Text antialiasing 文字のアンチエイリアス - + TextAntilaTip (ヒント:小さい間隔の大きい画面に適しています。このオプションを有効にすると、文字の端に影がフォントのエッジの滑らかさに達します。小さいサイズのスクリーンと単色のスクリーンは使用を推奨しません) - + GuangYinPin スクリーン - + + Width Split + + + + OK 確定 - - SpecialDlg - - Specify IP - 指定IP - - - Search - 検索 - - - Cancel - キャンセル - - - Attention - 注意 - - - Please input IP address! - IPアドレスを入力してください! - - - Your IP Address is Invalid! - IPアドレスが無効です! - - - Error - エラー - - - - ThreadUpgradeApk - - - Uploadding - アップロード中 - - - - TipDialog - - - TextLabel - - - - - - OK - 確定 - - - - - Cancel - キャンセル - - - - X - - - - - - Import - インポート - - - - - Path - パス - - - - - : - - - - - - browse - ブラウズ - - - - You will delete the selected solution(s),are you sure? - 是否确认删除选中的节目? - - - - - Export - 出力 - - - - - Done - 完了 - - - - - Solution Name - リスト名 - - - - - Progress - 程度 - - - - Delete - 削除 - - - - Select the network to connect to the device - LEDコントローラに接続するネットワークを選択してください - - - - Network name - ネットワーク名 - - - - - This operation will only set cable network to static IP,are you sure? - この動作は,選択されたネットワークを固定IPに設定し,自動で直連のLEDデバイスを同一セグメントのIPアドレスに設定して確認するかどうかである? - - - - Do you want set IP of cable network to DHCP - ネットワークの設定はDHCPにより自動的にIPを取得する - - - - - - - - Tip - 提示 - - - - - - Please select the network to connect to the Led controller - LEDコントローラに接続するネットワークを選択してください - - - - Choose Directory - ディレクトリを選択 - - - - The imported directory is already in the working directory, so there is no need to import it again! - このインポートしたディレクトリはすでにワークディレクトリの下にあります。再インポートする必要はありません! - - - - no find program can be imported - プログラムはインポートできません - - UpdateLedset3Dialog @@ -6472,262 +6221,315 @@ おめでとう!あなたは%1の最新バージョンを実行しています - - UpdaterDialog - - - Software Update - ソフトウェアの更新 - - - - X - X - - - - V1.0 - - - - - Update - 更新 - - - - CurVersion - 現在のバージョン - - - - LatestVersion: - 最新バージョン: - - - - - Update log: - 更新ログ: - - - - The current version is already the latest version - すでに最新バージョンです。 - - UpgradeApkDialog - - - Upgrade apk - アップグレード + + Update APK + 更新APK - - 口 - - - - - X - X - - - - + Select apk Appパッケージを選択 - - - - + Upgrade アップグレード - - - APK: - - - - - + Uninstall アンマウント - - + check running state 運転状態を検出 - - + Select Fpga FPGAファイルを選択 - - - success info - + + Installing + インストール中 - - + Refresh 更新 - - + Cancel キャンセル - + Screen ID ターミナルID - + Remark Name 別名 - + Online オンライン中 - + Screen IP ターミナルIP - + Security 暗号化 - + Progress 程度 - + xixunplayer - + cardsystem - + taxiapp - + starter - + connection - + displayer - + FPGA FPGA - + update - + State 状態 - - - + + All トータル - + + This screen is encrypted + スクリーンは暗号化されています + + + + + Select Online APK + オンラインAPKを選択 + + + + No Files + ファイルがありません + + + + Name + 名前 + + + + Size + サイズ + + + + Create Time + 作成時間 + + + + + + Tip + ヒント + + + + Is upgrading now. Please wait + 更新中です、しばらくお待ちください + + + + NoSelectedController + 先に大きいスクリーンを選んでください + + + + + Downloading Online File + オンラインファイルをダウンロード中 + + + + + Error + エラー + + + + Online file is empty + オンラインファイルが空です + + + + Uploading + アップロード中 + + + + Upload error + アップロード エラー + + + + Install error + インストール エラー + + + + Install success + インストールに成功しました + + + + Reminder + ヒント + + + + Reminder: Uninstalling this program may cause the device to offline, cannot be found, lost configs and have a black screen. Please uninstall with caution! + ヒント:このプログラムをアンインストールすると、プラットフォームがオフラインになり、デバイスが見つかりません。構成パラメータが失われ、黒画面の問題が発生します。慎重にアンインストールしてください。 + + + + Do you want to continue? + 続行しますか? + + + + Uninstalling + アンマウント中 + + + + Uninstall error + アンインストール エラー + + + + Uninstall success + アンインストールに成功しました + + + + Check apk running status + APK運転状態監視 + + + + Check error + チェック エラー + + + + Running + 実行中 + + + + Not running + 実行されていません + + + The encrypted control card can be upgraded directly 暗号化されたコントロールカードを直接アップグレードすることができます - - - apk package (*.rpd) - - - - - apk package (*.apk *.zip) - - UsbDetectDialog - + Usb upgrade program Uディスク更新プログラム - + Password パスワード - + OK 確定 - + Input password パスワードを入力 - - + + Tip 提示 - + No checked USB device チェックUSBデバイス - + please select usb device in list リスト内のUSBデバイスを選択してください - + Cancel キャンセル @@ -6735,7 +6537,7 @@ WaitingDlg - + Success 成功 @@ -6764,331 +6566,6 @@ キャンセル - - eAClock - - - Basic Properties - 基本的な属性 - - - - Time Zone - タイムゾーン - - - - Custom Dial - ユーザー定義の文字盤 - - - - Select - 選択 - - - - Select Dail file - 文字盤の画像を選択 - - - - Hour Mark - 時間目盛り - - - - - Circular - 円形 - - - - - Rectangle - 矩形 - - - - Number - デジタル - - - - - - T - - - - - Min Mark - 分目盛り - - - - Hand Color - 剣カラー - - - - H - H - - - - M - - - - - S - - - - - Text - テキスト - - - - Play Properties - 再生方法 - - - - Play Duration - 再生時間 - - - - s - - - - - eDClock - - - MON - 月曜日 - - - - TUE - 火曜日 - - - - WED - 水曜日 - - - - THU - 木曜日 - - - - FRI - 金曜日 - - - - SAT - 土曜日 - - - - SUN - 日曜日 - - - - - AM - 午前 - - - - - PM - 午後 - - - - Basic Properties - 基本的な属性 - - - - Time Zone - タイムゾーン - - - - Year - - - - - Month - - - - - Day - - - - - Hour - - - - - Min. - - - - - Sec. - - - - - Weekly - 曜日 - - - - Full Year - 四桁数の年 - - - - 12-Hour - 12時 - - - - Date Style - 日付スタイル - - - - Time Style - タイムスタイル - - - - Display Style - 表示スタイル - - - - Multiline - 複数行表示 - - - - Play Properties - 再生方法 - - - - Play Duration - 再生時間 - - - - s - - - - - GenTmpThread - - - Preparing ... - 準備... - - - - MON - 月曜日 - - - - TUE - 火曜日 - - - - WED - 水曜日 - - - - THU - 木曜日 - - - - FRI - 金曜日 - - - - SAT - 土曜日 - - - - SUN - 日曜日 - - - - AM - 午前 - - - - PM - 午後 - - - - day - - - - - hour - - - - - min - - - - - sec - - - - - Create json ... - クリエイトjson... - - - - Scan program ... - スキャン番組… - - mGuangYingPinWidget @@ -7493,68 +6970,55 @@ シリアルのオープンに失敗しました - - wExportProgramItem - - - Tip Info - ヒント - - - - :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? - 解決策は既に存在します。既存の解決策を上書きしたいと思いますか? - - wPlanItem - + Form リフレッシュ - + 1 1 - + Every week: 毎週: - + M - + Tu - + W - + Th - + F - + Sa - + Su @@ -7562,30 +7026,30 @@ wProgramPublishItem - + Input password パスワードを入力 - - - + + + Error エラー - - + + Tip Info ヒント - + Fail 失敗 - + password is wrong パスワードエラー @@ -7593,92 +7057,24 @@ wUpgradeApkItem - + Input password パスワードを入力 - - uninstalling - アンマウント中 + + Error + エラー - - - IsSoftwareRunning - APK運転状態監視 - - - - - This screen is encrypted - スクリーンは暗号化されています - - - - - Start upgrading - レベルアップします - - - - - Timeout - タイムアウト - - - - install start... - インストールを開始します - - - - - SynchronousHardwareVersion - 同期FPGA - - - + Tip Info ヒント - + password is wrong - - - - UninstallSoftware - アンマウント - - - - - Success - 成功 - - - - Running - 実行中 - - - - NoRunning - 実行されていません - - - - install success - インストール成功 - - - - - Fail - 失敗 - diff --git a/LedOK/translations/app_zh_CN.ts b/LedOK/translations/app_zh_CN.ts index 31d6b17..3284c38 100644 --- a/LedOK/translations/app_zh_CN.ts +++ b/LedOK/translations/app_zh_CN.ts @@ -71,1339 +71,202 @@ 密码更改成功 - - ControlEncryptWidget - - - Form - Form - - - - - Entrypt Configuration - 安全配置 - - - - Original password - 原始密码 - - - - - - original password - 原始密码 - - - - - - New password - 新密码 - - - - - Repeat new password - 重复输入 - - - - - - - Set encryption - 加密 - - - - - Cancel encryption - 取消加密 - - - - - Enter password - 输入密码 - - - - Enter again - 再次输入 - - - - - - - - - Tip - 提示 - - - - NoSelectedController - 请先选择大屏幕 - - - - - InputOriginalPasswordTip - 请输入原始密码 - - - - InputNewPasswordTip - 请输入新密码 - - - - InputRepeatPasswordTip - 请重复输入新密码 - - - - InputRepeatPasswordNotSameTip - 两次输入的密码不一致 - - - - Tip Info - 提示 - - - - After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? - 设置密码后,请记住密码并记录。如果忘记密码,设备将无法运行。确实要继续此操作吗? - - - - - SetControllerPassword - 设置加密 - - - - Readback - 回读 - - - - - - Success - 成功 - - - - - - failed - 失败 - - - - - Modify password - 修改密码 - - - - OriginalPasswordErrorTip - 原始密码错误 - - - - ControlHdmiSchedule - - - Form - Form - - - - - Add - 添加 - - - - - Delete - 删除 - - - - - Clear - 清除 - - - - - Import - 导入 - - - - - Export - 导出 - - - - By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period - 默认播放异步内容,定时时间段内播放同步HDMI-IN端口输入内容 - - - - - Apply - 应用 - - - - Readback - 回读 - - - - SYNC HDMI - 同步模式 - - - - Start Time - 开始时间 - - - - End Time - 结束时间 - - - - SUN - 星期日 - - - - MON - 星期一 - - - - TUE - 星期二 - - - - WED - 星期三 - - - - THU - 星期四 - - - - FRI - 星期五 - - - - SAT - 星期六 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - - On - - - - - SyncSchedule (*.syncs) - - - - - Save File - 保存文件 - - - - Sync Schedule (*.syncs) - - - - - - Tip - 提示 - - - - - NoSelectedController - 请先选择大屏幕 - - - - SetTimingHdmiInTask - 设置同步模式定时任务 - - - - GetTimingHdmiInTask - 获取同步模式定时任务 - - - - - Success - 成功 - - - - - failed - 失败 - - - - ControlHdmiWidget - - - HDMI Configuration - 画面输入源配置 - - - - Manual - 手动 - - - - Schedule - 定时 - - - - - Tip - 提示 - - - - - NoSelectedController - 请先选择大屏幕 - - - - - SyncSwitch - 切换同步模式 - - - - - AnSyncSwitch - 切换异步模式 - - - - - IsSync - 回读同异步模式 - - - - Error - 错误 - - - - HDMI IN - 同步 - - - - Async - 异步 - - - - Readback - 回读 - - - - ControlNetConfigWidget - - - Wire Enther(RJ45) Configuration - 有线网配置 - - - - - DHCP - - - - - - Specify IP - 指定IP - - - - - IP Address - IP地址 - - - - Mask Address - 子网掩码 - - - - - Gateway - 网关 - - - - - DNS Address - DNS地址 - - - - - - - - - - Set - 设置 - - - - - - - - - Readback - 回读 - - - - - WIFI Configuration - WiFi配置 - - - - - WiFi On/Off - WiFi使能 - - - - Input Ap name - 输入热点名称 - - - - - 4G/5G Configuration - 蜂窝数据配置 - - - - - Open 4G/5G - 启用蜂窝数据 - - - - APN: - - - - - - Get cellular network status information - 获取蜂窝网络状态信息 - - - - - Check SIM can automatically match to MCC, and then select carrier get apn param,if not found carrier,you can check the CUSTOM checkbox,then enter custom param. - 通过获取状态按钮可以自动匹配国家码MCC,然后选择“运营商”可获取到响应的APN信息,如果找不到运营商,可以选中“自定义”复选框,然后手动输入APN信息。 - - - - - Readback APN Info - 回读APN信息 - - - - - Set Apn Info,Check SIM can automatically match to MCC, and then select carrier get apn param - 设置Apn信息 - - - - - CUSTOM - 自定义 - - - - - Check SIM - 查询SIM信息 - - - - - - -> - - - - - - Country ID(mcc): - 国家码(mcc): - - - - - Carrier Name - 运营商 - - - - - APN: - 运营商APN: - - - - - APN(Required) - APN(必填) - - - - - User: - 用户名: - - - - - - - Not required - 非必填 - - - - - Password: - 密码: - - - - Set Apn:iot.cargo - - - - - - Flight Mode - 飞行模式 - - - - - WiFi name - WiFi名称 - - - - - - - Password - 密码 - - - - - - - Input password - 输入密码 - - - - - Scan - 扫描 - - - - - Ap Mode - AP使能 - - - - Ap name - 热点名称 - - - - OFF - - - - - ON - - - - - AP name - 热点名称 - - - - Subnet mask - 子网掩码 - - - - Input ap name - 输入AP名称 - - - - - - - - - - - - - - - Success - 成功 - - - - - - - - - - - - - - - failed - 失败 - - - - - - - Tip - 提示 - - - - - NoSelectedController - 请先选择大屏幕 - - - - - SetEthernet - 设置有线网 - - - - - - - - - - - Attention - 注意 - - - - Please input IP address! - 请输入IP地址! - - - - Your IP Address is Invalid! - IP地址无效! - - - - Please input Mask address! - 请输入子网掩码地址! - - - - Your Mask Address is Invalid! - 掩码地址无效! - - - - Please input Gateway address! - 请输入网关地址! - - - - Your Gateway Address is Invalid! - 网关地址无效! - - - - Please input DNS address! - 请输入DNS地址! - - - - Your DNS Address is Invalid! - DNS地址无效! - - - - - GetEthernet - 获取有线网配置 - - - - DHCP IP - 动态DHCP IP - - - - STATIC IP - 静态IP - - - - Error - 错误 - - - - - - - - - SignalPower - 信号强度 - - - - - ConfigurationWiFi - 配置WiFi - - - - IsPortableHotSpot - 获取热点和WiFi模式 - - - - GetWifiList - 扫描WiFi - - - - ConfigurationHotSpot - 配置热点 - - - - GetCurrentAPN - 获取APN信息 - - - - - GetSIMStatus - 获取SIM状态 - - - - SetAPN - 设置APN - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - 状态: - 状态: - - - - 未知 - 未知 - - - - 锁定状态,需要用户的PIN码解锁 - 锁定状态,需要用户的PIN码解锁 - - - - 锁定状态,需要用户的PUK码解锁 - 锁定状态,需要用户的PUK码解锁 - - - - 锁定状态,需要网络的PIN码解锁 - 锁定状态,需要网络的PIN码解锁 - - - - 就绪 - 就绪 - - - - no checked sim card - 检测不到sim卡 - - - - 国家码: - 国家码: - - - - 号码: - 号码: - - - - 用户: - 用户: - - - - 信号: - 信号: - - - - 信号正常 - 信号正常 - - - - 不在服务区 - 不在服务区 - - - - 仅限紧急呼叫 - 仅限紧急呼叫 - - - - 射频已经关闭 - 射频已经关闭 - - - - 网络: - 网络: - - - - 网络类型未知 - 未知 - - - - GPRS网络 - GPRS - - - - EDGE网络 - EDGE - - - - UMTS网络 - UMTS - - - - CDMA网络,IS95A 或 IS95B. - CDM - - - - EVDO网络, revision 0. - EVDO,revision 0. - - - - EVDO网络, revision A. - EVDO,revision A. - - - - 1xRTT网络 - 1xRTT - - - - HSDPA网络 - HSDPA - - - - HSUPA网络 - HSUPA - - - - HSPA网络 - HSPA - - - - 漫游: - 漫游: - - - - Yes - - - - - No - - - - - 数据连接状态: - 数据连接状态: - - - - 断开 - 断开 - - - - 正在连接 - 正在连接 - - - - 已连接 - 已连接 - - - - 暂停 - 暂停 - - - - 数据活动休眠状态: - 数据活动休眠状态: - - - - 活动,但无数据发送和接收 - 活动,但无数据发送和接收 - - - - 活动,正在接收数据 - 活动,正在接收数据 - - - - 活动,正在发送数据 - 活动,正在发送数据 - - - - 活动,正在接收和发送数据 - 活动,正在接收和发送数据 - - - - 休眠状态 - 休眠状态 - - - - 信号强度: - - - - - SetSwitchSimData - 设置4G/5G开关 - - - - ContrFlightMode - 配置飞行模式 - - - - GetFlightModeState - 获取飞行模式状态 - - - - ControlPowerManual - - - Form - Form - - - - - POWER - 开关 - - - - - - Readback - 回读 - - - - OFF - - - - - ON - - - - - - Tip - 提示 - - - - - NoSelectedController - 请先选择大屏幕 - - - - IsScreenOn - 读取开关状态 - - - - - - SetScreenOn - 设置电源 - - - - - - - Success - 成功 - - - - - on - - - - - - - - failed - 失败 - - - - - off - - - - - - SetScreenOff - 配置屏幕开关 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - ControlPowerSchedule - + Form Form - + Edit area 编辑区 - - + + Add 添加 - - + + Delete 删除 - - + + Clear - 清除 + 清空 - - + + Import 导入 - - + + Export 导出 - + It is power off state outside the schedule time period 定时时间段内显示屏开启,其他时间段为关屏状态 - + Send command 指令区 - - + + Apply 应用 - + Clear Schedule 清除定时 - + Readback 回读 - + Power On State 屏开关状态 - + Start Time 开始时间 - + End Time 结束时间 - + SUN 星期日 - + MON 星期一 - + TUE 星期二 - + WED 星期三 - + THU 星期四 - + FRI 星期五 - + SAT 星期六 - - + + DeviceItem OnProHttpResponse 解析json文件错误! - - + + On - - + + PowerSchedule (*.pjs) 开关屏定时(*.pjs) - + Save File 保存文件 - - - + + + Tip 提示 - - - + + + NoSelectedController 请先选择大屏幕 - - + + Tip Info 提示 - - + + Clear schedule task? 取消计划任务? - - + + CleanTimingScreenTask 取消计划任务 - + SetTimingScreenTask 设置屏幕定时开关任务 - - - - + + + + Success 成功 - - - - + + + + failed 失败 - + GetTimingScreenTask 获取屏幕定时开关任务 @@ -1411,678 +274,378 @@ ControlPowerWidget - - Form - Form + + + Off + - - + + + On + + + + + + Tip + 提示 + + + + + NoSelectedController + 请先选择大屏幕 + + + + + SetScreenOn + 打开屏幕电源 + + + + + SetScreenOff + 关闭屏幕电源 + + + + + IsScreenOn + 读取开关状态 + + + Power Configuration 开关屏控制 - - + Manual 手动 - - + Schedule 定时 + + + Power + 电源 + + + + Readback + 回读 + ControlTestWidget - + Form Form - - + + Test Screen 测试屏幕 - - + + Line test 线条测试 - - - - - - - + + + + + + + Red - - - - - - - + + + + + + + Green 绿 - - - - - - - + + + + + + + Blue - - - - - - - + + + + + + + White - - + + Vertical 竖线 - - + + Slash 斜线 - - - + + + Horizontal 横线 - - - - + + + + Speed 速度 - - + + ms(>10) 毫秒(>10) - - + + Line Distance 线距 - + px 像素 - - - - - + + + + + Test 测试 - - + + Gradation test 灰度测试 - - + + Only the gray value is displayed 只显示颜色值 - + (>10) - - + + GrayValue 灰度值 - + (0-255) - - + + Color test 颜色测试 - - + + Gradient 渐变 - + 8 8 - + 2 2 - + 3 3 - + 6 6 - + 4 4 - + 5 5 - + 1 1 - + 9 9 - + 7 7 - + 0 0 - - + + Clear - 清除 + 清空 - - + + Reset 循环 - - - - + + + + Anycast 点播 - - + + Stop 停止 - - - - - - - - + + + + + + + + Tip 提示 - - - - - + + + + + NoSelectedController 请先选择大屏幕 - - - + + + StartTest 开始测试 - - - - + + + + Success 成功 - - - - + + + + failed 失败 - + StopTest 停止测试 - + loopback mode 循环模式 - + Connect timeout 连接超时 - + Reset loop mode 设置循环 - - + + success 成功 - - - DeviceItem OnProHttpResponse 解析json文件错误! - 解析json文件错误! - - - - CtrlVerifyClockPanel - - - Form - Form - - - - English - - - - - 中文 - - - - - Verify Clock Configuration - 校准时间 - - - - Verify to Computer time - 校准到计算机时间 - - - - - Cur time of controller - LED显示屏设备当前时间 - - - - LAN - 局域网 - - - - (min/time) - (分钟/次) - - - - Sync identificationCode - 同步识别码 - - - - - identification code - 同步识别码 - - - - - Time offset(msec) - 时间偏移(毫秒) - - - - - Brightness - 屏体亮度 - - - - - Volume - 音量 - - - - - Screen on/off - 屏幕开关 - - - - - Slave - - - - - Master - - - - - - NTP Server - NTP服务器 - - - - - - - NTP Server address - NTP服务器地址 - - - - - - - TimeZone - 时区 - - - - - - - - - - - - - - - Set - 设置 - - - - - Language: - 语言: - - - - - Enable Synchronous playing - 使能同步画面功能 - - - - Lora - - - - - GPS - - - - - NTP - - - - - Time zone - 时区 - - - - - - - Sync time interval - 同步时间间隔 - - - - Verify clock configuration - 校准时间 - - - - - - - - - - - - - - Readback - 回读 - - - - Master - - - - - Sync clock to computer time - 校准时钟到计算机时间 - - - - Identification Code - 识别码 - - - - - - - - - - - - - - Success - 成功 - - - - - - - - - - - - - - failed - 失败 - - - - SetNtpServer - 设置NTP服务 - - - - MasterSwitch - 设置为主设备 - - - - SlaveSwitch - 设置为从设备 - - - - IsMasterSlave - 回读主从身份 - - - - GetControllerDate - 获取日期时间 - - - - SetingSyncMethod - 设置同步方法 - - - - SyncTime - 校准时间 - - - - GetNtpServer - 获取NTP服务信息 - - - - GetingSyncMethod - 获取同步方式 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - - - - - SetTimezone - 设置时区 - - - - ControlVolumeManual - - - Form - Form - - - - Volume(0-15) - 音量(0-15) - - - - - - Readback - 回读 - - - - SetVolume - 音量调节 - - - - - - Success - 成功 - - - - - - failed - 失败 - - - - Volume(min:0-max:15) - 音量(最小値:0-最大値:15) - - - - GetVolume - 获取当前音量 - - - - + + DeviceItem OnProHttpResponse 解析json文件错误! 解析json文件错误! @@ -2090,174 +653,174 @@ ControlVolumeSchedule - + Defalut volume tip - - + + Add 添加 - - + + Delete 删除 - - + + Clear - 清除 + 清空 - + Default Volume 默认音量 - + (0-15) - - + + Import 导入 - - + + Export 导出 - - + + Apply 应用 - + Readback 回读 - + Volume value 音量值 - + Start Time 开始时间 - + End Time 结束时间 - + SUN 星期日 - + MON 星期一 - + TUE 星期二 - + WED 星期三 - + THU 星期四 - + FRI 星期五 - + SAT 星期六 - + Default volume tip 提醒:定时时间段以外的时间显示屏为默认亮度 - + Default volume 默认音量值 - - + + DeviceItem OnProHttpResponse 解析json文件错误! 解析json文件错误! - + 10 10 - - + + Volume Schedule (*.vols) - + Save File 保存文件 - - + + Tip 提示 - - + + NoSelectedController 请先选择大屏幕 - + SetAutoVolumeTask 配置定时音量表 - - + + Success 成功 - - + + failed 失败 - + GetAutoVolumeTask 获取定时音量表 @@ -2265,1187 +828,2504 @@ ControlVolumeWidget - - Form - Form + + + Tip + 提示 - - + + + NoSelectedController + 请先选择大屏幕 + + + + + SetVolume + 音量调节 + + + + + GetVolume + 获取当前音量 + + + Volume Control 音量调节 - - + Manual 手动 - - + Schedule 定时 + + + Volume + 音量 + + + + Readback + 回读 + CtrlAdvancedPanel - - Advanced parameters + + Advanced 高级参数 - + Screen Width(pixel) 屏幕宽(像素) - + Width - - + + Height - - - - - - - + + + + + + + + + + + + + + + Set 设置 - + Alias 别名 - + Web Server Address: Web服务器地址: - + www.m2mled.net - + www.ledaips.com - + https://www.taxihub.cn:2340 - + https://www.ledaips.com:2340 - + https://www.36taxi.com:2340 - + www.tlzxled.com - + + MCU Uploading + 正在上传单片机 + + + + Traffic screen settings + 交通屏设置 + + + + Setting protocol ... + 正在设置协议 ... + + + + Set protocol + 设置协议 + + + + Getting protocol ... + 正在回读协议 ... + + + + Get protocol + 回读协议 + + + + + Port + 端口 + + + Realtimer Server Address: Realtimer地址: - + + Firmware Management + 固件管理 + + + + update or uninstall + 更新或卸载 + + + Clear - 清除 + 清空 - - Apk upgrade - Apk升级 - - - + Check Apk 检查Apk - + Uninstall 卸载 - + Running check 运行状态监测 - - FPGA version check - FPGA版本查询 - - - - Sync FPGA version - 同步FPGA版本 - - - - Restart led controller system + + Restart 重启 - + Check Log 查看日志 - + Start LedSet4 使用 LedSet4.0 配置LED模组(Apk Display2.0以上版本) - + Open ADB 打开ADB调试功能 - + Post Custom JSON Post Custom JSON - - - - - - - - + + + + + + + + Clear Program 清除节目 - + www.ledokcloud.com/realtime - - M80 configuration - M80配置 + + Config + 配置 - + Refresh 刷新 - + Restore to default 恢复默认值 - + Taxi top screen configuration 车顶有无客电平配置 - + + Service:High Out of service:Low 有客:高电平 无客:低电平 - + + Service:Low Out of service:High 有客:低电平 无客:高电平 - + Start LedSet3.0 configure LED module 使用LedSet3.0配置LED模组(厂家专业人员使用) - + Binding *.ic account indentity voucher 绑定taxihub平台用户身份凭证 - + Rotate 旋转 - - 0 degrees - 0度 - - - - 90 degrees - 90度 - - - - 180 degrees - 180度 - - - - 270 degrees - 270度 - - - + Min brightness 最低亮度 - - (min:1) - (最小:1) - - - - - + + + Readback 回读 - - - + Send 发送 - + Max brightness 最高亮度 - - (max:255) - (最高:255) - - - - + + SetScreenSize 设置屏幕像素尺寸 - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Success 成功 - + Compant ID: 公司ID: - - FPGA Upgrade - FPGA升级 - - - + Compant ID 公司ID - + InputWebServerAddressTip 请输入Web服务器地址 - + InputCompanyIdTip 请输入公司ID - + Do you want to modify webserveraddress and companyId? 是否确认配置服务器地址和公司ID? - - - - - - - - - - - - - - - - - - - - - - failed - 失败 - - - - + + SetOnlineAddr 设置web服务器地址 - + + ClearRealtimeServer 清除 - - InputRealTimeAddressTip - 请输入RealTimer地址 - - - + + SetRealtimeServer 设置RealTimer地址 - - - - + + + + Tip Info 提示 - - - + + + Can not find LedSet3.0.exe,down you need download and install it 找不到LedSet3.0.exe,确认下载并安装 - + + RestartAndroid 重启 - - FPGA Version - FPGA版本 - - - - + + running 正在运行 - - + + no running 没有运行 - + Check Apk Version 查询已安装apk版本 - - + + UninstallSoftware 卸载 - - - IsSoftwareRunning + + + Check apk running status 监测APK运行状态 - - apk package (*.rpd) - - - - - CheckHardwareVersions - 查询FPGA版本 - - - - - - SynchronousHardwareVersion - 同步FPGA硬件版本 - - - - Check Screen untile fpga update finished - 观察屏幕升级进度直到升级成功 - - - + + OpenAdb 打开ADB调试功能 - + indentity voucher (*.ic) 身份凭证(*.ic) - - - - - + + + + + InvokeTaxiAppFunction 绑定证书 - - Json format is error! - - - - - + + AliIotSetting - - apk package (*.apk *.zip) - - - - + Software Version Info 软件版本信息 - + Package 包名 - + Version 版本 - - - UpgradeSoftware - 升级固件 - - - - This screen is encrypted,Please decrypt and upgrade APK! - 此屏幕已加密,请解密并升级APK! - - - - + + Package name is null 包名为空 - + Clearing Program 正在清除节目 - - - - + + + + Timeout 超时 - - - - + + + + Failed 失败 - + Getting Log 正在获取日志 - - - - - - - - - + + + + + + + + + + + Error 错误 - + + Setting Timing Reboot + 正在设置定时重启 + + + + Set Timing Reboot + 设置定时重启 + + + + Getting Timing Reboot + 正在获取定时重启 + + + + Get Timing Reboot + 获取定时重启 + + + + totalResolution + 包括行场数的分辨率 + + + + strCurDisplayResolution + 当前显示屏分辨率 + + + + File not exist + 文件不存在 + + + + Uploading + 正在上传 + + + + + Set Display Mode + 设置显示模式 + + + + + Get Display Mode + 获取显示模式 + + + + + Set Screen Offset + 设置屏幕偏移 + + + + + Get Screen Offset + 获取屏幕偏移 + + + Open file Failed 文件打开失败 - + Setting Wallpaper 正在设置系统桌面背景 - - + + Set Wallpaper 设置系统桌面背景 - + System Updating 系统升级中 - - + + System Update 系统升级 - + + Getting MCU Version + 正在获取单片机版本 + + + + + MCU Version + 单片机版本 + + + Select File 选择文件 - + Setting player background 正在设置播放器背景 - - + + Set player background 设置播放器背景 - + Clearing player background 正在清除播放器背景 - - - - - - - - + + + + + + + + Clear player background 清除播放器背景 - + Setting Baud Rate 正在设置波特率 - + Set Baud Rate 设置波特率 - + Getting Baud Rate 正在获取波特率 - + Get Baud Rate 获取波特率 - + + Text is empty + 文本为空 + + + + Json Parse Error + + + + + Json isn't an Object + + + + + Setting card work mode ... + 正在设置控制卡工作模式 ... + + + + Set card work mode + 设置控制卡工作模式 + + + + Getting card work mode ... + 正在回读控制卡工作模式 ... + + + + Get card work mode + 回读控制卡工作模式 + + + + Resolution Config + 分辨率配置 + + + + Full screen + 全屏 + + + + Part + 局部 + + + + Display Mode + 显示模式 + + + + Screen Position + 屏幕位置 + + + + Offset + 偏移 + + + Hidden Settings 隐藏的设置 - + Click right button to hide 点击右键隐藏 - + + + Update MCU + 更新单片机 + + + + Get MCU Version + 获取单片机版本 + + + Baud Config 波特率配置 - + Model 设备型号 - + Uart 串口节点 - + Baud 波特率 - + + + + + + Get 获取 - - - - + + Timing Reboot + 定时重启 + + + + Protocol + 协议 + + + + Server + 服务端 + + + + Client + 客户端 + + + + SetScreenRotation 设置屏幕旋转 - + + SetMinBrightness 设置最小的亮度值 - + + SetMaxBrightness 设置亮度最大值 - + + GetMinBrightness 获取亮度最小值 - + + GetMaxBrightness 获取亮度最大值 - + + + Card work mode + 控制卡工作模式 + + + + SetSpecialResolution 设置分辨率 - + + GetSpecialResolution 读取分辨率 - + + CleanDisplayScreenSize 恢复默认分辨率 - + + SetHighForBusy 设置有无客电平 - + + GetStateForBusy 获取有无客电平 - - install start... - 开始安装... - - - + InputAliasTip 请输入别名 - - + + SetCardAlias 设置别名 - - Uploadding - 上传 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tip 提示 - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NoSelectedController 请先选择大屏幕 - + InputWidthTip 请输入正确的宽度像素值 - + InputHeightTip 请输入正确的高度像素值 - + Password is error 密码错误 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - 解析json文件错误! - CtrlBrightPanel - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + Tip 提示 - - - - - - - - - - - + + + + + + + + + + + NoSelectedController 请先选择大屏幕 - - + + SetBrightnessSensitivity 设置亮度传感器灵敏度 - - + + GetBrightnessSensitivity 获取亮度传感器灵敏度 - - + + SetMinBrightness 设置最小的亮度值 - - + + GetMinBrightness 获取亮度最小值 - - + + NeedSelectSensorTypeTip 请先选择传感器类型 - + Open file dialog 打开文件 - + Not found current worksheet 没找到当前工作表 - - + + SensorBrightnessTable 设置亮度传感器配置表 - + GetSensorBrightnessTable 获取传感器亮度配置表 - + no sensorBrightnessTable 控制卡没有发现亮度配置表 - + Save file 保存 - - + + GetCurrentSensorBrightness 获取当前亮度 - - + + SetBrightness 设置亮度 - + GetBrightness 获取亮度值 - + Brightness 屏体亮度 - + Import File 导入文件 - - + + BrightnessSchedule (*.bjs) - + Save File 保存文件 - + BrightnessValue 亮度值 - + Start Time 开始时间 - + End Time 结束时间 - - + + SetAutoBrightnessTask 发送定时亮度表 - + GetAutoBrightnessTask 获取定时亮度表 - - - - + + Error 错误 - + Brightness Configuration 亮度配置 - + Auto 自动 - + Manual 手动 - + Schedule 定时 - + + Adapt to Old Devices + 适配旧设备 + + + BrightTip1 如果最大亮度为64,则最小亮度可以配置为1%或适当的值;如果最大亮度为255,则最小亮度必须配置为36%或更高,否则亮度将很低。 - + BrightTip2 上传文件时,请确认选择正确的传感器类型,否则无效! - + Sensitivity 灵敏度 - + Minbrightness 最小亮度值 - - - + + + Set 设置 - + Upload 上传配置文件 - - - - + + + + Readback 回读 - + ReadbackTable 回读 - + Refresh 刷新 - + Cur Brigntness 当前亮度 - + Brightness value 亮度值 - + Default brightness 默认亮度 - + Add 添加 - + Clear 清空 - + Delete 删除 - + Import 导入 - + Export 导出 - + Apply 应用 - + Default brightness tip - 提示:该设定时间内为设定亮度,设定时间外为默认亮度。例如设定默认亮度为80,设定亮度为180,时间范围是8:00-17:00,则时间范围内亮度为180,其他时间内为默认亮度80! + 提示:时间范围内为设定亮度,时间范围外为默认亮度。例如默认亮度为50%,设定亮度为80%,时间范围是8:00-17:00,则时间范围内亮度为80%,其他时间为默认亮度50% + + + + CtrlHdmiPanel + + + HDMI Configuration + 画面输入源配置 + + + + Manual + 手动 + + + + Schedule + 定时 + + + + + + + Tip + 提示 + + + + + + + NoSelectedController + 请先选择大屏幕 + + + + + SyncSwitch + 切换同步模式 + + + + + AnSyncSwitch + 切换异步模式 + + + + IsSync + 回读同异步模式 + + + + Import File + 导入文件 + + + + Save File + 保存文件 + + + + + Sync Schedule + 同步定时任务 + + + + + SetTimingHdmiInTask + 设置同步模式定时任务 + + + + GetTimingHdmiInTask + 获取同步模式定时任务 + + + + + Async + 异步 + + + + + Readback + 回读 + + + + Start Time + 开始时间 + + + + End Time + 结束时间 + + + + SUN + 星期日 + + + + MON + 星期一 + + + + TUE + 星期二 + + + + WED + 星期三 + + + + THU + 星期四 + + + + FRI + 星期五 + + + + SAT + 星期六 + + + + Add + 添加 + + + + + Apply + 应用 + + + + Clear + 清空 + + + + Delete + 删除 + + + + Import + 导入 + + + + Export + 导出 + + + + By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period + 默认播放异步内容,定时时间段内播放同步HDMI-IN端口输入内容 + + + + CtrlNetworkPanel + + + Wire Enther(RJ45) Configuration + 有线网配置 + + + + DHCP + + + + + Specify IP + 指定IP + + + + IP Address + IP地址 + + + + Gateway + 网关 + + + + DNS Address + DNS地址 + + + + + + Set + 设置 + + + + + + + Readback + 回读 + + + + WIFI Configuration + WiFi配置 + + + + WiFi Mode + 使用WiFi + + + + Cellular Config + 蜂窝数据配置 + + + + Enable Cellular Data + 启用蜂窝数据 + + + + Get cellular network status information + 获取蜂窝网络状态信息 + + + + Through the check status button + 通过“获取状态”按钮可以自动匹配国家码,然后选择“运营商”可获取到相应的APN信息。 + + + + Set APN Info + 设置APN信息 + + + + Country ID(mcc): + 国家码(mcc): + + + + + Carrier Name + 运营商 + + + + APN(Required) + APN(必填) + + + + Flight Mode + 飞行模式 + + + + WiFi name + WiFi名称 + + + + + + Password + 密码 + + + + + Input password + 输入密码 + + + + Scan + 扫描 + + + + Ap Mode + 使用热点 + + + + OFF + + + + + ON + + + + + AP name + 热点名称 + + + + Subnet mask + 子网掩码 + + + + Input ap name + 输入AP名称 + + + + + + + + + + + + + + + Tip + 提示 + + + + + + + + + + + + + + NoSelectedController + 请先选择大屏幕 + + + + + SetEthernet + 设置有线网 + + + + + + + + + + + Attention + 注意 + + + + Please input IP address! + 请输入IP地址! + + + + Your IP Address is Invalid! + IP地址无效! + + + + Please input Mask address! + 请输入子网掩码地址! + + + + Your Mask Address is Invalid! + 掩码地址无效! + + + + Please input Gateway address! + 请输入网关地址! + + + + Your Gateway Address is Invalid! + 网关地址无效! + + + + Please input DNS address! + 请输入DNS地址! + + + + Your DNS Address is Invalid! + DNS地址无效! + + + + + GetEthernet + 获取有线网配置 + + + + DHCP IP + 动态DHCP IP + + + + STATIC IP + 静态IP + + + + + ConfigurationWiFi + 配置WiFi + + + + + IsPortableHotSpot + 获取热点和WiFi模式 + + + + GetWifiList + 扫描WiFi + + + + + ConfigurationHotSpot + 配置热点 + + + + success + 成功 + + + + WifiName + Wifi名称 + + + + ApName + 热点名称 + + + + + GetCurrentAPN + 获取APN信息 + + + + GetSIMStatus + 获取SIM状态 + + + + + SetAPN + 设置APN + + + + 状态: + 状态: + + + + 未知 + 未知 + + + + 锁定状态,需要用户的PIN码解锁 + 锁定状态,需要用户的PIN码解锁 + + + + 锁定状态,需要用户的PUK码解锁 + 锁定状态,需要用户的PUK码解锁 + + + + 锁定状态,需要网络的PIN码解锁 + 锁定状态,需要网络的PIN码解锁 + + + + 就绪 + 就绪 + + + + no checked sim card + 检测不到sim卡 + + + + 国家码: + 国家码: + + + + 号码: + 号码: + + + + 用户: + 用户: + + + + 信号: + 信号: + + + + 信号正常 + 信号正常 + + + + 不在服务区 + 不在服务区 + + + + 仅限紧急呼叫 + 仅限紧急呼叫 + + + + 射频已经关闭 + 射频已经关闭 + + + + 网络: + 网络: + + + + 网络类型未知 + 未知 + + + + GPRS网络 + GPRS + + + + EDGE网络 + EDGE + + + + UMTS网络 + UMTS + + + + CDMA网络,IS95A 或 IS95B. + CDM + + + + EVDO网络, revision 0. + EVDO,revision 0. + + + + EVDO网络, revision A. + EVDO,revision A. + + + + 1xRTT网络 + 1xRTT + + + + HSDPA网络 + HSDPA + + + + HSUPA网络 + HSUPA + + + + HSPA网络 + HSPA + + + + 漫游: + 漫游: + + + + Yes + + + + + No + + + + + 数据连接状态: + 数据连接状态: + + + + 断开 + 断开 + + + + 正在连接 + 正在连接 + + + + 已连接 + 已连接 + + + + 暂停 + 暂停 + + + + 数据活动休眠状态: + 数据活动休眠状态: + + + + 活动,但无数据发送和接收 + 活动,但无数据发送和接收 + + + + 活动,正在接收数据 + 活动,正在接收数据 + + + + 活动,正在发送数据 + 活动,正在发送数据 + + + + 活动,正在接收和发送数据 + 活动,正在接收和发送数据 + + + + 休眠状态 + 休眠状态 + + + + 信号强度: + + + + + User + 用户 + + + + Type + 类型 + + + + Server + 服务端 + + + + Port + 端口 + + + + Proxy + 代理 + + + + MMS Port + 彩信端口 + + + + MMS Proxy + 彩信代理 + + + + + SetSwitchSimData + 设置4G/5G开关 + + + + + ContrFlightMode + 配置飞行模式 + + + + + GetFlightModeState + 获取飞行模式状态 + + + + CtrlPwdPanel + + + Set Password + 安全配置 + + + + Original password + 原始密码 + + + + original password + 原始密码 + + + + + New password + 新密码 + + + + Repeat new password + 重复输入 + + + + + + + Set encryption + 加密 + + + + Cancel encryption + 取消加密 + + + + Enter again + 再次输入 + + + + + + + + + + + + Tip + 提示 + + + + + NoSelectedController + 请先选择大屏幕 + + + + + InputOriginalPasswordTip + 请输入原始密码 + + + + InputNewPasswordTip + 请输入新密码 + + + + InputRepeatPasswordTip + 请重复输入新密码 + + + + InputRepeatPasswordNotSameTip + 两次输入的密码不一致 + + + + Tip Info + 提示 + + + + After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? + 设置密码后,请记住密码并记录。如果忘记密码,设备将无法运行。确实要继续此操作吗? + + + + + + + SetControllerPassword + 设置加密 + + + + + Error + 错误 + + + + + Success + 成功 + + + + + + Modify password + 修改密码 + + + + + + + OriginalPasswordErrorTip + 原始密码错误 + + + + CtrlVerifyClockPanel + + + Verify Clock Configuration + 校准时间 + + + + + Verify to Computer time + 校准到计算机时间 + + + + Cur time of controller + LED显示屏设备当前时间 + + + + + LAN + 局域网 + + + + + + + + + + + + + + Tip + 提示 + + + + + + + + + + + + + + NoSelectedController + 请先选择大屏幕 + + + + screenSwitch + 开关屏 + + + + + + YES + + + + + + + NO + + + + + volume + 音量 + + + + brightness + 亮度 + + + + + identificationCode + 识别码 + + + + + delaySync + 时间偏移 + + + + + msec + 毫秒 + + + + + + + OtherSyncItem + 其他同步项 + + + + + + + lastSynchronousTime + 上次同步时间 + + + + checkNtpTime + 同步间隔 + + + + Lora identity + Lora身份 + + + + (min/time) + (分钟/次) + + + + identification code + 同步识别码 + + + + Time offset(msec) + 时间偏移(毫秒) + + + + Brightness + 屏体亮度 + + + + Volume + 音量 + + + + Screen on/off + 屏幕开关 + + + + + Slave + + + + + NTP Server + NTP服务器 + + + + + NTP Server address + NTP服务器地址 + + + + TimeZone + 时区 + + + + + + + + Set + 设置 + + + + Language: + 语言: + + + + Enable Synchronous playing + 使能同步画面功能 + + + + + Sync time interval + 同步时间间隔 + + + + + + + + Readback + 回读 + + + + + Master + + + + + Identification Code + 识别码 + + + + + SetNtpServer + 设置NTP服务 + + + + + MasterSwitch + 设置为主设备 + + + + + SlaveSwitch + 设置为从设备 + + + + IsMasterSlave + 回读主从身份 + + + + + GetControllerDate + 获取日期时间 + + + + + SetingSyncMethod + 设置同步方法 + + + + + SyncTime + 校准时间 + + + + + GetNtpServer + 获取NTP服务信息 + + + + + GetingSyncMethod + 获取同步方式 + + + + + SetTimezone + 设置时区 Def - - - + Connection Timeout 连接超时 - - - - - - - + + + + + Device replied 设备回复 - - + + + Success 成功 - - - - Error - 错误 - - - - Tip Info - 提示 - - - - + Fail 失败 @@ -3453,666 +3333,314 @@ DeviceCtrlPanel - - - + + + + Current Screen 当前屏幕 - - + + none - - + + Clear 清空 - - - single screen operation - 单屏操作 - - - + + Multi screen operation 多屏操作 - + + selected num 选中数目 - + Brightness Adjustment 亮度调节 - + Power Control 电源控制 - + Net Config 网络配置 - - Time Synchronization + + Time Sync 对时管理 - + Video source 同异步配置 - - Encrypt - 加密配置 + + Password + 设置密码 - - Advanced parameters + + Advanced 高级设置 - - Current Screen: - 当前屏幕: - - - + Test 测试 - - Volume Adjustment + + Volume Adj. 音量调节 DeviceItem - + GetScreenDetailInfo 更多信息 - + ReadbackPic 回读画面 - + Input password 输入密码 - + GetScreenshotFull 回读画面 - + cur brightness: 当前亮度: - + android version: 安卓版本: - + IMEI: - + HardWard Version: FPGA版本: - + MAX Brightness level: 亮度等级: - + Android OS Resolution: 安卓分辨率: - + Firmware Version: 固件版本: - + Player Version: 播放器固件版本: - + Detail Info 详细信息 - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + receive 接收 - - SetScreenOn - 设置电源 - - - + AliIotSetting - - + + GetScreenStatus 获取屏幕状态 - - + + Status 状态 - + Tip Info 提示 - + password is wrong 密码错误 - + GetBrightness 获取亮度值 - - - + brightness 亮度 - - MasterSlaveSwitch - 配置主从身份 - - - - SetBrightness - 设置亮度 - - - - - SetMinBrightness - 设置最小的亮度值 - - - - GetBrightnessSensitivity - 获取亮度传感器灵敏度 - - - - sensitivity - 灵敏度 - - - - GetMinBrightness - 获取亮度最小值 - - - - SetSensorBrightnessTable - 配置传感器参数表 - - - - SetSwitchWiFi - 设置WiFi开关 - - - - ConfigurationWiFi - 配置WiFi - - - - ConfigurationHotSpot - 配置热点 - - - - GetSwitchWiFi - 获取WiFi状态 - - - + SetAutoBrightnessTask 发送定时亮度表 - + SetAutoVolumeTask 配置定时音量表 - + SetVolume 音量调节 - + GetVolume 获取当前音量 - + SetTimingScreenTask 设置屏幕定时开关任务 - - GetControllerDate - 获取日期时间 - - - - SetHighForBusy - 设置有无客电平 - - - - - GetStateForBusy - 获取有无客电平 - - - - Service:Low Out of service:High - 有客:低电平 无客:高电平 - - - - Service:High Out of service:Low - 有客:高电平 无客:低电平 - - - - - - IsPortableHotSpot - 获取热点和WiFi模式 - - - - WifiName - Wifi名称 - - - - ApName - 热点名称 - - - + TestScreen 测试屏幕 - + SetOnlineAddr 设置web服务器地址 - + SetRealtimeServer 设置RealTimer地址 - - GetOnlineAddr - 获取web服务器地址 - - - - GetRealtimeServer - 获取realtime服务器地址 - - - - SetNtpServer - 设置NTP服务 - - - - GetNtpServer - 获取NTP服务信息 - - - - SyncTime - 校准时间 - - - - DelPrograms - 清除节目 - - - - SetingSyncMethod - 设置同步方法 - - - + GetCurrentSensorBrightness 获取当前亮度 - + Cur brightness 当前亮度 - - SetSpecialResolution - 设置分辨率 - - - - GetSpecialResolution - 读取分辨率 - - - - totalResolution - 包括行场数的分辨率 - - - - strCurDisplayResolution - 当前显示屏分辨率 - - - - CleanDisplayScreenSize - 恢复默认分辨率 - - - - SetMaxBrightness - 设置亮度最大值 - - - - GetMaxBrightness - 获取亮度最大值 - - - - screenSwitch - 开关屏 - - - - - - YES - - - - - - - NO - - - - - LAN - 局域网 - - - + Connect 连接 - + timeout 超时 - + Anycast 点播 - - + volume 音量 - - - - - - - GetingSyncMethod - 获取同步方式 - - - - - identificationCode - 识别码 - - - - - delaySync - 时间偏移 - - - - - msec - 毫秒 - - - - - - - OtherSyncItem - 其他同步项 - - - - - - - lastSynchronousTime - 上次同步时间 - - - - checkNtpTime - 同步间隔 - - - - Uploadding - 上传 - - - + Success 成功 - + failed 失败 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + success 成功 - - - Lora identity - Lora身份 - - - - Master - - - - - Slave - - - - - SetBrightnessSensitivity - 设置亮度传感器灵敏度 - - - - - + + + on - - - + + + off @@ -4121,116 +3649,116 @@ DevicePanel - + All 总数 总数 - + Online 在线 在线 - - + + Refresh 刷新 刷新 - + Current Screen 当前屏幕 - + none - - - + + + Specify IP 指定IP 指定IP - + Specify IP list 指定IP列表 - + Search 搜索 - - + + Attention 注意 - - + + Please input IP address! 请输入IP地址! - + Cancel 取消 - + Screen ID 屏幕ID - + Screen IP 屏幕IP - + Screen Size 屏幕像素 - + Remark Name - 別名 + 别名 - + readback pic 回读画面 - + send 发送 - + More Info 详细信息 - + Cur Brightness 屏幕当前亮度 - + Power Status 屏幕开关状态 - + Security 加密 @@ -4407,39 +3935,156 @@ - EAudio + EAClock - + Basic Properties 基本属性 - - File - 文件 + + Time Zone + 时区 - + + Custom Dial + 自定义表盘 + + + + Select + 选择 + + + + Select Dail file + 选择表盘图片 + + + + Hour Mark + 时标 + + + + + Circular + 圆形 + + + + + Rectangle + 矩形 + + + + Number + 数字 + + + + + + T + + + + + Min Mark + 分标 + + + + Color + 颜色 + + + + Length + + + + + Width + + + + + Hour Hand + 时针 + + + + Min Hand + 分针 + + + + Sec Hand + 秒针 + + + + Show + 显示 + + + + Text + 文本 + + + Play Properties 播放方式 - + Play Duration 播放时长 - + + s + + + + + EAudio + + + Basic Properties + 基本属性 + + + + File + 文件 + + + + Play Properties + 播放方式 + + + + Play Duration + 播放时长 + + + Select File 选择文件 - + s - + Audio 音频 @@ -4447,233 +4092,373 @@ EBase - + Area 区域(px) - + X - + Y - + W - + H - + Border 边框 - - + + None - + Effect 特效 - + Rotate 旋转 - + Blink 闪烁 - + Speed 速度 - + Slow - + Moderate - + Fast - EEnviron + EDClock - - - - - - - - north - + + MON + 星期一 - - - - - - - - east - + + TUE + 星期二 - - - - - - - - south - + + WED + 星期三 - - - - - - - - west - 西 + + THU + 星期四 - - - Temperature - 温度 + + FRI + 星期五 - - - Humidity - 湿度 + + SAT + 星期六 - - - Noise - 噪音 + + SUN + 星期日 - - Wind Speed - 风速 + + + AM + 上午 - - Wind Direction - 风向 + + + PM + 下午 - + Basic Properties 基本属性 - - Title - 标题 + + Time Zone + 时区 - - Compensation - 补偿 + + Year + - - Wind speed - 风速 + + Month + - - Wind direction - 风向 + + Day + - - Left - 靠左 + + Hour + - - Center - 居中 + + Min. + - - Right - 靠右 + + Sec. + - - Single scroll - 单行滚动 + + Weekly + 星期 - - Speed - 速度 + + Full Year + 四位年 - - ms/pixel - 毫秒/像素 + + 12-Hour + 12小时制 - - Back Color - 背景色 + + Date Style + 日期风格 - + + Time Style + 时间风格 + + + + Display Style + 显示风格 + + + + Multiline + 多行显示 + + + Play Properties 播放方式 - - Refresh Cycle - 刷新周期 - - - - min. - 分钟 - - - + Play Duration 播放时长 - + + s + + + + + EEnviron + + + + + + + + + north + + + + + + + + + + + east + + + + + + + + + + + south + + + + + + + + + + + west + 西 + + + + + Temperature + 温度 + + + + + Humidity + 湿度 + + + + + Noise + 噪音 + + + + Wind Speed + 风速 + + + + Wind Direction + 风向 + + + + Basic Properties + 基本属性 + + + + Title + 标题 + + + + Compensation + 补偿 + + + + Wind speed + 风速 + + + + Wind direction + 风向 + + + + Left + 靠左 + + + + Center + 居中 + + + + Right + 靠右 + + + + Single scroll + 单行滚动 + + + + Speed + 速度 + + + + ms/pixel + 毫秒/像素 + + + + Back Color + 背景色 + + + + Play Properties + 播放方式 + + + + Refresh Cycle + 刷新周期 + + + + min. + 分钟 + + + + Play Duration + 播放时长 + + + s @@ -4681,37 +4466,37 @@ EGif - + Basic Properties 基本属性 - + File 文件 - + Select File 选择文件 - + Play Properties 播放方式 - + Play Duration 播放时长 - + s - + Play Times 播放次数 @@ -4719,73 +4504,73 @@ EMultiWin - + Please add media on the right 请在右边添加媒体,可以加入多个不同媒体,LED显示屏将按列表先后顺序播放 - + Media List 媒体列表 - - - + + + Text 文本 - - - + + + Photo 图片 - - - + + + Video 视频 - - - + + + Gif 动画 - - - + + + DClock 数字时钟 - - - + + + AClock 模拟时钟 - - - + + + Select File 选择文件 - - + + Environment 环境监测 - - + + Timer 计时器 @@ -4793,118 +4578,118 @@ EPhoto - + Basic Properties 基本属性 - + File 文件 - + Select File 选择文件 - + Image Read Error 图片读取错误 - + Play Properties 播放方式 - + Play Duration 播放时长 - - + + s - + Enter Style 入场特效 - + None - + Alpha_In 淡入 - + Moving to left 连续左移 - + Moving to right 连续右移 - + Moving to top 连续上移 - + Move to bottom 连续下移 - + Zoom in 放大 - + Zoom in to left_bottom 左下角放大 - + Zoom in to left_top 左上角放大 - + Zoom in to right_top 右上角放大 - + Zoom in to right bottom 右下角放大 - + Rotate to right 向右旋转 - + Rotate to left 向左旋转 - + Enter Duration 特效时长 - + Images (*.png *.jpg *.jpeg *.bmp) 图片(*.png *.jpg *.jpeg *.bmp) @@ -4912,191 +4697,191 @@ EText - + Enter your text 请输入内容 - + Basic Properties 基本属性 - - Font Color - 字体色 - - - + Back Color 背景色 - + Kerning 字间距 - + Line Spacing 行距 - + PageCount: 总页数: - + page - + Import txt File 导入 txt 文件 - + Select File 选择文件 - + Fail 失败 - + File Open Fail 文件打开失败 - + Play Properties 播放方式 - + Flip 翻页 - + Scroll 滚动 - + Static 静态 - - - + + + Play Duration 播放时长 - + Duration/Page 每页播放时长 - + Effect time 特效时长 - - + + Tip Info 提示 - - + + Effect time cannot be longer than duration time 特效时长不能大于播放时长 - + s - + + Text Color + 文字颜色 + + + + Colorful Text + 炫彩文字 + + + Entrance Effect 入场特效 - + no - + random 随机 - + right to left 连续左移 - + bottom to top 连续上移 - + left to right 连续右移 - + top to bottom 连续下移 - - Head-Tail Connected - 首尾相接 - - - + Head-Tail Spacing 首尾间隔 - + Scroll Style 滚动方向 - + Right -> Left 向左 - + Bottom -> Top 向上 - + Left -> Right 向右 - + Top -> Bottom 向下 - + Scroll Speed 滚动速度 @@ -5104,87 +4889,87 @@ ETimer - + day - + hour - + min - + sec - + Basic Properties 基本属性 - + Count Down 倒计时 - + Count Up 正计时 - + Time 目标时间 - + Day - + Hour - + Min - + Sec - + Multiline 多行显示 - + Text 文本 - + Play Properties 播放方式 - + Play Duration 播放时长 - + s @@ -5192,64 +4977,64 @@ EVideo - + Basic Properties 基本属性 - + File 文件 - + Play Properties 播放方式 - + Play Duration 播放时长 - + Select File 选择文件 - + s - + Play Times 播放次数 - + Video Transcoding 视频转码 - - + + Video Transcoding Progress 视频转码进度 - - + + Error 错误 - + Video 视频 - + Flash 动画 @@ -5257,17 +5042,17 @@ EWeb - + Basic Properties 基本属性 - + Play Duration 播放时长 - + s @@ -5295,10 +5080,93 @@ + + GenTmpThread + + + Preparing ... + 准备中... + + + + MON + 星期一 + + + + TUE + 星期二 + + + + WED + 星期三 + + + + THU + 星期四 + + + + FRI + 星期五 + + + + SAT + 星期六 + + + + SUN + 星期日 + + + + AM + 上午 + + + + PM + 下午 + + + + day + + + + + hour + + + + + min + + + + + sec + + + + + Create json ... + 生成json... + + + + Scan program ... + 扫描节目... + + LoColorSelector - + Transparent 透明 @@ -5341,186 +5209,230 @@ MainWindow - + Language 语言 - + Help 帮助 - - + + Check for updates 检查更新 - - + + firmware manager 固件管理 - - - Software Configuration + + + Software Config 软件配置 - - + + Info 信息 - - + + About 关于 - - + + Setting 设置 - + + Software Update + 软件更新 + + + + CurVersion + 当前版本 + + + + Update + 更新 + + + + LatestVersion: + 最新版本: + + + + + Update log: + 更新日志: + + + + The current version is already the latest version + 已经是最新的版本 + + + Device 设备管理 - + Program 节目管理 - + Control 终端控制 - + GuangYinPin 光影屏 - + Check card 一键找卡 - + Tip Info 提示 - + RestoreLedCardIpByUdpTip 该操作会把局域网内的所有与计算机IP不在同一网段的控制卡修复成固定IP,请谨慎操作! + + Net + + + Connection Timeout + 连接超时 + + + + Error + 错误 + + PageEditor - + Zoom In 放大 - + Zoom Out 缩小 - + Original size 原始比例 - + Delete the secect media 删除选中的媒体 - + Clear all media 清空所有媒体 - + Move layer up 向上一层(快捷键PgUp) - + Send backward 向下一层(快捷键PgDn) - + Bring to front 图层置顶(快捷键Home) - + Move to the bottom layer 图层置底(快捷键End) - + Fill the entire screen 全屏铺满 - + Fill the screen horizontally 水平铺满 - + Fill the screen vertically 垂直铺满 - + Align top 垂直靠顶 - + Center vertically 垂直居中 - + Bottom align 垂直靠底 - + Align left 水平靠左 - + Center horizontally 水平居中 - + Align right 水平靠右 - + Tip Info 提示 - + Clear all medias? 清除所有媒体? @@ -5528,79 +5440,84 @@ PageListItem - + times - + Page name 节目名称 - + New 新建 - + Play times 播放次数 - + + Sources Repeat + 素材循环 + + + Audios 音频 - + Total Dur 总时长 - - + + s - + Select File 选择文件 - + Duration 时长 - + Vol 音量 - + Valid Date 有效日期 - - + + Warning 警告 - + Start Time can't be later than End Time 开始时间不能晚于结束时间 - + End Time can't be earlier than Start Time 结束时间不能早于开始时间 - + Plan 时间计划表 @@ -5629,17 +5546,17 @@ PlayWin - + Move to Top Left 移动到左上角 - + Set Position 设置位置 - + Close 关闭 @@ -5647,12 +5564,12 @@ PlayerBackSendThread - + Open file failed 文件读取失败 - + Read file failed 文件读取失败 @@ -5673,47 +5590,47 @@ ProgCreateDlg - + Resolution 分辨率 - + Solution Information 节目信息 - + Solution Name 节目名称 - + Width - + Height - + Remarks 备注 - - 节目超宽需要打折, 请输入打折宽度 - + + 每段打折宽度 (用空格分隔) + - + OK 确认 - + Cancel 取消 @@ -5721,221 +5638,200 @@ ProgEditorWin - + Save 保存 - - + + Save as 另存为 - + Setting 设置 - + Text 文本 - + Photo 图片 - + Video 视频 - + Gif 动画 - + Clock 数字时钟 - + Analog Clock 模拟时钟 - + Environment 环境监测 - + Web 网页 - + MuliContentWindow 多素材窗口 - + In this window, a plurality of different program materials can be added and played according to the order of joining the list; 该窗口中可以加入多个不同是节目素材,并按照加入列表的先后顺序播放 - + Timer 计时器 - + Play 播放 - + Stop 停止 - + Publish 发布 - - - - + + + + Select File 选择文件 - + program 节目列表 - + Add page 添加页面 - + Copy page 复制页面 - + Delete page 删除页面 - - + + Tip Info 提示 - + Are you sure you want to delete this program page? 确定要删除该节目页吗? - + Move up 向上移动一个页面 - + Move down 向下移动一个页面 - + widget properties 组件属性 - + Page properties 节目属性 - + Do you want to save the modifications? 是否保存修改? - - + + Saving... 正在保存... - - + + Success 成功 - - + Save failed 保存失败 - + Convertering 整理数据中 - - Converter Successed - 整理成功 - - - - Converter TimeOut - 整理超时 - - - + Generate preview data 生成预览数据 - - Ready - 准备完毕 - - - - Generate TimeOut - 超时 - - - - + + Error 错误 - + Rename fail when saving 重命名文件夹失败 - + Remove Recursively fail when saving - + Warning 警告 @@ -5943,155 +5839,177 @@ ProgItem - - + + ExportButtonTip U盘播放 - - + + SendButtonTip 发布 - - + + Convertering 整理数据中 - - - USB Export Successed - U盘导出成功 - - - - USB Export TimeOut - U盘导出失败 - - - - Converter Successed - 整理成功 - - - - Converter TimeOut - 整理超时 - ProgPanel - - + + New 新建 - - + + Edit 编辑 - - + + Delete 删除 - - + + + Import 导入 - - + + + Export 导出 - - + + Send 发送 - - + + Publish 发布 - - + + Name 名称 - - + + + Choose Directory + 选择目录 + + + + Tip + 提示 + + + + The imported directory is already in the working directory, so there is no need to import it again! + 该导入的目录已经在工作目录下,无需再次导入! + + + + :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? + :节目已存在。是否确实要覆盖现有节目? + + + + Play 播放 - - + + Stop 停止 - - + + Resolution 分辨率 - - + + File Size 文件大小 - - + + Last Modify 最后修改时间 - - + + Usb playback U盘更新 - + Program name conflicted 节目名称重复 - + Warning 警告 - + You will delete the selected solution(s),are you sure? 是否确认删除选中的节目? - + + Tip Info 提示 + + ProgPortDlg + + + Solution Name + 节目名称 + + + + Progress + 进度 + + + + Done + 完成 + + QObject - + Setting up the LedOK Express... 初始化LedOK Express... @@ -6099,18 +6017,18 @@ SendProgThread - - + + Program is empty 节目为空 - + Open file failed 文件打开失败 - + Read file failed 文件读取失败 @@ -6118,73 +6036,73 @@ SendProgramDialog - - + + Publish 发布 - + success info - + Refresh 刷新 - + Cancel 取消 - + Screen ID 屏幕ID - + Remark Name - 別名 + 别名 - + Online 在线 - + Screen IP 屏幕IP - + Screen Size 屏幕像素 - + Security 加密 - + Progress 进度 - + Remarks 备注 - + This screen is encrypted 屏幕已加密 - + All 总数 @@ -6192,12 +6110,12 @@ SoftConfigDialog - - Software Configuration + + Software Config 软件配置 - + Video compress to 视频压缩成 @@ -6207,200 +6125,31 @@ 视频转码成 - + Text antialiasing 文字反锯齿 - + TextAntilaTip (提示:该选项适合小间距大尺寸的屏幕,选中此项,文字边缘会有暗影已达到字体边缘光滑的效果;小尺寸屏幕和单双色屏幕不建议使用) - + GuangYinPin 光影屏 - + + Width Split + 超长屏打折 + + + OK 确认 - - SpecialDlg - - Specify IP - 指定IP - - - Search - 搜索 - - - Cancel - 取消 - - - Attention - 注意 - - - Please input IP address! - 请输入IP地址! - - - Your IP Address is Invalid! - IP地址无效! - - - Error - 错误 - - - - ThreadUpgradeApk - - - Uploadding - 正在上传 - - - - TipDialog - - - TextLabel - - - - - - OK - 确认 - - - - - Cancel - 取消 - - - - X - - - - - - Import - 导入 - - - - - Path - 路径 - - - - - : - - - - - - browse - 选择 - - - - You will delete the selected solution(s),are you sure? - 是否确认删除选中的节目? - - - - - Export - 导出 - - - - - Done - 完成 - - - - - Solution Name - 节目名称 - - - - - Progress - 进度 - - - - Delete - 删除 - - - - Select the network to connect to the device - 选择和LED控制卡直连的网络 - - - - Network name - 网络名称 - - - - - This operation will only set cable network to static IP,are you sure? - 此操作将设置选中的网络为固定IP,并自动配置直连的LED设备为同一网段的IP地址,是否确认? - - - - Do you want set IP of cable network to DHCP - 是否设置网络为通过DHCP自动获取IP - - - - - - - - Tip - 提示 - - - - - - Please select the network to connect to the Led controller - 请选择连接到LED控制器的网络 - - - - Choose Directory - 选择目录 - - - - The imported directory is already in the working directory, so there is no need to import it again! - 该导入的目录已经在工作目录下,无需再次导入! - - - - no find program can be imported - 没有找到可以导入的节目 - - UpdateLedset3Dialog @@ -6473,262 +6222,315 @@ 祝贺你!您正在运行最新版本的%1 - - UpdaterDialog - - - Software Update - 软件更新 - - - - X - X - - - - V1.0 - - - - - Update - 升级 - - - - CurVersion - 当前版本 - - - - LatestVersion: - 最新版本: - - - - - Update log: - 更新日志: - - - - The current version is already the latest version - 已经是最新的版本 - - UpgradeApkDialog - - - Upgrade apk - 升级apk + + Update APK + 更新APK - - 口 - - - - - X - - - - - + Select apk 选择Apk包 - - - - + Upgrade 升级 - - - APK: - - - - - + Uninstall 卸载 - - + check running state 检测运行状态 - - + Select Fpga 选择FPGA文件 - - - success info - + + Installing + 正在安装 - - + Refresh 刷新 - - + Cancel 取消 - + Screen ID 屏幕ID - + Remark Name - 別名 + 别名 - + Online 在线 - + Screen IP 屏幕IP - + Security 加密 - + Progress 进度 - + xixunplayer - + cardsystem - + taxiapp - + starter - + connection - + displayer - + FPGA FPGA - + update - + State 状态 - - - + + All 总数 - + + This screen is encrypted + 屏幕已加密 + + + + + Select Online APK + 选择在线APK + + + + No Files + 没有文件 + + + + Name + 名称 + + + + Size + 大小 + + + + Create Time + 创建时间 + + + + + + Tip + 提示 + + + + Is upgrading now. Please wait + 正在更新,请稍后 + + + + NoSelectedController + 请先选择大屏幕 + + + + + Downloading Online File + 正在下载在线文件 + + + + + Error + 错误 + + + + Online file is empty + 在线文件为空 + + + + Uploading + 正在上传 + + + + Upload error + 上传错误 + + + + Install error + 安装错误 + + + + Install success + 安装成功 + + + + Reminder + 提示 + + + + Reminder: Uninstalling this program may cause the device to offline, cannot be found, lost configs and have a black screen. Please uninstall with caution! + 提示:卸载此程序会导致平台掉线,找不到设备,配置参数丢失和黑屏问题,请谨慎卸载! + + + + Do you want to continue? + 是否继续? + + + + Uninstalling + 正在卸载 + + + + Uninstall error + 卸载错误 + + + + Uninstall success + 卸载成功 + + + + Check apk running status + 监测APK运行状态 + + + + Check error + 检查错误 + + + + Running + 正在运行 + + + + Not running + 没有运行 + + + The encrypted control card can be upgraded directly 加密控制卡可以直接升级 - - - apk package (*.rpd) - - - - - apk package (*.apk *.zip) - - UsbDetectDialog - + Usb upgrade program U盘更新节目 - + Password 密码 - + OK 确认 - + Input password 输入密码 - - + + Tip 提示 - + No checked USB device 未检查USB设备 - + please select usb device in list 请在列表中选择usb设备 - + Cancel 取消 @@ -6736,7 +6538,7 @@ WaitingDlg - + Success 成功 @@ -6765,331 +6567,6 @@ 取消 - - eAClock - - - Basic Properties - 基本属性 - - - - Time Zone - 时区 - - - - Custom Dial - 自定义表盘 - - - - Select - 选择 - - - - Select Dail file - 选择表盘图片 - - - - Hour Mark - 时标 - - - - - Circular - 圆形 - - - - - Rectangle - 矩形 - - - - Number - 数字 - - - - - - T - - - - - Min Mark - 分标 - - - - Hand Color - 指针颜色 - - - - H - - - - - M - - - - - S - - - - - Text - 文本 - - - - Play Properties - 播放方式 - - - - Play Duration - 播放时长 - - - - s - - - - - eDClock - - - MON - 星期一 - - - - TUE - 星期二 - - - - WED - 星期三 - - - - THU - 星期四 - - - - FRI - 星期五 - - - - SAT - 星期六 - - - - SUN - 星期日 - - - - - AM - 上午 - - - - - PM - 下午 - - - - Basic Properties - 基本属性 - - - - Time Zone - 时区 - - - - Year - - - - - Month - - - - - Day - - - - - Hour - - - - - Min. - - - - - Sec. - - - - - Weekly - 星期 - - - - Full Year - 四位年 - - - - 12-Hour - 12小时制 - - - - Date Style - 日期风格 - - - - Time Style - 时间风格 - - - - Display Style - 显示风格 - - - - Multiline - 多行显示 - - - - Play Properties - 播放方式 - - - - Play Duration - 播放时长 - - - - s - - - - - GenTmpThread - - - Preparing ... - 准备中... - - - - MON - 星期一 - - - - TUE - 星期二 - - - - WED - 星期三 - - - - THU - 星期四 - - - - FRI - 星期五 - - - - SAT - 星期六 - - - - SUN - 星期日 - - - - AM - 上午 - - - - PM - 下午 - - - - day - - - - - hour - - - - - min - - - - - sec - - - - - Create json ... - 生成json... - - - - Scan program ... - 扫描节目... - - mGuangYingPinWidget @@ -7494,68 +6971,55 @@ 串口打开失败 - - wExportProgramItem - - - Tip Info - 提示 - - - - :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? - :节目已存在。是否确实要覆盖现有节目? - - wPlanItem - + Form Form - + 1 1 - + Every week: 每周: - + M - + Tu - + W - + Th - + F - + Sa - + Su @@ -7563,30 +7027,30 @@ wProgramPublishItem - + Input password 输入密码 - - - + + + Error 错误 - - + + Tip Info 提示 - + Fail 失败 - + password is wrong 密码错误 @@ -7594,92 +7058,24 @@ wUpgradeApkItem - + Input password 输入密码 - - uninstalling - 正在卸载 + + Error + 错误 - - - IsSoftwareRunning - 监测APK运行状态 - - - - - This screen is encrypted - 屏幕已加密 - - - - - Start upgrading - 开始升级 - - - - - Timeout - 超时 - - - - install start... - 开始安装... - - - - - SynchronousHardwareVersion - 同步FPGA - - - + Tip Info 提示 - + password is wrong 密码错误 - - - - UninstallSoftware - 卸载 - - - - - Success - 成功 - - - - Running - 正在运行 - - - - NoRunning - 没有运行 - - - - install success - 安装成功 - - - - - Fail - 失败 - diff --git a/LedOK/translations/app_zh_TW.ts b/LedOK/translations/app_zh_TW.ts index cf96b0f..e99ba53 100644 --- a/LedOK/translations/app_zh_TW.ts +++ b/LedOK/translations/app_zh_TW.ts @@ -71,2018 +71,581 @@ 密碼更改成功 - - ControlEncryptWidget - - - Form - Form - - - - - Entrypt Configuration - 安全配寘 - - - - Original password - 原始密碼 - - - - - - original password - 原始密碼 - - - - - - New password - 新密碼 - - - - - Repeat new password - 重複輸入 - - - - - - - Set encryption - 加密 - - - - - Cancel encryption - 取消加密 - - - - - Enter password - 輸入密碼 - - - - Enter again - 再次輸入 - - - - - - - - - Tip - 提示 - - - - NoSelectedController - 請先選擇大螢幕 - - - - - InputOriginalPasswordTip - 請輸入原始密碼 - - - - InputNewPasswordTip - 請輸入新密碼 - - - - InputRepeatPasswordTip - 請重複輸入新密碼 - - - - InputRepeatPasswordNotSameTip - 兩次輸入的密碼不一致 - - - - Tip Info - 提示 - - - - After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? - 設置密碼後,請記住密碼並記錄。如果忘記密碼,設備將無法運行。確實要繼續此操作嗎? - - - - - SetControllerPassword - 設定加密 - - - - Readback - 回讀 - - - - - - Success - 成功 - - - - - - failed - 失敗 - - - - - Modify password - 修改密碼 - - - - OriginalPasswordErrorTip - 原始密碼錯誤 - - - - ControlHdmiSchedule - - - Form - Form - - - - - Add - 添加 - - - - - Delete - 删除 - - - - - Clear - 清除 - - - - - Import - 導入 - - - - - Export - 匯出 - - - - By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period - 默認播放非同步內容,定時時間段內播放同步HDMI-IN埠輸入內容 - - - - - Apply - 應用 - - - - Readback - 回讀 - - - - SYNC HDMI - 同步模式 - - - - Start Time - 開始時間 - - - - End Time - 結束時間 - - - - SUN - 星期日 - - - - MON - 星期一 - - - - TUE - 星期二 - - - - WED - 星期三 - - - - THU - 星期四 - - - - FRI - 星期五 - - - - SAT - 星期六 - - - - - On - - - - - SyncSchedule (*.syncs) - - - - - Save File - 保存 - - - - Sync Schedule (*.syncs) - - - - - - Tip - 提示 - - - - - NoSelectedController - 請先選擇大螢幕 - - - - SetTimingHdmiInTask - 設定同步模式定時任務 - - - - GetTimingHdmiInTask - 獲取同步模式定時任務 - - - - - Success - 成功 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse 解析json檔案錯誤! - - - - - failed - 失败 - - - - ControlHdmiWidget - - - HDMI Configuration - 畫面輸入源配寘 - - - - Manual - 手動 - - - - Schedule - 定時 - - - - - Tip - 提示 - - - - - NoSelectedController - 請先選擇大螢幕 - - - - - SyncSwitch - 切換同步模式 - - - - - AnSyncSwitch - 切換异步模式 - - - - - IsSync - 回讀同非同步模式 - - - - Error - 錯誤 - - - - HDMI IN - HDMI IN - - - - Async - BOX - - - - Readback - 回讀 - - - - ControlNetConfigWidget - - - Wire Enther(RJ45) Configuration - 有線網配寘 - - - - - DHCP - - - - - - Specify IP - 指定IP - - - - - IP Address - IP地址 - - - - Mask Address - 子網路遮罩 - - - - - Gateway - 閘道 - - - - - DNS Address - DNS地址 - - - - - - - - - - Set - 設定 - - - - - - - - - Readback - 回讀 - - - - - WIFI Configuration - WiFi配寘 - - - - - WiFi On/Off - WiFi使能 - - - - Input Ap name - 輸入熱點名稱 - - - - - 4G/5G Configuration - 蜂窩數據G配寘 - - - - - Open 4G/5G - 啟用蜂窩數據 - - - - APN: - - - - - - Get cellular network status information - 獲取蜂窩網絡狀態資訊 - - - - - Check SIM can automatically match to MCC, and then select carrier get apn param,if not found carrier,you can check the CUSTOM checkbox,then enter custom param. - 通過獲取狀態按鈕可以自動匹配國家碼MCC,然後選擇“運營商”可獲取到響應的APN資訊,如果找不到運營商,可以選中“自定義”核取方塊,然後手動輸入APN資訊。 - - - - - Readback APN Info - 回讀APN資訊 - - - - - Set Apn Info,Check SIM can automatically match to MCC, and then select carrier get apn param - 設定Apn資訊 - - - - - CUSTOM - 自定義 - - - - - Check SIM - 査詢SIM資訊 - - - - - - -> - - - - - - Country ID(mcc): - 国家码(mcc):國家碼(mcc): - - - - - Carrier Name - 運營商 - - - - - APN: - 運營商APN: - - - - - APN(Required) - APN(必填) - - - - - User: - 用戶名: - - - - - - - Not required - 非必填 - - - - - Password: - 密碼: - - - - Set Apn:iot.cargo - - - - - - Flight Mode - 飛行模式 - - - - - WiFi name - WiFi名稱 - - - - - - - Password - 密碼 - - - - - - - Input password - 輸入密碼 - - - - - Scan - 掃描 - - - - - Ap Mode - AP使能 - - - - Ap name - 熱點名稱 - - - - OFF - - - - - ON - - - - - AP name - 熱點名稱 - - - - Subnet mask - 子網路遮罩 - - - - Input ap name - 輸入AP名稱 - - - - - - - - - - - - - - - Success - 成功 - - - - - - - - - - - - - - - failed - 失敗 - - - - - - - Tip - 提示 - - - - - NoSelectedController - 請先選擇大螢幕 - - - - - SetEthernet - 設定有線網 - - - - - - - - - - - Attention - 注意 - - - - Please input IP address! - 請輸入IP地址! - - - - Your IP Address is Invalid! - IP地址無效! - - - - Please input Mask address! - 請輸入子網路遮罩地址! - - - - Your Mask Address is Invalid! - 遮罩地址無效! - - - - Please input Gateway address! - 請輸入閘道地址! - - - - Your Gateway Address is Invalid! - 閘道地址無效! - - - - Please input DNS address! - 請輸入DNS地址! - - - - Your DNS Address is Invalid! - DNS地址無效! - - - - - GetEthernet - 獲取有線網配寘 - - - - DHCP IP - 動態DHCP IP - - - - STATIC IP - 靜態IP - - - - Error - 錯誤 - - - - - - - - - SignalPower - 信號強度 - - - - - ConfigurationWiFi - 配寘WiFi - - - - IsPortableHotSpot - 獲取熱點和WiFi模式 - - - - GetWifiList - 掃描WiFi - - - - ConfigurationHotSpot - 配寘熱點 - - - - GetCurrentAPN - 獲取APN資訊 - - - - - GetSIMStatus - 獲取SIM狀態 - - - - SetAPN - 設定APN - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse 解析json檔案錯誤! - - - - 状态: - 狀態: - - - - 未知 - 未知 - - - - 锁定状态,需要用户的PIN码解锁 - 鎖定狀態,需要用戶的PIN碼解鎖 - - - - 锁定状态,需要用户的PUK码解锁 - 鎖定狀態,需要用戶的PUK碼解鎖 - - - - 锁定状态,需要网络的PIN码解锁 - 鎖定狀態,需要網絡的PIN碼解鎖 - - - - 就绪 - 就緒 - - - - no checked sim card - 檢測不到sim卡 - - - - 国家码: - 國家碼: - - - - 号码: - 號碼: - - - - 用户: - 用戶: - - - - 信号: - 信号: - - - - 信号正常 - 訊號正常 - - - - 不在服务区 - 不在服務區 - - - - 仅限紧急呼叫 - 僅限緊急呼叫 - - - - 射频已经关闭 - 射頻已經關閉 - - - - 网络: - 網絡: - - - - 网络类型未知 - 未知 - - - - GPRS网络 - GPRS - - - - EDGE网络 - EDGE - - - - UMTS网络 - UMTS - - - - CDMA网络,IS95A 或 IS95B. - CDM - - - - EVDO网络, revision 0. - EVDO,revision 0. - - - - EVDO网络, revision A. - EVDO,revision A. - - - - 1xRTT网络 - 1xRTT - - - - HSDPA网络 - HSDPA - - - - HSUPA网络 - HSUPA - - - - HSPA网络 - HSPA - - - - 漫游: - 漫遊: - - - - Yes - - - - - No - - - - - 数据连接状态: - 數據連接狀態: - - - - 断开 - 斷開 - - - - 正在连接 - 正在連接 - - - - 已连接 - 已連接 - - - - 暂停 - 暫停 - - - - 数据活动休眠状态: - 數據活動休眠狀態: - - - - 活动,但无数据发送和接收 - 活動,但無數據發送和接收 - - - - 活动,正在接收数据 - 活動,正在接收數據 - - - - 活动,正在发送数据 - 活動,正在發送數據 - - - - 活动,正在接收和发送数据 - 活動,正在接收和發送數據 - - - - 休眠状态 - 休眠狀態 - - - - 信号强度: - 信號強度: - - - - SetSwitchSimData - 設定4G/5G開關 - - - - ContrFlightMode - 配寘飛行模式 - - - - GetFlightModeState - 獲取飛行模式狀態 - - - - ControlPowerManual - - - Form - Form - - - - - POWER - 開關 - - - - - - Readback - 回讀 - - - - OFF - - - - - ON - - - - - - Tip - 提示 - - - - - NoSelectedController - 請先選擇大螢幕 - - - - IsScreenOn - 讀取開關狀態 - - - - - - SetScreenOn - 設定電源 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse 解析json檔案錯誤! - - - - - - - Success - 成功 - - - - - on - - - - - - - - failed - 失敗 - - - - - off - - - - - - SetScreenOff - 配寘荧幕開關 - - ControlPowerSchedule - + Form Form - + Edit area 編輯區 - - + + Add 添加 - - + + Delete 删除 - - + + Clear - 清除 + 清空 - - + + Import 導入 - - + + Export 匯出 - + It is power off state outside the schedule time period 定時時間段內顯示幕開啟,其他時間段為關屏狀態 - + Send command 指令區 - - + + Apply 應用 - + Clear Schedule 清除定時 - + Readback 回讀 - + Power On State - 屏开关状态 + 屏開關狀態 - + Start Time 開始時間 - + End Time 結束時間 - + SUN 星期日 - + MON 星期一 - + TUE 星期二 - + WED 星期三 - + THU 星期四 - + FRI 星期五 - + SAT 星期六 - - + + On - + - - + + PowerSchedule (*.pjs) - 开关屏定时(*.pjs) + 開關屏定時(*.pjs) - + Save File 保存 - - - + + + Tip 提示 - - - + + + NoSelectedController 請先選擇大螢幕 - - + + Tip Info 提示 - - + + Clear schedule task? 取消計畫任務? - - + + CleanTimingScreenTask 取消計畫任務 - + SetTimingScreenTask - 设置屏幕定时开关任务 + 設定螢幕定時開關任務 - - - - + + + + Success 成功 - - + + DeviceItem OnProHttpResponse 解析json文件错误! DeviceItem OnProHttpResponse 解析json檔案錯誤! - - - - + + + + failed 失败 - + GetTimingScreenTask - 获取屏幕定时开关任务 + 獲取螢幕定時開關任務 ControlPowerWidget - - Form - Form + + + Off + - - + + + On + + + + + + Tip + 提示 + + + + + NoSelectedController + 請先選擇大螢幕 + + + + + SetScreenOn + 打開螢幕電源 + + + + + SetScreenOff + 關閉螢幕電源 + + + + + IsScreenOn + 讀取開關狀態 + + + Power Configuration - 开关屏控制 + 開關屏控制 - - + Manual - 手动 + 手動 - - + Schedule - 定时 + 定時 + + + + Power + 電源 + + + + Readback + 回讀 ControlTestWidget - + Form Form - - + + Test Screen - 測試荧幕 + 測試螢幕 - - + + Line test 線條測試 - - - - - - - + + + + + + + Red - - - - - - - + + + + + + + Green - - - - - - - + + + + + + + Blue - - - - - - - + + + + + + + White - - + + Vertical 豎線 - - + + Slash 斜線 - - - + + + Horizontal 橫線 - - - - + + + + Speed 速度 - - + + ms(>10) 毫秒(>10) - - + + Line Distance 線距 - + px px - - - - - + + + + + Test 測試 - - + + Gradation test 灰度測試 - - + + Only the gray value is displayed 只顯示顏色值 - + (>10) - - + + GrayValue 灰度值 - + (0-255) - - + + Color test 顏色測試 - - + + Gradient 漸變 - + 8 8 - + 2 2 - + 3 3 - + 6 6 - + 4 4 - + 5 5 - + 1 1 - + 9 9 - + 7 7 - + 0 0 - - + + Clear - 清除 + 清空 - - + + Reset 迴圈 - - - - + + + + Anycast 點播 - - + + Stop 停止 - - - - - - - - + + + + + + + + Tip 提示 - - - - - + + + + + NoSelectedController 請先選擇大螢幕 - - - + + + StartTest 開始測試 - - - - + + + + Success 成功 - - - - + + + + failed 失敗 - + StopTest 停止測試 - + loopback mode 迴圈模式 - + Connect timeout 連接超時 - + Reset loop mode 設定迴圈 - - + + success 成功 - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse 解析json檔案錯誤! - - - - CtrlVerifyClockPanel - - - Form - Form - - - - English - - - - - 中文 - - - - - Verify Clock Configuration - 校准时间 - - - - Verify to Computer time - 校准到计算机时间 - - - - - Cur time of controller - 顯示幕設備當前時間 - - - - LAN - 局域網 - - - - (min/time) - (分鐘/次) - - - - Sync identificationCode - 同步识别码 - - - - - identification code - 同步识别码 - - - - - Time offset(msec) - 时间偏移(毫秒) - - - - - Brightness - 屏体亮度 - - - - - Volume - 音量 - - - - - Screen on/off - 荧幕開關 - - - - - Slave - - - - - Master - - - - - - NTP Server - NTP服务器 - - - - - - - NTP Server address - NTP服务器地址 - - - - - - - TimeZone - 时区 - - - - - - - - - - - - - - - Set - 设置 - - - - - Language: - 語言: - - - - - Enable Synchronous playing - 使能同步画面功能 - - - - Lora - - - - - GPS - - - - - NTP - - - - - Time zone - 时区 - - - - - - - Sync time interval - 同步时间间隔 - - - - Verify clock configuration - 校准时间 - - - - - - - - - - - - - - Readback - 回讀 - - - - Master - - - - - Sync clock to computer time - 校準時鐘到電腦時間 - - - - Identification Code - 識別碼 - - - - - - - - - - - - - - Success - 成功 - - - - - - - - - - - - - - failed - 失败 - - - - SetNtpServer - 设置NTP服务 - - - - MasterSwitch - 設定為主設備 - - - - SlaveSwitch - 設定為從設備 - - - - IsMasterSlave - 回讀主從身份 - - - - GetControllerDate - 獲取日期時間 - - - - SetingSyncMethod - 設定同步方法 - - - - SyncTime - 校准时间 - - - - GetNtpServer - 获取NTP服务信息 - - - - GetingSyncMethod - 获取同步方式 - - - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse 解析json檔案錯誤! - - - - SetTimezone - 設定時區 - - - - ControlVolumeManual - - - Form - Form - - - - Volume(0-15) - 音量(0-15) - - - - - - Readback - 回讀 - - - - SetVolume - 音量調節 - - - - - - Success - 成功 - - - - - - failed - 失败 - - - - Volume(min:0-max:15) - 音量(最小值:0-最大值:15) - - - - GetVolume - 獲取當前音量 - - - - + + DeviceItem OnProHttpResponse 解析json文件错误! DeviceItem OnProHttpResponse 解析json檔案錯誤! @@ -2090,179 +653,179 @@ ControlVolumeSchedule - + Defalut volume tip 提醒:定時時間段內亮度按定時亮度顯示,其他沒有設定時間段為默認亮度值 - - + + Add 添加 - - + + Delete 删除 - - + + Clear - 清除 + 清空 - + Default Volume 默認音量 - + (0-15) - - + + Import 導入 - - + + Export 匯出 - - + + Apply 應用 - + Readback 回讀 - + Volume value 音量值 - + 開始時間 - + Start Time 開始時間 - + End Time 結束時間 - + SUN 星期日 - + MON 星期一 - + TUE 星期二 - + WED 星期三 - + THU 星期四 - + FRI 星期五 - + SAT 星期六 - + Default volume tip 提醒:定時時間段以外的時間顯示幕為默認亮度 - + Default volume 默認音量值 - - + + DeviceItem OnProHttpResponse 解析json文件错误! DeviceItem OnProHttpResponse 解析json檔案錯誤! - + 10 10 - - + + Volume Schedule (*.vols) - + Save File 保存 - - + + Tip 提示 - - + + NoSelectedController 請先選擇大螢幕 - + SetAutoVolumeTask 配寘定時音量表 - - + + Success 成功 - - + + failed 失敗 - + GetAutoVolumeTask 獲取定時音量表 @@ -2270,849 +833,1012 @@ ControlVolumeWidget - - Form - Form + + + Tip + 提示 - - + + + NoSelectedController + 請先選擇大螢幕 + + + + + SetVolume + 音量調節 + + + + + GetVolume + 獲取當前音量 + + + Volume Control 音量調節 - - + Manual 手動 - - + Schedule 定時 + + + Volume + 音量 + + + + Readback + 回讀 + CtrlAdvancedPanel - - Advanced parameters + + Advanced 高級參數 - + Screen Width(pixel) - 荧幕寬(點數) + 螢幕寬(點數) - + Width - - + + Height - - - - - - - + + + + + + + + + + + + + + + Set 設定 - + Alias 別名 - + Web Server Address: Web伺服器地址: - + www.m2mled.net - + www.ledaips.com - + https://www.taxihub.cn:2340 - + https://www.ledaips.com:2340 - + https://www.36taxi.com:2340 - + www.tlzxled.com - + + MCU Uploading + 正在上傳單片機 + + + + Traffic screen settings + 交通屏設定 + + + + Setting protocol ... + 正在設定協定 + + + + Set protocol + 設定協定 + + + + Getting protocol ... + 正在回讀協定 ... + + + + Get protocol + 回讀協定 + + + + + Port + + + + Realtimer Server Address: Realtimer地址: - + + Firmware Management + 固件管理 + + + + update or uninstall + 更新或卸載 + + + Clear - 清除 + 清空 - - Apk upgrade - Apk陞級 - - - + Check Apk 檢查Apk - + Uninstall 卸載 - + Running check 運行狀態監測 - - FPGA version check - FPGA版本査詢 - - - - Sync FPGA version - 同步FPGA版本 - - - - Restart led controller system + + Restart 重啓 - + Check Log 查看日誌 - + Start LedSet4 - + Open ADB 打開ADB調試功能 - + Post Custom JSON Post Custom JSON - - - - - - - - + + + + + + + + Clear Program 清除節目 - + www.ledokcloud.com/realtime - - M80 configuration - M80配寘 + + Config + 配寘 - + Refresh 檢測 - + Restore to default 恢復預設值 - + Taxi top screen configuration 車頂有無客電平配寘 - + + Service:High Out of service:Low 有客:高電平無客:低電平 - + + Service:Low Out of service:High 有客:低電平 無客:高電平 - + Start LedSet3.0 configure LED module 使用LedSet3.0配寘LED模組(廠家專業人員使用) - + Binding *.ic account indentity voucher 綁定taxihub平臺用戶身份憑證 - + Rotate 旋轉 - - 0 degrees - 0度 - - - - 90 degrees - 90度 - - - - 180 degrees - 10度 - - - - 270 degrees - 270度 - - - + Min brightness 最低亮度 - - (min:1) - (最小:1) - - - - - + + + Readback 回讀 - - - + Send 發送 - + Max brightness 最高亮度 - - (max:255) - (最高:255) - - - - + + SetScreenSize - 設定荧幕點數尺寸 + 設定螢幕點數尺寸 - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Success 成功 - + Compant ID: 公司ID: - - FPGA Upgrade - FPGA陞級 - - - + Compant ID 公司ID - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NoSelectedController 請先選擇大螢幕 - + InputWebServerAddressTip 請輸入Web伺服器地址 - + InputCompanyIdTip 請輸入公司ID - + Do you want to modify webserveraddress and companyId? 是否確認配寘伺服器地址和公司ID? - - - - - - - - - - - - - - - - - - - - - - failed - 失敗 - - - - + + SetOnlineAddr 設定web伺服器地址 - + + ClearRealtimeServer 清除 - - InputRealTimeAddressTip - 請輸入RealTimer地址 - - - + + SetRealtimeServer 設定RealTimer地址 - - - - + + + + Tip Info 提示 - - - + + + Can not find LedSet3.0.exe,down you need download and install it 找不到LedSet3.0.exe,確認下載並安裝 - + + RestartAndroid 重啓 - - FPGA Version - FPGA版本 - - - - + + running 正在運行 - - + + no running 沒有運行 - + Check Apk Version 査詢已安裝apk版本 - - + + UninstallSoftware 卸載 - - - IsSoftwareRunning + + + Check apk running status 監測APK運行狀態 - - apk package (*.rpd) - - - - - CheckHardwareVersions - 査詢FPGA版本 - - - - - - SynchronousHardwareVersion - 同步FPGA硬體版本 - - - - Check Screen untile fpga update finished - 觀察荧幕陞級進度直到陞級成功 - - - + + OpenAdb 打開ADB調試功能 - + indentity voucher (*.ic) 身份憑證(*.ic) - - - - - + + + + + InvokeTaxiAppFunction 綁定證書 - - Json format is error! - - - - - + + AliIotSetting - - apk package (*.apk *.zip) - - - - + Software Version Info 軟體版本資訊 - + Package 包名 - + Version 版本 - - - UpgradeSoftware - 陞級固件 - - - - This screen is encrypted,Please decrypt and upgrade APK! - 此荧幕已加密,請解密並陞級APK! - - - - + + Package name is null 包名為空 - + Clearing Program 正在清除節目 - - - - + + + + Timeout 超時 - - - - + + + + Failed 失敗 - + Getting Log 讀取日誌 - - - - - - - - - + + + + + + + + + + + Error 錯誤 - + + Setting Timing Reboot + 正在設定定時重啓 + + + + Set Timing Reboot + 設定定時重啓 + + + + Getting Timing Reboot + 正在獲取定時重啓 + + + + Get Timing Reboot + 獲取定時重啓 + + + + totalResolution + 行数を含む解像度 + + + + strCurDisplayResolution + 當前顯示分辯率 + + + + File not exist + 檔案不存在 + + + + Uploading + 正在上傳 + + + + + Set Display Mode + 設定顯示模式 + + + + + Get Display Mode + 獲取顯示模式 + + + + + Set Screen Offset + 設定螢幕偏移 + + + + + Get Screen Offset + 獲取螢幕偏移 + + + Open file Failed 檔案打開失敗 - + Setting Wallpaper 正在設定系統桌面背景 - - + + Set Wallpaper 設定系統桌面背景 - + System Updating 系統升級中 - - + + System Update 系統升級 - + + Getting MCU Version + 正在獲取單片機版本 + + + + + MCU Version + 單片機版本 + + + Select File 選擇檔案 - + Setting player background 正在設定播放機背景 - - + + Set player background 設定播放機背景 - + Clearing player background 正在清除播放機背景 - - - - - - - - + + + + + + + + Clear player background 清除播放機背景 - + Setting Baud Rate 正在設定串列傳輸速率 - + Set Baud Rate 設定串列傳輸速率 - + Getting Baud Rate 正在讀取串列傳輸速率 - + Get Baud Rate 讀取串列傳輸速率 - + + Text is empty + + + + + Json Parse Error + + + + + Json isn't an Object + + + + + Setting card work mode ... + 正在設定控制卡工作模式 ... + + + + Set card work mode + 設定控制卡工作模式 + + + + Getting card work mode ... + 正在回讀控制卡工作模式 ... + + + + Get card work mode + 回讀控制卡工作模式 + + + + Resolution Config + 分辯率配寘 + + + + Full screen + 全屏 + + + + Part + 局部 + + + + Display Mode + 顯示模式 + + + + Screen Position + 螢幕位置 + + + + Offset + 偏移 + + + Hidden Settings 隱藏的設定 - + Click right button to hide 點擊右鍵隱藏 - + + + Update MCU + 更新單片機 + + + + Get MCU Version + 獲取單片機版本 + + + Baud Config 串列傳輸速率配寘 - + Model 設備型號 - + Uart 串口節點 - + Baud 串列傳輸速率 - + + + + + + Get 讀取 - - - - DeviceItem OnProHttpResponse 解析json文件错误! - DeviceItem OnProHttpResponse 解析json檔案錯誤! + + Timing Reboot + 定時重啓 - - - - + + Protocol + 協定 + + + + Server + 服務端 + + + + Client + 用戶端 + + + + SetScreenRotation - 設定荧幕旋轉 + 設定螢幕旋轉 - + + SetMinBrightness 設定最小的亮度值 - + + SetMaxBrightness 設定亮度最大值 - + + GetMinBrightness 獲取亮度最小值 - + + GetMaxBrightness 獲取亮度最大值 - + + + Card work mode + 控制卡工作模式 + + + + SetSpecialResolution 設定分辯率 - + + GetSpecialResolution 讀取分辯率 - + + CleanDisplayScreenSize 恢復默認分辯率 - + + SetHighForBusy 設定有無客電平 - + + GetStateForBusy 獲取有無客電平 - - install start... - 開始安裝… - - - + InputAliasTip 請輸入別名 - - + + SetCardAlias 設定別名 - - Uploadding - 上傳 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Tip 提示 - + InputWidthTip 請輸入正確的寬度點數值 - + InputHeightTip 請輸入正確的高度點數值 - + Password is error 密碼錯誤 @@ -3120,342 +1846,1496 @@ CtrlBrightPanel - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + Tip 提示 - - - - - - - - - - - + + + + + + + + + + + NoSelectedController 請先選擇大螢幕 - - + + SetBrightnessSensitivity 設定亮度感測器靈敏度 - - + + GetBrightnessSensitivity 獲取亮度感測器靈敏度 - - + + SetMinBrightness 設定最小的亮度值 - - + + GetMinBrightness 獲取亮度最小值 - - + + NeedSelectSensorTypeTip 請先選擇感測器類型 - + Open file dialog 打開文件 - + Not found current worksheet 沒找到當前工作表 - - + + SensorBrightnessTable 設定亮度感測器配寘錶 - + GetSensorBrightnessTable 獲取感測器亮度配寘錶 - + no sensorBrightnessTable 控制卡沒有發現亮度配寘錶 - + Save file 保存 - - + + GetCurrentSensorBrightness 獲取當前亮度 - - + + SetBrightness 設定亮度 - + GetBrightness 獲取亮度值 - + Brightness 屏体亮度 - + Import File 導入檔案 - - + + BrightnessSchedule (*.bjs) - + Save File 保存 - + BrightnessValue 亮度值 - + 開始時間 - + Start Time 開始時間 - + End Time 結束時間 - - + + SetAutoBrightnessTask 發送定時亮度錶 - + GetAutoBrightnessTask 獲取定時亮度錶 - - - - + + Error 錯誤 - + Brightness Configuration 亮度配寘 - + Auto 自動 - + Manual 手動 - + Schedule 定時 - + + Adapt to Old Devices + 適配舊設備 + + + BrightTip1 如果最大亮度為64,則最小亮度可以配寘為1%或適當的值;如果最大亮度為255,則最小亮度必須配寘為36%或更高,否則亮度將很低。 - + BrightTip2 上傳文件時,請確認選擇正確的感測器類型,否則無效! - + Sensitivity 靈敏度 - + Minbrightness 最小亮度值 - - - + + + Set 設定 - + Upload 上傳設定檔 - - - - + + + + Readback 回讀 - + ReadbackTable 回讀 - + Refresh 檢測 - + Cur Brigntness 當前亮度 - + Brightness value 亮度值 - + Default brightness 默認亮度 - + Add 添加 - + Clear 清空 - + Delete 删除 - + Import 導入 - + Export 匯出 - + Apply 應用 - + Default brightness tip - 提示:該設定時間內為設定亮度,設定時間外為默認亮度。例如設定默認亮度為80,設定亮度為180,時間範圍是8:00-17:00,則時間範圍內亮度為180,其他時間內為默認亮度80! + 提示:時間範圍內為設定亮度,時間範圍外為默認亮度。例如默認亮度為50%,設定亮度為80%,時間範圍是8:00-17:00,則時間範圍內亮度為80%,其他時間為默認亮度50% + + + + CtrlHdmiPanel + + + HDMI Configuration + 畫面輸入源配寘 + + + + Manual + 手動 + + + + Schedule + 定時 + + + + + + + Tip + 提示 + + + + + + + NoSelectedController + 請先選擇大螢幕 + + + + + SyncSwitch + 切換同步模式 + + + + + AnSyncSwitch + 切換異步模式 + + + + IsSync + 回讀同非同步模式 + + + + Import File + 導入檔案 + + + + Save File + 保存 + + + + + Sync Schedule + 同步定時任務 + + + + + SetTimingHdmiInTask + 設定同步模式定時任務 + + + + GetTimingHdmiInTask + 獲取同步模式定時任務 + + + + + Async + BOX + + + + + Readback + 回讀 + + + + Start Time + 開始時間 + + + + End Time + 結束時間 + + + + SUN + 星期日 + + + + MON + 星期一 + + + + TUE + 星期二 + + + + WED + 星期三 + + + + THU + 星期四 + + + + FRI + 星期五 + + + + SAT + 星期六 + + + + Add + 添加 + + + + + Apply + 應用 + + + + Clear + 清空 + + + + Delete + 删除 + + + + Import + 導入 + + + + Export + 匯出 + + + + By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period + 默認播放非同步內容,定時時間段內播放同步HDMI-IN埠輸入內容 + + + + CtrlNetworkPanel + + + Wire Enther(RJ45) Configuration + 有線網配寘 + + + + DHCP + + + + + Specify IP + 指定IP + + + + IP Address + IP地址 + + + + Gateway + 閘道 + + + + DNS Address + DNS地址 + + + + + + Set + 設定 + + + + + + + Readback + 回讀 + + + + WIFI Configuration + WiFi配寘 + + + + WiFi Mode + 使用WiFi + + + + Cellular Config + 蜂窩數據配寘 + + + + Enable Cellular Data + 啟用蜂窩數據 + + + + Get cellular network status information + 獲取蜂窩網絡狀態資訊 + + + + Through the check status button + 通過“獲取狀態”按鈕可以自動匹配國家碼,然後選擇“運營商”可獲取到相應的APN資訊。 + + + + Set APN Info + 設定APN資訊 + + + + Country ID(mcc): + 国家码(mcc):國家碼(mcc): + + + + + Carrier Name + 運營商 + + + + APN(Required) + APN(必填) + + + + Flight Mode + 飛行模式 + + + + WiFi name + WiFi名稱 + + + + + + Password + 密碼 + + + + + Input password + 輸入密碼 + + + + Scan + 掃描 + + + + Ap Mode + 使用熱點 + + + + OFF + + + + + ON + + + + + AP name + 熱點名稱 + + + + Subnet mask + 子網路遮罩 + + + + Input ap name + 輸入AP名稱 + + + + + + + + + + + + + + + Tip + 提示 + + + + + + + + + + + + + + NoSelectedController + 請先選擇大螢幕 + + + + + SetEthernet + 設定有線網 + + + + + + + + + + + Attention + 注意 + + + + Please input IP address! + 請輸入IP地址! + + + + Your IP Address is Invalid! + IP地址無效! + + + + Please input Mask address! + 請輸入子網路遮罩地址! + + + + Your Mask Address is Invalid! + 遮罩地址無效! + + + + Please input Gateway address! + 請輸入閘道地址! + + + + Your Gateway Address is Invalid! + 閘道地址無效! + + + + Please input DNS address! + 請輸入DNS地址! + + + + Your DNS Address is Invalid! + DNS地址無效! + + + + + GetEthernet + 獲取有線網配寘 + + + + DHCP IP + 動態DHCP IP + + + + STATIC IP + 靜態IP + + + + + ConfigurationWiFi + 配寘WiFi + + + + + IsPortableHotSpot + 獲取熱點和WiFi模式 + + + + GetWifiList + 掃描WiFi + + + + + ConfigurationHotSpot + 配寘熱點 + + + + success + 成功 + + + + WifiName + Wifi名稱 + + + + ApName + 熱點名稱 + + + + + GetCurrentAPN + 獲取APN資訊 + + + + GetSIMStatus + 獲取SIM狀態 + + + + + SetAPN + 設定APN + + + + 状态: + 狀態: + + + + 未知 + 未知 + + + + 锁定状态,需要用户的PIN码解锁 + 鎖定狀態,需要用戶的PIN碼解鎖 + + + + 锁定状态,需要用户的PUK码解锁 + 鎖定狀態,需要用戶的PUK碼解鎖 + + + + 锁定状态,需要网络的PIN码解锁 + 鎖定狀態,需要網絡的PIN碼解鎖 + + + + 就绪 + 就緒 + + + + no checked sim card + 檢測不到sim卡 + + + + 国家码: + 國家碼: + + + + 号码: + 號碼: + + + + 用户: + 用戶: + + + + 信号: + 信号: + + + + 信号正常 + 訊號正常 + + + + 不在服务区 + 不在服務區 + + + + 仅限紧急呼叫 + 僅限緊急呼叫 + + + + 射频已经关闭 + 射頻已經關閉 + + + + 网络: + 網絡: + + + + 网络类型未知 + 未知 + + + + GPRS网络 + GPRS + + + + EDGE网络 + EDGE + + + + UMTS网络 + UMTS + + + + CDMA网络,IS95A 或 IS95B. + CDM + + + + EVDO网络, revision 0. + EVDO,revision 0. + + + + EVDO网络, revision A. + EVDO,revision A. + + + + 1xRTT网络 + 1xRTT + + + + HSDPA网络 + HSDPA + + + + HSUPA网络 + HSUPA + + + + HSPA网络 + HSPA + + + + 漫游: + 漫遊: + + + + Yes + + + + + No + + + + + 数据连接状态: + 數據連接狀態: + + + + 断开 + 斷開 + + + + 正在连接 + 正在連接 + + + + 已连接 + 已連接 + + + + 暂停 + 暫停 + + + + 数据活动休眠状态: + 數據活動休眠狀態: + + + + 活动,但无数据发送和接收 + 活動,但無數據發送和接收 + + + + 活动,正在接收数据 + 活動,正在接收數據 + + + + 活动,正在发送数据 + 活動,正在發送數據 + + + + 活动,正在接收和发送数据 + 活動,正在接收和發送數據 + + + + 休眠状态 + 休眠狀態 + + + + 信号强度: + 信號強度: + + + + User + 用戶 + + + + Type + 型態 + + + + Server + 服務端 + + + + Port + + + + + Proxy + 代理 + + + + MMS Port + 彩信埠 + + + + MMS Proxy + 彩信代理 + + + + + SetSwitchSimData + 設定4G/5G開關 + + + + + ContrFlightMode + 配寘飛行模式 + + + + + GetFlightModeState + 獲取飛行模式狀態 + + + + CtrlPwdPanel + + + Set Password + 安全配寘 + + + + Original password + 原始密碼 + + + + original password + 原始密碼 + + + + + New password + 新密碼 + + + + Repeat new password + 重複輸入 + + + + + + + Set encryption + 加密 + + + + Cancel encryption + 取消加密 + + + + Enter again + 再次輸入 + + + + + + + + + + + + Tip + 提示 + + + + + NoSelectedController + 請先選擇大螢幕 + + + + + InputOriginalPasswordTip + 請輸入原始密碼 + + + + InputNewPasswordTip + 請輸入新密碼 + + + + InputRepeatPasswordTip + 請重複輸入新密碼 + + + + InputRepeatPasswordNotSameTip + 兩次輸入的密碼不一致 + + + + Tip Info + 提示 + + + + After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation? + 設定密碼後,請記住密碼並記錄。如果忘記密碼,設備將無法運行。確實要繼續此操作嗎? + + + + + + + SetControllerPassword + 設定加密 + + + + + Error + 錯誤 + + + + + Success + 成功 + + + + + + Modify password + 修改密碼 + + + + + + + OriginalPasswordErrorTip + 原始密碼錯誤 + + + + CtrlVerifyClockPanel + + + Verify Clock Configuration + 校準時間 + + + + + Verify to Computer time + 校準到電腦時間 + + + + Cur time of controller + 顯示幕設備當前時間 + + + + + LAN + 局域網 + + + + + + + + + + + + + + Tip + 提示 + + + + + + + + + + + + + + NoSelectedController + 請先選擇大螢幕 + + + + screenSwitch + 開關屏 + + + + + + YES + + + + + + + NO + + + + + volume + 音量 + + + + brightness + 亮度 + + + + + identificationCode + 識別碼 + + + + + delaySync + 時間偏移 + + + + + msec + 毫秒 + + + + + + + OtherSyncItem + 其他同步項 + + + + + + + lastSynchronousTime + 上次同步時間 + + + + checkNtpTime + 同步間隔 + + + + Lora identity + Lora身份 + + + + (min/time) + (分鐘/次) + + + + identification code + 同步识别码 + + + + Time offset(msec) + 時間偏移(毫秒) + + + + Brightness + 屏体亮度 + + + + Volume + 音量 + + + + Screen on/off + 螢幕開關 + + + + + Slave + + + + + NTP Server + NTP服務器 + + + + + NTP Server address + NTP服務器地址 + + + + TimeZone + 時區 + + + + + + + + Set + 設定 + + + + Language: + 語言: + + + + Enable Synchronous playing + 使能同步画面功能 + + + + + Sync time interval + 同步時間間隔 + + + + + + + + Readback + 回讀 + + + + + Master + + + + + Identification Code + 識別碼 + + + + + SetNtpServer + 設定NTP服務 + + + + + MasterSwitch + 設定為主設備 + + + + + SlaveSwitch + 設定為從設備 + + + + IsMasterSlave + 回讀主從身份 + + + + + GetControllerDate + 獲取日期時間 + + + + + SetingSyncMethod + 設定同步方法 + + + + + SyncTime + 校準時間 + + + + + GetNtpServer + 獲取NTP服務資訊 + + + + + GetingSyncMethod + 獲取同步方式 + + + + + SetTimezone + 設定時區 Def - - - + Connection Timeout 連接超時 - - - - - - - + + + + + Device replied 設備回復 - - + + + Success 成功 - - - - Error - 錯誤 - - - - Tip Info - 提示 - - - - + Fail 失敗 @@ -3463,666 +3343,314 @@ DeviceCtrlPanel - - - + + + + Current Screen 当前屏幕 - - + + none - + - - + + Clear 清空 - - - single screen operation - 單屏操作 - - - + + Multi screen operation 多屏操作 - + + selected num 選中數目 - + Brightness Adjustment 亮度調節 - + Power Control 電源控制 - + Net Config 網絡配寘 - - Time Synchronization + + Time Sync 對時管理 - + Video source - 同异步配置 + 同異步配寘 - - Encrypt - 加密配寘 + + Password + 設寘密碼 - - Advanced parameters + + Advanced 高級設定 - - Current Screen: - 当前屏幕: - - - + Test 測試 - - Volume Adjustment + + Volume Adj. 音量調節 DeviceItem - + GetScreenDetailInfo 更多資訊 - + ReadbackPic 回讀畫面 - + Input password 輸入密碼 - + GetScreenshotFull 回讀畫面 - + cur brightness: 當前亮度: - + android version: 安卓版本: - + IMEI: - + HardWard Version: FPGA版本: - + MAX Brightness level: 亮度等級: - + Android OS Resolution: 安卓分辯率: - + Firmware Version: 固件版本: - + Player Version: 播放機固件版本: - + Detail Info 詳細資訊 - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + receive 接收 - - SetScreenOn - 設定電源 - - - + AliIotSetting - - + + GetScreenStatus - 獲取荧幕狀態 + 獲取螢幕狀態 - - + + Status 狀態 - + Tip Info 提示 - + password is wrong 密碼錯誤 - + GetBrightness 獲取亮度值 - - - + brightness 亮度 - - MasterSlaveSwitch - 配寘主從身份 - - - - SetBrightness - 設定亮度 - - - - - SetMinBrightness - 設定最小的亮度值 - - - - GetBrightnessSensitivity - 獲取亮度感測器靈敏度 - - - - sensitivity - 靈敏度 - - - - GetMinBrightness - 獲取亮度最小值 - - - - SetSensorBrightnessTable - 配寘感測器參數表 - - - - SetSwitchWiFi - 設定WiFi開關 - - - - ConfigurationWiFi - 配寘WiFi - - - - ConfigurationHotSpot - 配寘熱點 - - - - GetSwitchWiFi - 獲取WiFi狀態 - - - + SetAutoBrightnessTask 發送定時亮度錶 - + SetAutoVolumeTask 配寘定時音量表 - + SetVolume 音量調節 - + GetVolume 獲取當前音量 - + SetTimingScreenTask - 設定荧幕定時開關任務 + 設定螢幕定時開關任務 - - GetControllerDate - 獲取日期時間 - - - - SetHighForBusy - 設定有無客電平 - - - - - GetStateForBusy - 獲取有無客電平 - - - - Service:Low Out of service:High - 有客:低電平 無客:高電平 - - - - Service:High Out of service:Low - 有客:高電平無客:低電平 - - - - - - IsPortableHotSpot - 獲取熱點和WiFi模式 - - - - WifiName - Wifi名稱 - - - - ApName - 熱點名稱 - - - + TestScreen - 測試荧幕 + 測試螢幕 - + SetOnlineAddr 設定web伺服器地址 - + SetRealtimeServer 設定RealTimer地址 - - GetOnlineAddr - 取得web伺服器地址 - - - - GetRealtimeServer - 獲取realtime伺服器地址 - - - - SetNtpServer - 設定NTP服務 - - - - GetNtpServer - 獲取NTP服務資訊 - - - - SyncTime - 校準時間 - - - - DelPrograms - 清除節目 - - - - SetingSyncMethod - 設定同步方法 - - - + GetCurrentSensorBrightness 獲取當前亮度 - + Cur brightness 當前亮度 - - SetSpecialResolution - 設定分辯率 - - - - GetSpecialResolution - 讀取分辯率 - - - - totalResolution - 行数を含む解像度 - - - - strCurDisplayResolution - 當前顯示分辯率 - - - - CleanDisplayScreenSize - 恢復默認分辯率 - - - - SetMaxBrightness - 設定亮度最大值 - - - - GetMaxBrightness - 獲取亮度最大值 - - - - screenSwitch - 開關屏 - - - - - - YES - - - - - - - NO - - - - - LAN - 局域網 - - - + Connect 連接 - + timeout 超時 - + Anycast 點播 - - + volume 音量 - - - - - - - GetingSyncMethod - 獲取同步管道 - - - - - identificationCode - 識別碼 - - - - - delaySync - 時間偏移 - - - - - msec - 毫秒 - - - - - - - OtherSyncItem - 其他同步項 - - - - - - - lastSynchronousTime - 上次同步時間 - - - - checkNtpTime - 同步間隔 - - - - Uploadding - 上傳 - - - + Success 成功 - + failed 失敗 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + success 成功 - - - Lora identity - Lora身份 - - - - Master - - - - - Slave - - - - - SetBrightnessSensitivity - 設定亮度感測器靈敏度 - - - - - + + + on - - - + + + off @@ -4131,114 +3659,114 @@ DevicePanel - + All 總數 - + Online 在线 線上 - - + + Refresh 檢測 - - - + + + Specify IP 指定IP 指定IP - + Current Screen 当前屏幕 - + none - + - + Specify IP list 指定IP清單 - + Search 蒐索 - - + + Attention 注意 - - + + Please input IP address! 請輸入IP地址! - + Cancel 取消 - - - Screen ID - 荧幕ID - - - - Screen IP - 荧幕IP - - - - Screen Size - 荧幕點數 - + Screen ID + 螢幕ID + + + + Screen IP + 螢幕IP + + + + Screen Size + 螢幕點數 + + + Remark Name 別名 - + readback pic 回讀畫面 - + send 發送 - + More Info 詳細資訊 - + Cur Brightness - 荧幕當前亮度 + 螢幕當前亮度 - + Power Status - 荧幕開關狀態 + 螢幕開關狀態 - + Security 加密 @@ -4271,7 +3799,7 @@ Open - 打开 + 打開 @@ -4283,7 +3811,7 @@ Time remaining - 剩余时间 + 剩餘時間 @@ -4313,7 +3841,7 @@ The installer will open separately - 安装程序将单独打开 + 安裝程式將單獨打開 @@ -4323,7 +3851,7 @@ In order to install the update, you may need to quit the application. This is a mandatory update, exiting now will close the application - 要安装更新,可能需要退出应用程序。这是强制更新,现在退出将关闭应用程序 + 要安裝更新,可能需要退出應用程序。 這是強制更新,現在退出將關閉應用程序 @@ -4333,17 +3861,17 @@ Click the "Open" button to apply the update - 单击“打开”按钮应用更新 + 按一下“打開”按鈕應用更新 Are you sure you want to cancel the download? - 您想现在下载更新吗? + 您想現在下載更新嗎? Are you sure you want to cancel the download? This is a mandatory update, exiting now will close the application - 确实要取消下载吗?这是强制更新,现在退出将关闭应用程序 + 確實要取消下載嗎? 這是強制更新,現在退出將關閉應用程序 @@ -4376,7 +3904,7 @@ Time Remaining - 剩余时间 + 剩餘時間 @@ -4386,22 +3914,22 @@ about %1 hours - 约%1小时 + 約%1小時 about one hour - 约1小时 + 約1小時 %1 minutes - %1 分钟 + %1 分鐘 1 minute - 1 分钟 + 1 分鐘 @@ -4415,39 +3943,156 @@ - EAudio + EAClock - + Basic Properties 基本屬性 - - File - 檔案 + + Time Zone + 時區 - + + Custom Dial + 自定義錶盤 + + + + Select + 選擇 + + + + Select Dail file + 選擇錶盤圖片 + + + + Hour Mark + 時標 + + + + + Circular + 圓形 + + + + + Rectangle + 矩形 + + + + Number + 數位 + + + + + + T + + + + + Min Mark + 分標 + + + + Color + 顏色 + + + + Length + + + + + Width + + + + + Hour Hand + 時針 + + + + Min Hand + 分針 + + + + Sec Hand + 分針 + + + + Show + 顯示 + + + + Text + 文字 + + + Play Properties 播放管道 - + Play Duration 播放時長 - + + s + + + + + EAudio + + + Basic Properties + 基本屬性 + + + + File + 檔案 + + + + Play Properties + 播放管道 + + + + Play Duration + 播放時長 + + + Select File 選擇檔案 - + s - + Audio 音訊 @@ -4455,233 +4100,373 @@ EBase - + Area 區域(px) - + X - + Y - + W - + H - + Border 邊框 - - + + None - + Effect 特效 - + Rotate 旋轉 - + Blink 閃爍 - + Speed 速度 - + Slow - + Moderate - + Fast - EEnviron + EDClock - - - - - - - - north - + + MON + 星期一 - - - - - - - - east - + + TUE + 星期二 - - - - - - - - south - + + WED + 星期三 - - - - - - - - west - 西 + + THU + 星期四 - - - Temperature - 溫度 + + FRI + 星期五 - - - Humidity - 濕度 + + SAT + 星期六 - - - Noise - 譟音 + + SUN + 星期日 - - Wind Speed - 風速 + + + AM + 上午 - - Wind Direction - 風向 + + + PM + 下午 - + Basic Properties 基本屬性 - - Title - 標題 + + Time Zone + 時區 - - Compensation - 補償 + + Year + - - Wind speed - 風速 + + Month + - - Wind direction - 風向 + + Day + - - Left - 靠左 + + Hour + - - Center - 居中 + + Min. + - - Right - 靠右 + + Sec. + - - Single scroll - 單行滾動 + + Weekly + 星期 - - Speed - 速度 + + Full Year + 四位年 - - ms/pixel - 毫秒/點數 + + 12-Hour + 12小時制 - - Back Color - 背景色 + + Date Style + 日期風格 - + + Time Style + 時間風格 + + + + Display Style + 顯示風格 + + + + Multiline + 多行顯示 + + + Play Properties 播放管道 - - Refresh Cycle - 重繪週期 - - - - min. - 分鐘 - - - + Play Duration 播放時長 - + + s + + + + + EEnviron + + + + + + + + + north + + + + + + + + + + + east + + + + + + + + + + + south + + + + + + + + + + + west + 西 + + + + + Temperature + 溫度 + + + + + Humidity + 濕度 + + + + + Noise + 譟音 + + + + Wind Speed + 風速 + + + + Wind Direction + 風向 + + + + Basic Properties + 基本屬性 + + + + Title + 標題 + + + + Compensation + 補償 + + + + Wind speed + 風速 + + + + Wind direction + 風向 + + + + Left + 靠左 + + + + Center + 居中 + + + + Right + 靠右 + + + + Single scroll + 單行滾動 + + + + Speed + 速度 + + + + ms/pixel + 毫秒/點數 + + + + Back Color + 背景色 + + + + Play Properties + 播放管道 + + + + Refresh Cycle + 重繪週期 + + + + min. + 分鐘 + + + + Play Duration + 播放時長 + + + s @@ -4689,37 +4474,37 @@ EGif - + Basic Properties 基本屬性 - + File 檔案 - + Select File 選擇檔案 - + Play Properties 播放管道 - + Play Duration 播放時長 - + s - + Play Times 播放次數 @@ -4727,73 +4512,73 @@ EMultiWin - + Please add media on the right 請在右邊添加媒體,可以加入多個不同媒體,LED顯示幕將按清單先後順序播放 - + Media List 媒體清單 - - - + + + Text 文字 - - - + + + Photo 圖片 - - - + + + Video 視頻 - - - + + + Gif 動畫 - - - + + + DClock 數位時鐘 - - - + + + AClock 圓形時鐘 - - - + + + Select File 選擇檔案 - - + + Environment 環境監測 - - + + Timer 計時器 @@ -4801,118 +4586,118 @@ EPhoto - + Basic Properties 基本屬性 - + File 檔案 - + Select File 選擇檔案 - + Image Read Error 圖片讀取錯誤 - + Play Properties 播放管道 - + Play Duration 播放時長 - - + + s - + Enter Style 入場特效 - + None - + Alpha_In 淡入 - + Moving to left 連續左移 - + Moving to right 連續右移 - + Moving to top 連續上移 - + Move to bottom 連續下移 - + Zoom in 放大 - + Zoom in to left_bottom 左下角放大 - + Zoom in to left_top 左上角放大 - + Zoom in to right_top 右上角放大 - + Zoom in to right bottom 右下角放大 - + Rotate to right 向右旋轉 - + Rotate to left 向左旋轉 - + Enter Duration 特效時長 - + Images (*.png *.jpg *.jpeg *.bmp) 圖片(*.png *.jpg *.jpeg *.bmp) @@ -4920,191 +4705,191 @@ EText - + Enter your text 請輸入內容 - + Basic Properties 基本屬性 - - Font Color - 字體色 - - - + Back Color 背景色 - + Kerning 字間距 - + Line Spacing 行距 - + PageCount: 總頁數: - + page - + Import txt File 導入 txt 檔案 - + Select File 選擇檔案 - + Fail 失敗 - + File Open Fail 檔案打開失敗 - + Play Properties 播放管道 - + Flip 翻頁 - + Scroll 滾動 - + Static 靜態 - - - + + + Play Duration 播放時長 - + Duration/Page 每頁播放時長 - + Effect time 特效時長 - - + + Tip Info 提示 - - + + Effect time cannot be longer than duration time 特效時長不能大於播放時長 - + s - + + Text Color + 文字顏色 + + + + Colorful Text + 炫彩文字 + + + Entrance Effect 入場特效 - + no - + random 隨機 - + right to left 連續左移 - + bottom to top 連續上移 - + left to right 連續右移 - + top to bottom 連續下移 - - Head-Tail Connected - 首尾相接 - - - + Head-Tail Spacing 首尾間隔 - + Scroll Style 滾動方向 - + Right -> Left 向左 - + Bottom -> Top 向上 - + Left -> Right 向右 - + Top -> Bottom 向下 - + Scroll Speed 滾動速度 @@ -5112,87 +4897,87 @@ ETimer - + day - + hour - + min - + sec - + Basic Properties 基本屬性 - + Count Down 倒數計時 - + Count Up 正計時 - + Time 目標時間 - + Day - + Hour - + Min - + Sec - + Multiline 多行顯示 - + Text 文字 - + Play Properties 播放管道 - + Play Duration 播放時長 - + s @@ -5200,64 +4985,64 @@ EVideo - + Basic Properties 基本屬性 - + File 檔案 - + Play Properties 播放管道 - + Play Duration 播放時長 - + Select File 選擇檔案 - + s - + Play Times 播放次數 - + Video Transcoding - - + + Video Transcoding Progress 視頻轉碼進度 - - + + Error 錯誤 - + Video 視頻 - + Flash 動畫 @@ -5265,17 +5050,17 @@ EWeb - + Basic Properties 基本屬性 - + Play Duration 播放時長 - + s @@ -5303,10 +5088,93 @@ + + GenTmpThread + + + Preparing ... + 準備中… + + + + MON + 星期一 + + + + TUE + 星期二 + + + + WED + 星期三 + + + + THU + 星期四 + + + + FRI + 星期五 + + + + SAT + 星期六 + + + + SUN + 星期日 + + + + AM + 上午 + + + + PM + 下午 + + + + day + + + + + hour + + + + + min + + + + + sec + + + + + Create json ... + 生成json… + + + + Scan program ... + 掃描節目… + + LoColorSelector - + Transparent 透明 @@ -5349,186 +5217,230 @@ MainWindow - + Language 語言 - + Help 幫助 - - + + Check for updates 檢查更新 - - + + firmware manager 固件管理 - - - Software Configuration + + + Software Config 軟件配寘 - - + + Info 資訊 - - + + About 關於 - - + + Setting 設定 - + + Software Update + 軟體更新 + + + + CurVersion + 當前版本 + + + + Update + 更新 + + + + LatestVersion: + 最新版本: + + + + + Update log: + 更新日誌: + + + + The current version is already the latest version + 已經是最新的版本 + + + Device 設備管理 - + Program 節目管理 - + Control 終端控制 - + GuangYinPin 光影屏 - + Check card - 一键找卡 + 一鍵找卡 - + Tip Info 提示 - + RestoreLedCardIpByUdpTip 該操作會把局域網內的所有與電腦IP不在同一網段的控制卡修復成固定IP,請謹慎操作! + + Net + + + Connection Timeout + 連接超時 + + + + Error + 錯誤 + + PageEditor - + Zoom In 放大 - + Zoom Out 縮小 - + Original size 原始比例 - + Delete the secect media 删除選中的媒體 - + Clear all media 清空所有媒體 - + Move layer up 向上一層(快速鍵PgUp) - + Send backward 向下一層(快速鍵PgDn) - + Bring to front 圖層置頂(快速鍵Home) - + Move to the bottom layer 圖層置底(快速鍵End) - + Fill the entire screen 全屏鋪滿 - + Fill the screen horizontally 水准鋪滿 - + Fill the screen vertically 垂直鋪滿 - + Align top 垂直靠頂 - + Center vertically 垂直居中 - + Bottom align 垂直靠底 - + Align left 水准靠左 - + Center horizontally 水准居中 - + Align right 水准靠右 - + Tip Info 提示 - + Clear all medias? 清除所有媒體? @@ -5536,79 +5448,84 @@ PageListItem - + times - + Page name 節目名稱 - + New 新建 - + Play times 播放次數 - + + Sources Repeat + 素材迴圈 + + + Audios 音訊 - + Total Dur 總時長 - - + + s - + Select File 選擇檔案 - + Duration 時長 - + Vol 音量 - + Valid Date 有效日期 - - + + Warning 警告 - + Start Time can't be later than End Time 開始時間不能晚於結束時間 - + End Time can't be earlier than Start Time 結束時間不能早於開始時間 - + Plan 時間計畫表 @@ -5637,17 +5554,17 @@ PlayWin - + Move to Top Left 移動到左上角 - + Set Position 設定位置 - + Close 關閉 @@ -5655,12 +5572,12 @@ PlayerBackSendThread - + Open file failed 檔案打開失敗 - + Read file failed 檔案讀取失敗 @@ -5681,47 +5598,47 @@ ProgCreateDlg - + Resolution 分辯率 - + Solution Information 節目資訊 - + Solution Name 節目名稱 - + Width - + Height - + Remarks 備註 - - 节目超宽需要打折, 请输入打折宽度 - + + 每段打折宽度 (用空格分隔) + 每段讓利寬度(用空格分隔) - + OK 確認 - + Cancel 取消 @@ -5729,221 +5646,200 @@ ProgEditorWin - + Save 保存 - - + + Save as 另存為 - + Setting 設定 - + Text 文字 - + Photo 圖片 - + Video 視頻 - + Gif 動畫 - + Clock 數位時鐘 - + Analog Clock 圓形時鐘 - + Environment 環境監測 - + Web 網頁 - + MuliContentWindow 多素材視窗 - + In this window, a plurality of different program materials can be added and played according to the order of joining the list; 該視窗中可以加入多個不同是節目素材,並按照加入列表的先後順序播放 - + Timer 計時器 - + Play 播放 - + Stop 停止 - + Publish 發佈 - - - - + + + + Select File 選擇檔案 - + program 節目清單 - + Add page 添加頁面 - + Copy page 複製頁面 - + Delete page 删除頁面 - - + + Tip Info 提示 - + Are you sure you want to delete this program page? 確定要删除該節目頁嗎? - + Move up 向上移動一個頁面 - + Move down 向下移動一個頁面 - + widget properties 組件内容 - + Page properties 節目内容 - + Do you want to save the modifications? 是否保存修改? - - + + Saving... 正在保存… - - + + Success 成功 - - + Save failed 保存失敗 - + Convertering 整理數據中 - - Converter Successed - 整理成功 - - - - Converter TimeOut - 整理超時 - - - + Generate preview data 生成預覽數據 - - Ready - 準備完畢 - - - - Generate TimeOut - 超時 - - - - + + Error 錯誤 - + Rename fail when saving - + Remove Recursively fail when saving - + Warning 警告 @@ -5951,155 +5847,177 @@ ProgItem - - + + ExportButtonTip U盤播放 - - + + SendButtonTip 發佈 - - + + Convertering 整理數據中 - - - USB Export Successed - U盤匯出成功 - - - - USB Export TimeOut - U盤匯出失敗 - - - - Converter Successed - 整理成功 - - - - Converter TimeOut - 整理超時 - ProgPanel - - + + New 新建 - - + + Edit 編輯 - - + + Delete 删除 - - + + + Import 導入 - - + + + Export 匯出 - - + + Send 發送 - - + + Publish 發佈 - - + + Name 名稱 - - + + + Choose Directory + 選擇目錄 + + + + Tip + 提示 + + + + The imported directory is already in the working directory, so there is no need to import it again! + 該導入的目錄已經在工作目錄下,無需再次導入! + + + + :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? + :節目已存在。是否確實要覆蓋現有節目? + + + + Play 播放 - - + + Stop 停止 - - + + Resolution 分辯率 - - + + File Size 文件大小 - - + + Last Modify 最後修改時間 - - + + Usb playback U盤更新 - + Program name conflicted 節目名稱重複 - + Warning 警告 - + You will delete the selected solution(s),are you sure? 是否確認删除選中的節目? - + + Tip Info 提示 + + ProgPortDlg + + + Solution Name + 節目名稱 + + + + Progress + 進度 + + + + Done + 完成 + + QObject - + Setting up the LedOK Express... 初始化LedOK Express… @@ -6107,18 +6025,18 @@ SendProgThread - - + + Program is empty 節目為空 - + Open file failed 檔案打開失敗 - + Read file failed 檔案讀取失敗 @@ -6126,73 +6044,73 @@ SendProgramDialog - - + + Publish 發佈 - + success info - + Refresh 檢測 - + Cancel 取消 - + Screen ID - 荧幕ID + 螢幕ID - + Remark Name 別名 - + Online 線上 - + Screen IP - 荧幕IP + 螢幕IP - + Screen Size - 荧幕點數 + 螢幕點數 - + Security 加密 - + Progress 進度 - + Remarks 備註 - + This screen is encrypted - 荧幕已加密 + 螢幕已加密 - + All 總數 @@ -6200,12 +6118,12 @@ SoftConfigDialog - - Software Configuration + + Software Config 軟件配寘 - + Video compress to 視頻壓縮成 @@ -6215,200 +6133,31 @@ 視頻轉碼成 - + Text antialiasing 文字反鋸齒 - + TextAntilaTip - (提示:該選項適合小間距大尺寸的荧幕,選中此項,文字邊緣會有暗影已達到字體邊緣光滑的效果;小尺寸荧幕和單雙色荧幕不建議使用) + (提示:該選項適合小間距大尺寸的螢幕,選中此項,文字邊緣會有暗影已達到字體邊緣光滑的效果;小尺寸螢幕和單雙色螢幕不建議使用) - + GuangYinPin 光影屏 - + + Width Split + 超長屏打折 + + + OK 確認 - - SpecialDlg - - Specify IP - 指定IP - - - Search - 蒐索 - - - Cancel - 取消 - - - Attention - 注意 - - - Please input IP address! - 請輸入IP地址! - - - Your IP Address is Invalid! - IP地址無效! - - - Error - 錯誤 - - - - ThreadUpgradeApk - - - Uploadding - 正在上傳 - - - - TipDialog - - - TextLabel - - - - - - OK - 確認 - - - - - Cancel - 取消 - - - - X - X - - - - - Import - 導入 - - - - - Path - 路徑 - - - - - : - - - - - - browse - 選擇 - - - - You will delete the selected solution(s),are you sure? - 是否確認删除選中的節目? - - - - - Export - 匯出 - - - - - Done - 完成 - - - - - Solution Name - 節目名稱 - - - - - Progress - 進度 - - - - Delete - 删除 - - - - Select the network to connect to the device - 選擇和LED控制卡直連的網絡 - - - - Network name - 網絡名稱 - - - - - This operation will only set cable network to static IP,are you sure? - 此操作將設定選中的網絡為固定IP,並自動配寘直連的LED設備為同一網段的IP地址,是否確認? - - - - Do you want set IP of cable network to DHCP - 是否設定網絡為通過DHCP自動獲取IP - - - - - - - - Tip - 提示 - - - - - - Please select the network to connect to the Led controller - 請選擇連接到LED控制器的網絡 - - - - Choose Directory - 選擇目錄 - - - - The imported directory is already in the working directory, so there is no need to import it again! - 該導入的目錄已經在工作目錄下,無需再次導入! - - - - no find program can be imported - 沒有找到可以導入的節目 - - UpdateLedset3Dialog @@ -6440,7 +6189,7 @@ Apk is download finished from internet,you can select LED Screen SYNC firmware now! - 固件APK成功下載,您可以選擇需要的LED荧幕同步固件! + 固件APK成功下載,您可以選擇需要的LED螢幕同步固件! @@ -6455,7 +6204,7 @@ The current version is already the latest version,,you can select LED Screen SYNC firmware now! - 當前固件APK版本已經是最新版本,您可以選擇需要的LED荧幕同步固件! + 當前固件APK版本已經是最新版本,您可以選擇需要的LED螢幕同步固件! @@ -6481,262 +6230,315 @@ 祝賀你!您正在運行最新版本的%1 - - UpdaterDialog - - - Software Update - 软件更新 - - - - X - X - - - - V1.0 - - - - - Update - 陞級 - - - - CurVersion - 當前版本 - - - - LatestVersion: - 最新版本: - - - - - Update log: - 更新日誌: - - - - The current version is already the latest version - 已經是最新的版本 - - UpgradeApkDialog - - - Upgrade apk - 陞級apk + + Update APK + 更新APK - - 口 - - - - - X - - - - - + Select apk 選擇Apk包 - - - - + Upgrade 陞級 - - - APK: - - - - - + Uninstall 卸載 - - + check running state 檢測運行狀態 - - + Select Fpga 選擇FPGA檔案 - - - success info - + + Installing + 正在安裝 - - + Refresh 檢測 - - + Cancel 取消 - + Screen ID - 荧幕ID + 螢幕ID - + Remark Name 別名 - + Online 線上 - + Screen IP - 荧幕IP + 螢幕IP - + Security 加密 - + Progress 進度 - + xixunplayer - + cardsystem - + taxiapp - + starter - + connection - + displayer - + FPGA FPGA - + update - + State 陳述 - - - + + All 總數 - + + This screen is encrypted + 螢幕已加密 + + + + + Select Online APK + 選擇線上APK + + + + No Files + 沒有檔案 + + + + Name + 名稱 + + + + Size + 大小 + + + + Create Time + 創建時間 + + + + + + Tip + 提示 + + + + Is upgrading now. Please wait + 正在更新,請稍後 + + + + NoSelectedController + 請先選擇大螢幕 + + + + + Downloading Online File + 正在下載線上檔案 + + + + + Error + 錯誤 + + + + Online file is empty + 線上檔案為空 + + + + Uploading + + + + + Upload error + 上傳錯誤 + + + + Install error + 安裝錯誤 + + + + Install success + 安裝成功 + + + + Reminder + 提示 + + + + Reminder: Uninstalling this program may cause the device to offline, cannot be found, lost configs and have a black screen. Please uninstall with caution! + 提示:卸載此程式會導致平臺掉線,找不到設備,配寘參數遺失和黑屏問題,請謹慎卸載! + + + + Do you want to continue? + 是否繼續? + + + + Uninstalling + 正在卸載 + + + + Uninstall error + 卸載錯誤 + + + + Uninstall success + 卸載成功 + + + + Check apk running status + 監測APK運行狀態 + + + + Check error + 檢查錯誤 + + + + Running + 正在運行 + + + + Not running + 沒有運行 + + + The encrypted control card can be upgraded directly 加密控制卡可以直接陞級 - - - apk package (*.rpd) - - - - - apk package (*.apk *.zip) - - UsbDetectDialog - + Usb upgrade program U盘更新节目 - + Password - + OK 確認 - + Input password 輸入密碼 - - + + Tip 提示 - + No checked USB device 未檢查USB設備 - + please select usb device in list 請在清單中選擇usb設備 - + Cancel 取消 @@ -6744,7 +6546,7 @@ WaitingDlg - + Success 成功 @@ -6773,331 +6575,6 @@ 取消 - - eAClock - - - Basic Properties - 基本屬性 - - - - Time Zone - 時區 - - - - Custom Dial - 自定義錶盤 - - - - Select - 選擇 - - - - Select Dail file - 選擇錶盤圖片 - - - - Hour Mark - 時標 - - - - - Circular - 圓形 - - - - - Rectangle - 矩形 - - - - Number - 數位 - - - - - - T - - - - - Min Mark - 分標 - - - - Hand Color - 指針顏色 - - - - H - - - - - M - - - - - S - - - - - Text - 文字 - - - - Play Properties - 播放管道 - - - - Play Duration - 播放時長 - - - - s - - - - - eDClock - - - MON - 星期一 - - - - TUE - 星期二 - - - - WED - 星期三 - - - - THU - 星期四 - - - - FRI - 星期五 - - - - SAT - 星期六 - - - - SUN - 星期日 - - - - - AM - 上午 - - - - - PM - 下午 - - - - Basic Properties - 基本屬性 - - - - Time Zone - 時區 - - - - Year - - - - - Month - - - - - Day - - - - - Hour - - - - - Min. - - - - - Sec. - - - - - Weekly - 星期 - - - - Full Year - 四位年 - - - - 12-Hour - 12小時制 - - - - Date Style - 日期風格 - - - - Time Style - 時間風格 - - - - Display Style - 顯示風格 - - - - Multiline - 多行顯示 - - - - Play Properties - 播放管道 - - - - Play Duration - 播放時長 - - - - s - - - - - GenTmpThread - - - Preparing ... - 準備中… - - - - MON - 星期一 - - - - TUE - 星期二 - - - - WED - 星期三 - - - - THU - 星期四 - - - - FRI - 星期五 - - - - SAT - 星期六 - - - - SUN - 星期日 - - - - AM - 上午 - - - - PM - 下午 - - - - day - - - - - hour - - - - - min - - - - - sec - - - - - Create json ... - 生成json… - - - - Scan program ... - 掃描節目… - - mGuangYingPinWidget @@ -7295,7 +6772,7 @@ Open - 打开 + 打開 @@ -7502,68 +6979,55 @@ 串口打開失敗 - - wExportProgramItem - - - Tip Info - 提示 - - - - :solution(s) already exist.are you sure you want to overwrite the existing solution(s)? - :節目已存在。是否確實要覆蓋現有節目? - - wPlanItem - + Form Form - + 1 1 - + Every week: 每週: - + M - + Tu - + W - + Th - + F - + Sa - + Su @@ -7571,30 +7035,30 @@ wProgramPublishItem - + Input password 輸入密碼 - - - + + + Error 錯誤 - - + + Tip Info 提示 - + Fail 失敗 - + password is wrong 密碼錯誤 @@ -7602,92 +7066,24 @@ wUpgradeApkItem - + Input password 輸入密碼 - - uninstalling - 正在卸載 + + Error + 錯誤 - - - IsSoftwareRunning - 監測APK運行狀態 - - - - - This screen is encrypted - 荧幕已加密 - - - - - Start upgrading - 開始陞級 - - - - - Timeout - 超時 - - - - install start... - 開始安裝… - - - - - SynchronousHardwareVersion - 同步FPGA - - - + Tip Info 提示 - + password is wrong 密碼錯誤 - - - - UninstallSoftware - 卸載 - - - - - Success - 成功 - - - - Running - 正在運行 - - - - NoRunning - 沒有運行 - - - - install success - 安裝成功 - - - - - Fail - 失敗 - diff --git a/LedOK/wDevicesManager/controlencryptwidget.cpp b/LedOK/wDevicesManager/controlencryptwidget.cpp deleted file mode 100644 index 69cf55a..0000000 --- a/LedOK/wDevicesManager/controlencryptwidget.cpp +++ /dev/null @@ -1,290 +0,0 @@ -#include "controlencryptwidget.h" -#include "ui_controlencryptwidget.h" -#include "base/x_uimsgboxok.h" -#include "QFileDialog" -#include -#include -#include -#include -#include "tools.h" - -extern QWidget *gMainWin; - -ControlEncryptWidget::ControlEncryptWidget(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlEncryptWidget) -{ - m_pLedlist=list; - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - ui->pushButtonSetPassword->setProperty("ssType", "progManageTool"); - ui->pushButtonCancelPassword->setProperty("ssType", "progManageTool"); - //按钮事件绑定 - connect(ui->pushButtonSetPassword,SIGNAL(clicked()),this,SLOT(OnSetPassword())); - connect(ui->pushButtonCancelPassword,SIGNAL(clicked()),this,SLOT(OnCancelPassword())); - MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent) - } - -ControlEncryptWidget::~ControlEncryptWidget() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} - -void ControlEncryptWidget::refreshLable() -{ - ui->labelNewPassword->setText(tr("New password")); - ui->labelRepeatPassword->setText(tr("Enter password")); - ui->labelOriginalPassword->setText(tr("original password")); - ui->labelEntryptConfiguration->setText(tr("Entrypt Configuration")); - ui->lineEditNewPassword->setPlaceholderText(tr("New password")); - ui->lineEditRepeatPassword->setPlaceholderText(tr("Repeat new password")); - ui->lineEditOriginalPassword->setPlaceholderText(tr("original password")); - ui->pushButtonSetPassword->setText(tr("Set encryption")); - ui->pushButtonCancelPassword->setText(tr("Cancel encryption")); -} - -void ControlEncryptWidget::OnSetPassword() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - - if(ui->lineEditOriginalPassword->isVisible()) - { - if(ui->lineEditOriginalPassword->text().isEmpty()) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputOriginalPasswordTip"),this,1); - pDlg->exec(); - return; - } - } - - if(ui->lineEditNewPassword->text().isEmpty()) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputNewPasswordTip"),this,1); - pDlg->exec(); - return; - } - if(ui->lineEditRepeatPassword->text().isEmpty()) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputRepeatPasswordTip"),this,1); - pDlg->exec(); - return; - } - if(ui->lineEditNewPassword->text()!=ui->lineEditRepeatPassword->text()) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputRepeatPasswordNotSameTip"),this,1); - pDlg->exec(); - return; - } - auto res = QMessageBox::information(gMainWin, tr("Tip Info"), tr("After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation?"), QMessageBox::Ok, QMessageBox::Cancel); - if(res == QMessageBox::Ok) { - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetControllerPassword"); - json.insert("pwd", ui->lineEditOriginalPassword->text()); - json.insert("newPwd", ui->lineEditNewPassword->text()); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetControllerPassword"),tr("Success"),tr("failed")) - } -} -void ControlEncryptWidget::OnCancelPassword() -{ - if(ui->lineEditOriginalPassword->isVisible()) - { - if(ui->lineEditOriginalPassword->text().isEmpty()) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputOriginalPasswordTip"),this,1); - pDlg->exec(); - return; - } - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetControllerPassword"); - json.insert("pwd", ui->lineEditOriginalPassword->text()); - json.insert("newPwd",""); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetControllerPassword"),tr("Success"),tr("failed")) -} -void ControlEncryptWidget::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - if(m_pLedlist==nullptr) - return; - MACRO_DEFINE_CONTROL_FUNC3 -} -void ControlEncryptWidget::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_Encrypt) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlEncryptWidget::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "HasControllerPassword"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - MACRO_DEFINE_TIPDLG_ALL_FUCN(tr("Readback"),tr("Success"),tr("failed")) -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlEncryptWidget::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<<"DeviceItem OnProHttpResponse 解析json文件错误!"; - return; - } - QJsonObject jsonObject = document.object(); - QString strType=jsonObject["_type"].toString(); - if(jsonObject["success"].toBool()==true) - { - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "HasControllerPassword") - { - if(jsonObject["result"].toBool()) - {//已经加密 - ui->labelOriginalPassword->show(); - ui->lineEditOriginalPassword->show(); - ui->pushButtonCancelPassword->show(); - ui->pushButtonSetPassword->setText(tr("Modify password")); - m_pLedCard->bPassword=true; - - } - else {//没有加密 - ui->labelOriginalPassword->hide(); - ui->lineEditOriginalPassword->hide(); - ui->pushButtonCancelPassword->hide(); - ui->pushButtonSetPassword->setText(tr("Set encryption")); - m_pLedCard->bPassword=false; - } - } - else if(strType == "SetControllerPassword") - { - if(jsonObject["result"].toInt()==0) - {//原始密码正确 - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "HasControllerPassword"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - ui->lineEditNewPassword->clear(); - ui->lineEditRepeatPassword->clear(); - ui->lineEditOriginalPassword->clear(); - } - else {//原始密码错误 - MACRO_ASKTIME_STOP - if(m_PostingDlg!=nullptr) - { - m_PostingDlg->SetFailedTipString(tr("OriginalPasswordErrorTip")); - m_PostingDlg->TimerOutUnlock(); - } - ui->lineEditNewPassword->clear(); - ui->lineEditRepeatPassword->clear(); - ui->lineEditOriginalPassword->clear(); - return; - - } - } - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} - -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlEncryptWidget::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<<"DeviceItem OnProHttpResponse 解析json文件错误!"; - return; - } - QJsonObject jsonObject = document.object(); - QString strType=jsonObject["_type"].toString(); - if(jsonObject["success"].toBool()==true) - { - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "HasControllerPassword") - { - if(jsonObject["result"].toBool()) - {//已经加密 - ui->labelOriginalPassword->show(); - ui->lineEditOriginalPassword->show(); - ui->pushButtonCancelPassword->show(); - ui->pushButtonSetPassword->setText(tr("Modify password")); - m_pLedCard->bPassword=true; - - } - else {//没有加密 - ui->labelOriginalPassword->hide(); - ui->lineEditOriginalPassword->hide(); - ui->pushButtonCancelPassword->hide(); - ui->pushButtonSetPassword->setText(tr("Set encryption")); - m_pLedCard->bPassword=false; - - } - - } - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -void ControlEncryptWidget::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} diff --git a/LedOK/wDevicesManager/controlencryptwidget.h b/LedOK/wDevicesManager/controlencryptwidget.h deleted file mode 100644 index cb30b49..0000000 --- a/LedOK/wDevicesManager/controlencryptwidget.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef CONTROLENCRYPTWIDGET_H -#define CONTROLENCRYPTWIDGET_H - -#include -#include -#include -#include -namespace Ui { -class ControlEncryptWidget; -} - -class ControlEncryptWidget : public QWidget -{ - Q_OBJECT - -public: - explicit ControlEncryptWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlEncryptWidget(); -private: - Ui::ControlEncryptWidget *ui; -protected slots: - void DeletePostingDlg(); - void OnSetPassword(); - void OnCancelPassword(); - void refreshLable(); - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigSend(QJsonObject &,QString); - protected slots: - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; -}; - -#endif // CONTROLENCRYPTWIDGET_H diff --git a/LedOK/wDevicesManager/controlencryptwidget.ui b/LedOK/wDevicesManager/controlencryptwidget.ui deleted file mode 100644 index af45b1a..0000000 --- a/LedOK/wDevicesManager/controlencryptwidget.ui +++ /dev/null @@ -1,336 +0,0 @@ - - - ControlEncryptWidget - - - - 0 - 0 - 572 - 412 - - - - - 0 - 0 - - - - Form - - - background-color: #F5F5F5; - - - - - - - 0 - 0 - - - - - Arial - 12 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - Entrypt Configuration - - - Qt::AlignCenter - - - - - - - Qt::Horizontal - - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 20 - - - - - - - - - 330 - 16777215 - - - - - - - false - - - false - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Original password - - - - - - - Enter password - - - - - - - Enter again - - - - - - - - - - - - 0 - 30 - - - - background-color: #FFFFFF; - - - QLineEdit::PasswordEchoOnEdit - - - original password - - - - - - - - 160 - 30 - - - - - 160 - 16777215 - - - - background-color: #FFFFFF; - - - - - - QLineEdit::PasswordEchoOnEdit - - - New password - - - - - - - - 160 - 30 - - - - - 160 - 16777215 - - - - background-color: #FFFFFF; - - - - - - QLineEdit::PasswordEchoOnEdit - - - Repeat new password - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - 0 - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 20 - - - - - - - - - 60 - 30 - - - - Set encryption - - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 20 - - - - - - - - - 60 - 30 - - - - Cancel encryption - - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 20 - - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - diff --git a/LedOK/wDevicesManager/controlhdmischedule.cpp b/LedOK/wDevicesManager/controlhdmischedule.cpp deleted file mode 100644 index a5b60ff..0000000 --- a/LedOK/wDevicesManager/controlhdmischedule.cpp +++ /dev/null @@ -1,523 +0,0 @@ -#include "controlhdmischedule.h" -#include "ui_controlhdmischedule.h" -#include "base/x_uimsgboxok.h" -#include "QFileDialog" -#include "QDir" -#include -#include -#include -#include -#include -#include -#include "cfg.h" -#include "QSettings" -#include "base/x_spinboxdelegate.h" -#include "base/x_timeeditdelegate.h" -#include "base/x_checkboxdelegate.h" -#include "tools.h" -ControlHdmiSchedule::ControlHdmiSchedule(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlHdmiSchedule) -{ - m_pLedlist=list; - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - ui->labelSyncScheduleTip->setVisible(false); - - ui->pushButtonAdd->setProperty("ssType", "progManageTool"); - ui->pushButtonAdd->setFlat(true); - ui->pushButtonDelete->setProperty("ssType", "progManageTool"); - ui->pushButtonDelete->setFlat(true); - ui->pushButtonClear->setProperty("ssType", "progManageTool"); - ui->pushButtonClear->setFlat(true); - ui->pushButtonApply->setProperty("ssType", "progManageTool"); - ui->pushButtonApply->setFlat(true); - ui->pushButtonImport->setProperty("ssType", "progManageTool"); - ui->pushButtonExport->setProperty("ssType", "progManageTool"); - ui->pushButtonReadback->setProperty("ssType", "progManageTool"); - - m_pModel = new QStandardItemModel(this); - m_pModel->setColumnCount(10); - m_pModel->setHeaderData(0,Qt::Horizontal, tr("SYNC HDMI")); - m_pModel->setHeaderData(1,Qt::Horizontal, tr("Start Time")); - m_pModel->setHeaderData(2,Qt::Horizontal, tr("End Time")); - m_pModel->setHeaderData(3,Qt::Horizontal, tr("SUN")); - m_pModel->setHeaderData(4,Qt::Horizontal, tr("MON")); - m_pModel->setHeaderData(5,Qt::Horizontal, tr("TUE")); - m_pModel->setHeaderData(6,Qt::Horizontal, tr("WED")); - m_pModel->setHeaderData(7,Qt::Horizontal, tr("THU")); - m_pModel->setHeaderData(8,Qt::Horizontal, tr("FRI")); - m_pModel->setHeaderData(9,Qt::Horizontal, tr("SAT")); - ui->tableView->setModel(m_pModel); - - X_timeEditDelegate *pStartTimeDelegate=new X_timeEditDelegate(this); - ui->tableView->setItemDelegateForColumn(1,pStartTimeDelegate); - ui->tableView->setItemDelegateForColumn(2,pStartTimeDelegate); - X_CheckBoxDelegate *WeekDelegate=new X_CheckBoxDelegate(this); - ui->tableView->setItemDelegateForColumn(3,WeekDelegate); - ui->tableView->setItemDelegateForColumn(4,WeekDelegate); - ui->tableView->setItemDelegateForColumn(5,WeekDelegate); - ui->tableView->setItemDelegateForColumn(6,WeekDelegate); - ui->tableView->setItemDelegateForColumn(7,WeekDelegate); - ui->tableView->setItemDelegateForColumn(8,WeekDelegate); - ui->tableView->setItemDelegateForColumn(9,WeekDelegate); - - - ReadOnlyDelegate1* readOnlyDelegate = new ReadOnlyDelegate1(); - ui->tableView->setItemDelegateForColumn(0, readOnlyDelegate); //设置某列只读 - - ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); - // ui->tableView->verticalHeader()->hide(); - ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); - ui->tableView->setFocusPolicy(Qt::NoFocus); - - - MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) - - connect(ui->pushButtonAdd,SIGNAL(clicked()),this,SLOT(OnClickAdd())); - connect(ui->pushButtonImport,SIGNAL(clicked()),this,SLOT(OnClickImport())); - connect(ui->pushButtonExport,SIGNAL(clicked()),this,SLOT(OnClickExport())); - connect(ui->pushButtonDelete,SIGNAL(clicked()),this,SLOT(OnClickDelete())); - connect(ui->pushButtonClear,SIGNAL(clicked()),this,SLOT(OnClickClear())); - connect(ui->pushButtonApply,SIGNAL(clicked()),this,SLOT(OnClickApply())); - connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnClickReadback())); -} - -ControlHdmiSchedule::~ControlHdmiSchedule() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} - -void ControlHdmiSchedule::refreshLable() -{ - ui->pushButtonAdd->setText(tr("Add")); - ui->pushButtonApply->setText(tr("Apply")); - ui->pushButtonClear->setText(tr("Clear")); - ui->pushButtonDelete->setText(tr("Delete")); - ui->pushButtonImport->setText(tr("Import")); - ui->pushButtonExport->setText(tr("Export")); - -} - -void ControlHdmiSchedule::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()==1) - { - ui->pushButtonReadback->setEnabled(true); - } - else { - ui->pushButtonReadback->setEnabled(false); - } - MACRO_DEFINE_CONTROL_FUNC3 - -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlHdmiSchedule::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetHdminScheduleTask") - { - - } - else if(strType == "etHdminScheduleTask") - { - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlHdmiSchedule::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetHdminScheduleTask") - { - - } - } - } -} - -void ControlHdmiSchedule::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_HDMI) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlHdmiSchedule::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetBrightness"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - -} -void ControlHdmiSchedule::OnClickAdd() -{ - QList Item; - Item.append(new QStandardItem(tr("On"))); - Item.append(new QStandardItem("00:00")); - Item.append(new QStandardItem("01:00")); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); -// Item.append(new QStandardItem(true)); - - Item.at(0)->setTextAlignment(Qt::AlignCenter); - Item.at(1)->setTextAlignment(Qt::AlignCenter); - Item.at(2)->setTextAlignment(Qt::AlignCenter); - m_pModel->appendRow(Item); - //m_lineEidt[i]->installEventFilter(this); - //Item.at(0)->setdsetValidator(new QRegExpValidator(rx, this)); - int i=m_pModel->rowCount()-1; - m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); - - if(m_pModel->rowCount()>0) - { - ui->labelSyncScheduleTip->setVisible(true); - } - else { - ui->labelSyncScheduleTip->setVisible(false); - } -} -void ControlHdmiSchedule::OnClickImport(){ - QSettings settings; - QString strDir="/"; - if(settings.value("lasOpendFileDlgtDir").isValid()) - { - strDir=settings.value("lasOpendFileDlgtDir").toString(); - } - QFileDialog dlg; - QString strBrightScheduleFile = QFileDialog::getOpenFileName(this, "open file dialog", - strDir, - tr("SyncSchedule (*.syncs)")); - if(strBrightScheduleFile.isEmpty()) return; - QFile fJson(strBrightScheduleFile); - if(fJson.open(QIODevice::ReadOnly)){ - QJsonDocument jBrightSchedule = QJsonDocument::fromJson(fJson.readAll()); - QJsonObject oTaskSync=jBrightSchedule.object(); - JieXiJsonTaskSync(oTaskSync); - fJson.close(); - } -} -bool ControlHdmiSchedule::JieXiJsonTaskSync(QJsonObject oTaskSync) -{ - OnClickClear(); - QJsonArray oSchedules; - oSchedules=oTaskSync["schedules"].toArray(); - if(oSchedules.count()>0) - { - ui->labelSyncScheduleTip->setVisible(true); - } - else - { - ui->labelSyncScheduleTip->setVisible(false); - } - for(int i=0;i Item; - Item.append(new QStandardItem(tr("On"))); - Item.append(new QStandardItem(oSchedule["startTime"].toString())); - Item.append(new QStandardItem(oSchedule["endTime"].toString())); - Item.at(0)->setTextAlignment(Qt::AlignCenter); - Item.at(1)->setTextAlignment(Qt::AlignCenter); - Item.at(2)->setTextAlignment(Qt::AlignCenter); - m_pModel->appendRow(Item); - if(oSchedule["filterType"].toString()=="None") - { - m_pModel->setData(m_pModel->index(i, 3),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 4),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 5),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 6),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 7),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 8),true,Qt::UserRole); - m_pModel->setData(m_pModel->index(i, 9),true,Qt::UserRole); - } - else if(oSchedule["filterType"].toString()=="Week") - { - QJsonArray oWeeks; - oWeeks=oSchedule["weekFilter"].toArray(); - for(int m=0;m<7;m++) - { - bool bHave=false; - for (int j=0;jsetData(m_pModel->index(i, m+3),bHave,Qt::UserRole); - } - - - } - - - - - } - if(oSchedules.count()>0) - return true; - else { - return false; - } -} -void ControlHdmiSchedule::OnClickExport() { - QSettings settings; - QString strDir="/"; - if(settings.value("lasOpendFileDlgtDir").isValid()) strDir=settings.value("lasOpendFileDlgtDir").toString(); - QFileDialog dlg; - QString saveFileName = dlg.getSaveFileName(this, tr("Save File"), strDir, tr("Sync Schedule (*.syncs)")); - if( saveFileName.isEmpty() ) return; - settings.setValue("lasOpendFileDlgtDir",saveFileName); - QJsonObject oTaskSync=GetJsonObjectSyncSchedule(); - QJsonDocument tSyncScheduleJsonDoc; - tSyncScheduleJsonDoc.setObject(oTaskSync); - - QFile f(saveFileName); - if(f.open(QIODevice::WriteOnly)) { - f.write(tSyncScheduleJsonDoc.toJson()); - f.close(); - } -} -void ControlHdmiSchedule::OnClickDelete() -{ - if(m_pModel->rowCount()>0) - { - QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); - if(selected.count()>0) - m_pModel->removeRows(selected.begin()->row(),selected.count()); - - } - if(m_pModel->rowCount()>0) - { - ui->labelSyncScheduleTip->setVisible(true); - } - else { - ui->labelSyncScheduleTip->setVisible(false); - } -} -void ControlHdmiSchedule:: OnClickClear() -{ - //QModelIndexList selected = ui->tableView->selectionModel()->selectedRows(0); - - if(m_pModel->rowCount()>0) - m_pModel->removeRows(0,m_pModel->rowCount()); - if(m_pModel->rowCount()>0) - { - ui->labelSyncScheduleTip->setVisible(true); - } - else { - ui->labelSyncScheduleTip->setVisible(false); - } - } -void ControlHdmiSchedule::OnClickApply() -{ - - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetTimingHdmiInTask"); - QJsonObject oTaskSync=GetJsonObjectSyncSchedule(); - json.insert("HdmiInTask", oTaskSync); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetTimingHdmiInTask"),tr("Success"),tr("failed")) - -} -void ControlHdmiSchedule::OnClickReadback() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetTimingHdmiInTask"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetTimingHdmiInTask"),tr("Success"),tr("failed")) - -} -QJsonObject ControlHdmiSchedule::GetJsonObjectSyncSchedule() -{ - QJsonObject oTaskSync; - QJsonArray oItems; - - oTaskSync["createDate"] = QJsonValue::Null; - oTaskSync["createBy"] = "alahover"; - oTaskSync["name"] = "TimingScreen"; - - QJsonArray oSchedules; - for(int i=0; irowCount(); i++) - { - - QJsonObject oSchedule; - oSchedule["timeType"] = "Range"; - oSchedule["startTime"] = m_pModel->data(m_pModel->index(i, 1)).toString();; - oSchedule["endTime"] = m_pModel->data(m_pModel->index(i, 2)).toString();; - oSchedule["dateType"] = "All"; - oSchedule["startDate"] = QJsonValue::Null; - oSchedule["endDate"] = QJsonValue::Null; - oSchedule["monthFilter"] = QJsonArray(); - - bool bSun=m_pModel->data(m_pModel->index(i, 3),Qt::UserRole).toBool(); - bool bMon=m_pModel->data(m_pModel->index(i, 4),Qt::UserRole).toBool(); - bool bTur=m_pModel->data(m_pModel->index(i, 5),Qt::UserRole).toBool(); - bool bWed=m_pModel->data(m_pModel->index(i, 6),Qt::UserRole).toBool(); - bool bThu=m_pModel->data(m_pModel->index(i, 7),Qt::UserRole).toBool(); - bool bFri=m_pModel->data(m_pModel->index(i, 8),Qt::UserRole).toBool(); - bool bSat=m_pModel->data(m_pModel->index(i, 9),Qt::UserRole).toBool(); - - - if(bMon && bTur && bWed && bThu && bFri && bSat && bSun) - { - oSchedule["filterType"] = "None"; - oSchedule["weekFilter"] = QJsonArray(); - - } - else { - oSchedule["filterType"] = "Week"; - QJsonArray tempArray; - if( bSun) - { - tempArray.append(0); - } - if(bMon) - { - tempArray.append(1); - } - if(bTur) - { - tempArray.append(2); - } - if( bWed) - { - tempArray.append(3); - } - if( bThu) - { - tempArray.append(4); - } - if( bFri) - { - tempArray.append(5); - } - if( bSat) - { - tempArray.append(6); - } - - - oSchedule["weekFilter"] = tempArray; - - } - - - oSchedules.append(oSchedule); - } - - oTaskSync["schedules"] = oSchedules; - return oTaskSync; - -} -void ControlHdmiSchedule::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} diff --git a/LedOK/wDevicesManager/controlhdmischedule.h b/LedOK/wDevicesManager/controlhdmischedule.h deleted file mode 100644 index df91ccd..0000000 --- a/LedOK/wDevicesManager/controlhdmischedule.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef CONTROLHDMISCHEDULE_H -#define CONTROLHDMISCHEDULE_H - -#include -#include -#include -#include -#include -#include -namespace Ui { -class ControlHdmiSchedule; -} - -class ControlHdmiSchedule : public QWidget -{ - Q_OBJECT - -public: - explicit ControlHdmiSchedule(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlHdmiSchedule(); -protected slots: - void refreshLable(); - void OnClickAdd(); - void OnClickImport(); - void OnClickExport(); - void OnClickDelete(); - void OnClickClear(); - void OnClickApply(); - void OnClickReadback(); -private: - Ui::ControlHdmiSchedule *ui; - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigSend(QJsonObject &,QString); - void sigHaveSchedule(bool); - protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; - QStandardItemModel * m_pModel; - bool JieXiJsonTaskSync(QJsonObject oTaskSync); - QJsonObject GetJsonObjectSyncSchedule(); - - - -}; -class ReadOnlyDelegate1: public QStyledItemDelegate -{ - Q_OBJECT -public: - ReadOnlyDelegate1(QWidget *parent = nullptr):QStyledItemDelegate(parent) - {} - - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, -const QModelIndex &index) const override //final - { - Q_UNUSED(parent) - Q_UNUSED(option) - Q_UNUSED(index) - return nullptr; - } -}; -#endif // CONTROLHDMISCHEDULE_H diff --git a/LedOK/wDevicesManager/controlhdmischedule.ui b/LedOK/wDevicesManager/controlhdmischedule.ui deleted file mode 100644 index 9134dea..0000000 --- a/LedOK/wDevicesManager/controlhdmischedule.ui +++ /dev/null @@ -1,214 +0,0 @@ - - - ControlHdmiSchedule - - - - 0 - 0 - 777 - 480 - - - - Form - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - 10 - - - 0 - - - - - - 60 - 30 - - - - Add - - - - - - - - 60 - 30 - - - - Delete - - - - - - - - 60 - 30 - - - - Clear - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Import - - - - - - - - 0 - 30 - - - - Export - - - - - - - - - By default, the asynchronous content is played, and the synchronous signal content is played in the fixed time period - - - true - - - - - - - background-color: #FFFFFF; - - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 60 - 30 - - - - Apply - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Readback - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - diff --git a/LedOK/wDevicesManager/controlhdmiwidget.cpp b/LedOK/wDevicesManager/controlhdmiwidget.cpp deleted file mode 100644 index 3c24656..0000000 --- a/LedOK/wDevicesManager/controlhdmiwidget.cpp +++ /dev/null @@ -1,172 +0,0 @@ -#include "controlhdmiwidget.h" -#include "gqt.h" -#include "tools.h" -#include "globaldefine.h" -#include "base/waitingdlg.h" -#include -#include - -ControlHdmiWidget::ControlHdmiWidget(QWidget *parent,QList *list) : QWidget(parent) { - auto vBox = new QVBoxLayout(this); - labelHdmiConfiguration = new QLabel; - labelHdmiConfiguration->setAlignment(Qt::AlignCenter); - vBox->addWidget(labelHdmiConfiguration); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - auto hBox = new QHBoxLayout(); - hBox->addStretch(); - - radioButtonManual = new QRadioButton; - hBox->addWidget(radioButtonManual); - hBox->addStretch(); - - radioButtonSchedule = new QRadioButton; - hBox->addWidget(radioButtonSchedule); - hBox->addStretch(); - - vBox->addLayout(hBox); - - m_pStackedW = new QStackedWidget; - m_pManual = new QWidget; - { - auto vBox = new VBox(m_pManual); - auto hBox = new HBox(vBox); - hBox->addStretch(); - - lbAsync = new QLabel; - hBox->addWidget(lbAsync); - - swich = new SwitchControl; - swich->setMinimumSize(QSize(66, 33)); - swich->setBgColor(QColor(200,200,200), QColor(200,200,200)); - swich->setSliderColor(QColor(0, 160, 230), QColor(0, 160, 230)); - connect(swich, &SwitchControl::checkedChanged, this, [this](bool checked) { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SyncSwitch"); - json.insert("_type", "SyncSwitch"); - json.insert("switchOn", checked); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, checked ? tr("SyncSwitch") : tr("AnSyncSwitch")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - if(checked){ - Def_CtrlSetMulti(tr("SyncSwitch")) - } else { - Def_CtrlSetMulti(tr("AnSyncSwitch")) - } - } - } - }); - hBox->addWidget(swich); - - lbSync = new QLabel; - hBox->addWidget(lbSync); - hBox->addStretch(); - - vBox->addSpacing(20); - - hBox = new HBox(vBox); - hBox->addStretch(); - btnGetSync = new QPushButton; - btnGetSync->setMinimumSize(60, 30); - btnGetSync->setProperty("ssType", "progManageTool"); - connect(btnGetSync, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "IsSync"); - json.insert("_type", "IsSync"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("IsSync")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - qDebug()<<"IsSync res"<setCheckedStatus(json["result"].toBool()); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = json["result"].toBool() ? "true" : "false"; - gFdResInfo->append(card->m_strCardId+" "+tr("IsSync")+" "+err); - }); - } - } - }); - hBox->addWidget(btnGetSync); - hBox->addStretch(); - - vBox->addStretch(); - } - m_pSchedule = new ControlHdmiSchedule(this, list); - m_pStackedW->addWidget(m_pManual); - m_pStackedW->addWidget(m_pSchedule); - vBox->addWidget(m_pStackedW); - - auto m_buttonGroup = new QButtonGroup; - m_buttonGroup->addButton(radioButtonManual, 0); - m_buttonGroup->addButton(radioButtonSchedule, 1); - connect(m_buttonGroup,SIGNAL(buttonClicked(int)),m_pStackedW,SLOT(setCurrentIndex(int))); - radioButtonManual->setChecked(true); - m_pStackedW->setCurrentIndex(0); - - connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { - if(isVisible()) init(); - }); - transUi(); -} - -void ControlHdmiWidget::showEvent(QShowEvent *event) { - QWidget::showEvent(event); - init(); -} - -void ControlHdmiWidget::init() { - bool isSingle = gSelCards->count()==1; - if(! isSingle) return; - QJsonObject json; - json.insert("_id", "IsSync"); - json.insert("_type", "IsSync"); - auto card = gSelCards->at(0); - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - swich->setCheckedStatus(json["result"].toBool()); - }); -} -void ControlHdmiWidget::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void ControlHdmiWidget::transUi() { - labelHdmiConfiguration->setText(tr("HDMI Configuration")); - radioButtonManual->setText(tr("Manual")); - radioButtonSchedule->setText(tr("Schedule")); - - lbSync->setText(tr("HDMI IN")); - lbAsync->setText(tr("Async")); - btnGetSync->setText(tr("Readback")); -} diff --git a/LedOK/wDevicesManager/controlhdmiwidget.h b/LedOK/wDevicesManager/controlhdmiwidget.h deleted file mode 100644 index f1dbaee..0000000 --- a/LedOK/wDevicesManager/controlhdmiwidget.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef CONTROLHDMIWIDGET_H -#define CONTROLHDMIWIDGET_H - -#include "base/switchcontrol.h" -#include -#include -#include - -class ControlHdmiWidget : public QWidget { - Q_OBJECT -public: - explicit ControlHdmiWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); -protected: - void showEvent(QShowEvent *event) override; - void init(); - void changeEvent(QEvent *) override; - void transUi(); - -private: - QLabel *labelHdmiConfiguration; - QRadioButton *radioButtonManual; - QRadioButton *radioButtonSchedule; - - QWidget *m_pManual=nullptr; - ControlHdmiSchedule *m_pSchedule=nullptr; - QStackedWidget *m_pStackedW; - - QLabel *lbAsync; - SwitchControl *swich; - QLabel *lbSync; - QPushButton *btnGetSync; - - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; -}; - -#endif // CONTROLHDMIWIDGET_H diff --git a/LedOK/wDevicesManager/controlnetconfigwidget.cpp b/LedOK/wDevicesManager/controlnetconfigwidget.cpp deleted file mode 100644 index 7630987..0000000 --- a/LedOK/wDevicesManager/controlnetconfigwidget.cpp +++ /dev/null @@ -1,1571 +0,0 @@ -#include "controlnetconfigwidget.h" -#include "base/waitingdlg.h" -#include "globaldefine.h" -#include "tools.h" -#include -#include -#include - -ControlNetConfigWidget::ControlNetConfigWidget(QWidget *parent,QList *list) : QWidget(parent) { - auto vBox = new QVBoxLayout(this); - - lbLanCfg = new QLabel; - QFont font = lbLanCfg->font(); - font.setPointSize(12); - lbLanCfg->setFont(font); - lbLanCfg->setAlignment(Qt::AlignCenter); - vBox->addWidget(lbLanCfg); - - auto hBox = new QHBoxLayout(); - hBox->addStretch(); - - fdDhcp = new QRadioButton; - hBox->addWidget(fdDhcp, 0, Qt::AlignTop); - - hBox->addSpacing(40); - - vBoxSpecifyIp = new QVBoxLayout(); - vBoxSpecifyIp->setContentsMargins(0, 0, 0, 0); - - fdSpecifyIp = new QRadioButton; - vBoxSpecifyIp->addWidget(fdSpecifyIp, 0, Qt::AlignCenter); - - gBoxSpecifyIp = new QGroupBox; - gBoxSpecifyIp->setMaximumWidth(340); - { - auto vvv = new QVBoxLayout(gBoxSpecifyIp); - auto hhh = new QHBoxLayout(); - - labelIpAddress = new QLabel; - hhh->addWidget(labelIpAddress); - - fdIP = new QIPLineEdit; - fdIP->setFixedWidth(160); - fdIP->setStyleSheet("background-color: #fff;"); - hhh->addWidget(fdIP); - - vvv->addLayout(hhh); - hhh = new QHBoxLayout(); - - labelMaskAddress = new QLabel; - hhh->addWidget(labelMaskAddress); - - fdMask = new QIPLineEdit; - fdMask->setFixedWidth(160); - fdMask->setStyleSheet("background-color: #FFF;"); - hhh->addWidget(fdMask); - - vvv->addLayout(hhh); - hhh = new QHBoxLayout(); - - labelGateway = new QLabel; - hhh->addWidget(labelGateway); - - fdGateWay = new QIPLineEdit; - fdGateWay->setFixedWidth(160); - fdGateWay->setStyleSheet("background-color: #fff;"); - hhh->addWidget(fdGateWay); - - vvv->addLayout(hhh); - hhh = new QHBoxLayout(); - - labelDnsAddress = new QLabel; - hhh->addWidget(labelDnsAddress); - - fdDns = new QIPLineEdit; - fdDns->setFixedWidth(160); - fdDns->setStyleSheet("background-color: #FFF;"); - hhh->addWidget(fdDns); - - vvv->addLayout(hhh); - } - vBoxSpecifyIp->addWidget(gBoxSpecifyIp); - - hBox->addLayout(vBoxSpecifyIp); - - hBox->addStretch(); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - - btnLanSet = new QPushButton; - btnLanSet->setMinimumSize(QSize(60, 30)); - connect(btnLanSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QString ip = fdIP->text(); - QString mask = fdMask->text(); - QString gateWay = fdGateWay->text(); - QString dns = fdDns->text(); - if(fdDhcp->isChecked()) { - if(ip=="...") ip="0.255.255.255"; - if(mask=="...") mask="0.255.255.255"; - if(gateWay=="...") gateWay="0.255.255.255"; - if(dns=="...") dns="0.255.255.255"; - } else { - if(ip=="...") { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input IP address!")); - fdIP->setFocus(); - return; - } - if(!isTextValid(ip)) { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Your IP Address is Invalid!")+"["+ip+"]"); - fdIP->setFocus(); - return; - } - if(mask=="...") { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input Mask address!")); - fdMask->setFocus(); - return; - } - if(!isTextValid(mask)) { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Your Mask Address is Invalid!")); - fdMask->setFocus(); - return; - } - if(gateWay=="...") { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input Gateway address!")); - fdGateWay->setFocus(); - return; - } - if(!isTextValid(gateWay)) { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Your Gateway Address is Invalid!")); - fdGateWay->setFocus(); - return; - } - if(dns=="...") { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input DNS address!")); - fdDns->setFocus(); - return; - } - if (!isTextValid(dns)) { - QMessageBox::warning(gMainWin, tr("Attention"), tr("Your DNS Address is Invalid!")); - fdDns->setFocus(); - return; - } - } - QJsonObject json; - json.insert("_id", "SetEthernet"); - json.insert("_type", "SetEthernet"); - json.insert("dhcp", fdDhcp->isChecked()); - json.insert("ip", ip); - json.insert("netMask", mask); - json.insert("gateWay", gateWay); - json.insert("dns", dns); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetEthernet")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetEthernet")) - } - } - }); - hBox->addWidget(btnLanSet); - - hBox->addSpacing(100); - - btnLanGet = new QPushButton; - btnLanGet->setMinimumSize(QSize(60, 30)); - connect(btnLanGet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetEthernet"); - json.insert("_type", "GetEthernet"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("GetEthernet")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - if(json["dhcp"].toBool()) { - fdDhcp->setChecked(true); - emit sigGetDhcpOrSpecifyIp(0); - } else { - fdSpecifyIp->setChecked(true); - emit sigGetDhcpOrSpecifyIp(1); - } - fdIP->setText(json["ipAddr"].toString()); - fdMask->setText(json["netMask"].toString()); - fdGateWay->setText(json["gateWay"].toString()); - fdDns->setText(json["dnsAddr"].toString()); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(err.isEmpty()) err = json["dhcp"].toBool() ? tr("DHCP IP") : tr("STATIC IP"); - gFdResInfo->append(card->m_strCardId+" "+tr("GetEthernet")+" "+err); - gFdResInfo->append(" IP: "+json["ipAddr"].toString()); - gFdResInfo->append(" Mask: "+json["netMask"].toString()); - gFdResInfo->append(" GateWay: "+json["gateWay"].toString()); - gFdResInfo->append(" Dns: "+json["dnsAddr"].toString()); - }); - } - } - }); - hBox->addWidget(btnLanGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - label_5 = new QLabel; - label_5->setFont(font); - label_5->setAlignment(Qt::AlignCenter); - - vBox->addWidget(label_5); - - horizontalLayout_2 = new QHBoxLayout(); - horizontalLayout_2->setContentsMargins(-1, -1, 10, -1); - verticalLayout_6 = new QVBoxLayout(); - verticalLayout_6->setContentsMargins(-1, -1, -1, 0); - groupBox_3 = new QGroupBox; - groupBox_3->setMinimumSize(QSize(0, 144)); - groupBox_3->setMaximumSize(QSize(460, 16777215)); - groupBox_3->setCheckable(true); - verticalLayout_7 = new QVBoxLayout(groupBox_3); - horizontalLayout_9 = new QHBoxLayout(); - horizontalLayout_9->setSpacing(6); - horizontalLayout_9->setContentsMargins(0, 0, -1, -1); - verticalLayout_11 = new QVBoxLayout(); - verticalLayout_11->setContentsMargins(-1, -1, 0, -1); - labelWifiName = new QLabel(groupBox_3); - labelWifiName->setMinimumSize(QSize(0, 30)); - - verticalLayout_11->addWidget(labelWifiName); - - labelWifiPassword = new QLabel(groupBox_3); - labelWifiPassword->setMinimumSize(QSize(0, 30)); - - verticalLayout_11->addWidget(labelWifiPassword); - - - horizontalLayout_9->addLayout(verticalLayout_11); - - verticalLayout_12 = new QVBoxLayout(); - verticalLayout_12->setContentsMargins(-1, -1, 0, -1); - comboBox = new QComboBox(groupBox_3); - comboBox->setMinimumSize(QSize(260, 30)); - comboBox->setMaximumSize(QSize(260, 16777215)); - comboBox->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - comboBox->setEditable(true); - - verticalLayout_12->addWidget(comboBox); - - lineEditWifiPassword = new QLineEdit(groupBox_3); - lineEditWifiPassword->setMinimumSize(QSize(140, 30)); - lineEditWifiPassword->setMaximumSize(QSize(160, 16777215)); - lineEditWifiPassword->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - lineEditWifiPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit); - - verticalLayout_12->addWidget(lineEditWifiPassword); - - - horizontalLayout_9->addLayout(verticalLayout_12); - - verticalLayout_13 = new QVBoxLayout(); - verticalLayout_13->setContentsMargins(-1, -1, 0, -1); - pushButtonScan = new QPushButton(groupBox_3); - pushButtonScan->setMinimumSize(QSize(60, 30)); - pushButtonScan->setMaximumSize(QSize(100, 16777215)); - - verticalLayout_13->addWidget(pushButtonScan); - - horizontalSpacer_10 = new QSpacerItem(40, 30, QSizePolicy::Expanding, QSizePolicy::Minimum); - - verticalLayout_13->addItem(horizontalSpacer_10); - - - horizontalLayout_9->addLayout(verticalLayout_13); - - - verticalLayout_7->addLayout(horizontalLayout_9); - - pushButtonWiFiModel = new QPushButton(groupBox_3); - pushButtonWiFiModel->setMinimumSize(QSize(60, 30)); - - verticalLayout_7->addWidget(pushButtonWiFiModel, 0, Qt::AlignHCenter); - - - verticalLayout_6->addWidget(groupBox_3); - - - horizontalLayout_2->addLayout(verticalLayout_6); - - pushButtonReadbackWiFiModel = new QPushButton; - QSizePolicy sizePolicy3(QSizePolicy::Expanding, QSizePolicy::Fixed); - sizePolicy3.setHorizontalStretch(0); - sizePolicy3.setVerticalStretch(0); - sizePolicy3.setHeightForWidth(pushButtonReadbackWiFiModel->sizePolicy().hasHeightForWidth()); - pushButtonReadbackWiFiModel->setSizePolicy(sizePolicy3); - pushButtonReadbackWiFiModel->setMinimumSize(QSize(0, 30)); - pushButtonReadbackWiFiModel->setMaximumSize(QSize(100, 16777215)); - - horizontalLayout_2->addWidget(pushButtonReadbackWiFiModel, 0, Qt::AlignBottom); - - verticalLayout_4 = new QVBoxLayout(); - verticalLayout_4->setContentsMargins(-1, 0, -1, -1); - groupBox_4 = new QGroupBox; - groupBox_4->setMinimumSize(QSize(0, 144)); - groupBox_4->setMaximumSize(QSize(300, 16777215)); - groupBox_4->setCheckable(true); - verticalLayout_8 = new QVBoxLayout(groupBox_4); - horizontalLayout_12 = new QHBoxLayout(); - horizontalLayout_12->setContentsMargins(0, -1, -1, -1); - verticalLayout_14 = new QVBoxLayout(); - verticalLayout_14->setContentsMargins(0, -1, -1, -1); - labelApName = new QLabel(groupBox_4); - - verticalLayout_14->addWidget(labelApName); - - labelApPassword = new QLabel(groupBox_4); - - verticalLayout_14->addWidget(labelApPassword); - - - horizontalLayout_12->addLayout(verticalLayout_14); - - verticalLayout_15 = new QVBoxLayout(); - verticalLayout_15->setContentsMargins(0, -1, -1, -1); - lineEditHotspotName = new QLineEdit(groupBox_4); - lineEditHotspotName->setMinimumSize(QSize(120, 30)); - lineEditHotspotName->setMaximumSize(QSize(120, 16777215)); - lineEditHotspotName->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - - verticalLayout_15->addWidget(lineEditHotspotName); - - lineEditApPassword = new QLineEdit(groupBox_4); - lineEditApPassword->setMinimumSize(QSize(120, 30)); - lineEditApPassword->setMaximumSize(QSize(120, 16777215)); - lineEditApPassword->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - lineEditApPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit); - - verticalLayout_15->addWidget(lineEditApPassword); - - - horizontalLayout_12->addLayout(verticalLayout_15); - - - verticalLayout_8->addLayout(horizontalLayout_12); - - pushButtonApSet = new QPushButton(groupBox_4); - pushButtonApSet->setMinimumSize(QSize(60, 30)); - - verticalLayout_8->addWidget(pushButtonApSet, 0, Qt::AlignHCenter); - - - verticalLayout_4->addWidget(groupBox_4); - - - horizontalLayout_2->addLayout(verticalLayout_4); - - horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_2->addItem(horizontalSpacer_2); - - - vBox->addLayout(horizontalLayout_2); - - line_3 = new QFrame; - line_3->setFrameShape(QFrame::HLine); - line_3->setFrameShadow(QFrame::Sunken); - - vBox->addWidget(line_3); - - label = new QLabel; - label->setFont(font); - - vBox->addWidget(label, 0, Qt::AlignHCenter); - - checkBox4g = new QCheckBox; - - vBox->addWidget(checkBox4g); - - horizontalLayout_13 = new QHBoxLayout(); - horizontalLayout_13->setContentsMargins(-1, 0, -1, -1); - pushButtonReadback4G = new QPushButton; - pushButtonReadback4G->setMinimumSize(QSize(60, 30)); - pushButtonReadback4G->setMaximumSize(QSize(200, 16777215)); - - horizontalLayout_13->addWidget(pushButtonReadback4G); - - label_ApnInfo = new QLabel; - label_ApnInfo->setMinimumSize(QSize(0, 0)); - - horizontalLayout_13->addWidget(label_ApnInfo); - - lineEditApnInfo = new QLineEdit; - - horizontalLayout_13->addWidget(lineEditApnInfo); - - pushButtonRead4GStatus = new QPushButton; - pushButtonRead4GStatus->setMinimumSize(QSize(0, 30)); - - horizontalLayout_13->addWidget(pushButtonRead4GStatus); - - horizontalSpacer_6 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_13->addItem(horizontalSpacer_6); - - - vBox->addLayout(horizontalLayout_13); - - verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); - - vBox->addItem(verticalSpacer_2); - - groupBox_5 = new QGroupBox; - groupBox_5->setMinimumSize(QSize(0, 80)); - groupBox_5->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); - groupBox_5->setFlat(false); - groupBox_5->setCheckable(true); - groupBox_5->setChecked(false); - verticalLayout_16 = new QVBoxLayout(groupBox_5); - label_8 = new QLabel(groupBox_5); - label_8->setWordWrap(true); - - verticalLayout_16->addWidget(label_8); - - checkBoxCustom = new QCheckBox(groupBox_5); - checkBoxCustom->setChecked(false); - - verticalLayout_16->addWidget(checkBoxCustom); - - horizontalLayout_10 = new QHBoxLayout(); - horizontalLayout_10->setContentsMargins(-1, 0, -1, -1); - pushButtonGetMcc = new QPushButton(groupBox_5); - pushButtonGetMcc->setMinimumSize(QSize(0, 30)); - - horizontalLayout_10->addWidget(pushButtonGetMcc); - - label_9 = new QLabel(groupBox_5); - - horizontalLayout_10->addWidget(label_9); - - label_2 = new QLabel(groupBox_5); - - horizontalLayout_10->addWidget(label_2); - - comboBoxCountryID = new QComboBox(groupBox_5); - comboBoxCountryID->setMinimumSize(QSize(80, 0)); - comboBoxCountryID->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF")); - comboBoxCountryID->setEditable(false); - - horizontalLayout_10->addWidget(comboBoxCountryID); - - label_11 = new QLabel(groupBox_5); - - horizontalLayout_10->addWidget(label_11); - - label_3 = new QLabel(groupBox_5); - - horizontalLayout_10->addWidget(label_3); - - comboBoxCarrierName = new QComboBox(groupBox_5); - comboBoxCarrierName->setMinimumSize(QSize(200, 0)); - comboBoxCarrierName->setContextMenuPolicy(Qt::DefaultContextMenu); - comboBoxCarrierName->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF")); - comboBoxCarrierName->setEditable(false); - comboBoxCarrierName->setDuplicatesEnabled(false); - - horizontalLayout_10->addWidget(comboBoxCarrierName); - - label_12 = new QLabel(groupBox_5); - - horizontalLayout_10->addWidget(label_12); - - label_4 = new QLabel(groupBox_5); - - horizontalLayout_10->addWidget(label_4); - - lineEditAPN = new QLineEdit(groupBox_5); - lineEditAPN->setMinimumSize(QSize(200, 0)); - lineEditAPN->setMaximumSize(QSize(200, 16777215)); - lineEditAPN->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF")); - lineEditAPN->setReadOnly(true); - - horizontalLayout_10->addWidget(lineEditAPN); - - horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_10->addItem(horizontalSpacer_3); - - - verticalLayout_16->addLayout(horizontalLayout_10); - - horizontalLayout_11 = new QHBoxLayout(); - horizontalLayout_11->setContentsMargins(-1, 10, -1, -1); - label_6 = new QLabel(groupBox_5); - - horizontalLayout_11->addWidget(label_6); - - lineEditUser = new QLineEdit(groupBox_5); - lineEditUser->setMaximumSize(QSize(120, 16777215)); - lineEditUser->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF")); - lineEditUser->setReadOnly(true); - - horizontalLayout_11->addWidget(lineEditUser); - - label_7 = new QLabel(groupBox_5); - - horizontalLayout_11->addWidget(label_7); - - lineEditPassword = new QLineEdit(groupBox_5); - lineEditPassword->setMaximumSize(QSize(120, 16777215)); - lineEditPassword->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF")); - lineEditPassword->setReadOnly(true); - - horizontalLayout_11->addWidget(lineEditPassword); - - horizontalSpacer_7 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_11->addItem(horizontalSpacer_7); - - - verticalLayout_16->addLayout(horizontalLayout_11); - - horizontalLayout_8 = new QHBoxLayout(); - horizontalLayout_8->setContentsMargins(-1, 0, -1, -1); - horizontalSpacer_5 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_8->addItem(horizontalSpacer_5); - - pushButtonSet4GInfo = new QPushButton(groupBox_5); - pushButtonSet4GInfo->setMinimumSize(QSize(60, 30)); - - horizontalLayout_8->addWidget(pushButtonSet4GInfo); - - pushButtonSetYuanHengApn = new QPushButton(groupBox_5); - pushButtonSetYuanHengApn->setMinimumSize(QSize(0, 30)); - - horizontalLayout_8->addWidget(pushButtonSetYuanHengApn); - - horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_8->addItem(horizontalSpacer_4); - - - verticalLayout_16->addLayout(horizontalLayout_8); - - - vBox->addWidget(groupBox_5); - - verticalSpacer_4 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); - - vBox->addItem(verticalSpacer_4); - - horizontalLayout_15 = new QHBoxLayout(); - horizontalLayout_15->setContentsMargins(-1, 0, 10, -1); - label_10 = new QLabel; - - horizontalLayout_15->addWidget(label_10); - - widgetFightModel = new SwitchControl; - widgetFightModel->setMinimumSize(QSize(80, 35)); - - horizontalLayout_15->addWidget(widgetFightModel); - - pushButtonReadbackFlightModel = new QPushButton; - pushButtonReadbackFlightModel->setMinimumSize(QSize(0, 30)); - - horizontalLayout_15->addWidget(pushButtonReadbackFlightModel); - - horizontalSpacer_8 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); - - horizontalLayout_15->addItem(horizontalSpacer_8); - - - vBox->addLayout(horizontalLayout_15); - - verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); - - vBox->addItem(verticalSpacer); - - - fdDhcp->setText(QCoreApplication::translate("ControlNetConfigWidget", "DHCP", nullptr)); - fdSpecifyIp->setText(QCoreApplication::translate("ControlNetConfigWidget", "Specify IP", nullptr)); - labelIpAddress->setText(QCoreApplication::translate("ControlNetConfigWidget", "IP Address", nullptr)); - labelMaskAddress->setText(QCoreApplication::translate("ControlNetConfigWidget", "Mask Address", nullptr)); - labelGateway->setText(QCoreApplication::translate("ControlNetConfigWidget", "Gateway", nullptr)); - labelDnsAddress->setText(QCoreApplication::translate("ControlNetConfigWidget", "DNS Address", nullptr)); - label_5->setText(QCoreApplication::translate("ControlNetConfigWidget", "WIFI Configuration", nullptr)); - groupBox_3->setTitle(QCoreApplication::translate("ControlNetConfigWidget", "WiFi On/Off", nullptr)); - labelWifiName->setText(QCoreApplication::translate("ControlNetConfigWidget", "WiFi name", nullptr)); - labelWifiPassword->setText(QCoreApplication::translate("ControlNetConfigWidget", "Password", nullptr)); - lineEditWifiPassword->setPlaceholderText(QCoreApplication::translate("ControlNetConfigWidget", "Input password", nullptr)); - pushButtonScan->setText(QCoreApplication::translate("ControlNetConfigWidget", "Scan", nullptr)); - pushButtonWiFiModel->setText(QCoreApplication::translate("ControlNetConfigWidget", "Set", nullptr)); - pushButtonReadbackWiFiModel->setText(QCoreApplication::translate("ControlNetConfigWidget", "Readback", nullptr)); - groupBox_4->setTitle(QCoreApplication::translate("ControlNetConfigWidget", "Ap Mode", nullptr)); - labelApName->setText(QCoreApplication::translate("ControlNetConfigWidget", "Ap name", nullptr)); - labelApPassword->setText(QCoreApplication::translate("ControlNetConfigWidget", "Password", nullptr)); - lineEditHotspotName->setPlaceholderText(QCoreApplication::translate("ControlNetConfigWidget", "Input Ap name", nullptr)); - lineEditApPassword->setPlaceholderText(QCoreApplication::translate("ControlNetConfigWidget", "Input password", nullptr)); - pushButtonApSet->setText(QCoreApplication::translate("ControlNetConfigWidget", "Set", nullptr)); - label->setText(QCoreApplication::translate("ControlNetConfigWidget", "4G/5G Configuration", nullptr)); - checkBox4g->setText(QCoreApplication::translate("ControlNetConfigWidget", "Open 4G/5G", nullptr)); - pushButtonReadback4G->setText(QCoreApplication::translate("ControlNetConfigWidget", "Readback APN Info", nullptr)); - label_ApnInfo->setText(QCoreApplication::translate("ControlNetConfigWidget", " APN:", nullptr)); - pushButtonRead4GStatus->setText(QCoreApplication::translate("ControlNetConfigWidget", "Get cellular network status information", nullptr)); - groupBox_5->setTitle(QCoreApplication::translate("ControlNetConfigWidget", "Set Apn Info,Check SIM can automatically match to MCC, and then select carrier get apn param", nullptr)); - label_8->setText(QCoreApplication::translate("ControlNetConfigWidget", "Check SIM can automatically match to MCC, and then select carrier get apn param,if not found carrier,you can check the CUSTOM checkbox,then enter custom param.", nullptr)); - checkBoxCustom->setText(QCoreApplication::translate("ControlNetConfigWidget", "CUSTOM", nullptr)); - pushButtonGetMcc->setText(QCoreApplication::translate("ControlNetConfigWidget", "Check SIM", nullptr)); - label_9->setText(QCoreApplication::translate("ControlNetConfigWidget", "->", nullptr)); - label_2->setText(QCoreApplication::translate("ControlNetConfigWidget", "Country ID(mcc):", nullptr)); - label_11->setText(QCoreApplication::translate("ControlNetConfigWidget", "->", nullptr)); - label_3->setText(QCoreApplication::translate("ControlNetConfigWidget", "Carrier Name", nullptr)); - label_12->setText(QCoreApplication::translate("ControlNetConfigWidget", "->", nullptr)); - label_4->setText(QCoreApplication::translate("ControlNetConfigWidget", "APN:", nullptr)); - lineEditAPN->setPlaceholderText(QCoreApplication::translate("ControlNetConfigWidget", "APN(Required)", nullptr)); - label_6->setText(QCoreApplication::translate("ControlNetConfigWidget", "User:", nullptr)); - lineEditUser->setPlaceholderText(QCoreApplication::translate("ControlNetConfigWidget", "Not required", nullptr)); - label_7->setText(QCoreApplication::translate("ControlNetConfigWidget", "Password:", nullptr)); - lineEditPassword->setPlaceholderText(QCoreApplication::translate("ControlNetConfigWidget", "Not required", nullptr)); - pushButtonSet4GInfo->setText(QCoreApplication::translate("ControlNetConfigWidget", "Set", nullptr)); - pushButtonSetYuanHengApn->setText(QCoreApplication::translate("ControlNetConfigWidget", "Set Apn:iot.cargo", nullptr)); - label_10->setText(QCoreApplication::translate("ControlNetConfigWidget", "Flight Mode", nullptr)); - pushButtonReadbackFlightModel->setText(QCoreApplication::translate("ControlNetConfigWidget", "Readback", nullptr)); - - - btnLanGet->setProperty("ssType", "progManageTool"); - pushButtonReadbackWiFiModel->setProperty("ssType", "progManageTool"); - btnLanSet->setProperty("ssType", "progManageTool"); - pushButtonApSet->setProperty("ssType", "progManageTool"); - pushButtonWiFiModel->setProperty("ssType", "progManageTool"); - pushButtonScan->setProperty("ssType", "progManageTool"); - pushButtonReadback4G->setProperty("ssType", "progManageTool"); - pushButtonSet4GInfo->setProperty("ssType", "progManageTool"); - pushButtonGetMcc->setProperty("ssType", "progManageTool"); - pushButtonSetYuanHengApn->setProperty("ssType", "progManageTool"); - pushButtonReadbackFlightModel->setProperty("ssType", "progManageTool"); - pushButtonRead4GStatus->setProperty("ssType", "progManageTool"); - widgetFightModel->setSliderColor(QColor(0, 0, 0),QColor(0, 160, 230)); - widgetFightModel->setBgColor(QColor(200,200,200),QColor(0,200,0)); - widgetFightModel->setTextColor(QColor(100,100,100),QColor(0, 160, 230)); - widgetFightModel->setText(tr("OFF"),tr("ON")); - - m_buttonGroup = new QButtonGroup; - m_buttonGroup->addButton(fdDhcp,0); - m_buttonGroup->addButton(fdSpecifyIp,1); - - checkBox4g->setStyleSheet("QCheckBox::indicator {width: 16px; height: 16px;}"); - checkBoxCustom->setStyleSheet("QCheckBox::indicator {width: 16px; height: 16px;}"); - comboBoxCountryID->setStyleSheet("background:rgba(216,216,216,1);"); - comboBoxCarrierName->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditAPN->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditUser->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditPassword->setStyleSheet("background:rgba(216,216,216,1);"); - checkBox4g->setChecked(true); - fdDhcp->setChecked(true); - - connect(this,SIGNAL(sigGetDhcpOrSpecifyIp(int)),this,SLOT(OnDhcpOrSpecifyIp(int))); - connect(m_buttonGroup,SIGNAL(buttonClicked(int)),this,SLOT(OnDhcpOrSpecifyIp(int))); - - connect(pushButtonWiFiModel, SIGNAL(clicked()), this, SLOT(onSetWiFiModel())); - connect(pushButtonReadbackWiFiModel, SIGNAL(clicked()), this, SLOT(onReadbackWiFiModel())); - connect(pushButtonApSet, SIGNAL(clicked()), this, SLOT(onSetAp())); - connect(pushButtonScan,SIGNAL(clicked()),this,SLOT(OnScanWifi())); - - connect(pushButtonSet4GInfo, SIGNAL(clicked()), this, SLOT(onSet4GInfo())); - connect(pushButtonReadback4G, SIGNAL(clicked()), this, SLOT(onReadback4G())); - connect(pushButtonGetMcc, SIGNAL(clicked()), this, SLOT(onGetMcc())); - connect(pushButtonRead4GStatus, SIGNAL(clicked()), this, SLOT(onGet4GStatus())); - - connect(comboBoxCountryID, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboMccChanged(int))); - connect(comboBoxCarrierName, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboCarrierChanged(int))); - connect(checkBoxCustom, SIGNAL(clicked(bool)), this, SLOT(OnCustom4G(bool))); - connect(checkBox4g, SIGNAL(clicked(bool)), this, SLOT(OnOpne4G(bool))); - connect(widgetFightModel, SIGNAL(checkedChanged(bool)), this, SLOT(onFightModelChecked(bool))); - connect(pushButtonReadbackFlightModel, SIGNAL(clicked()), this, SLOT(onReadbackFlightModel())); - - MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent) - emit sigGetDhcpOrSpecifyIp(0); - - pushButtonSetYuanHengApn->setVisible(false); - checkBoxCustom->setVisible(false); - OnCustom4G(true); - - transUi(); -} - -ControlNetConfigWidget::~ControlNetConfigWidget() -{ - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void ControlNetConfigWidget::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void ControlNetConfigWidget::transUi() { - lbLanCfg->setText(tr("Wire Enther(RJ45) Configuration")); - fdDhcp->setText(tr("DHCP")); - fdSpecifyIp->setText(tr("Specify IP")); - labelApName->setText(tr("AP name")); - labelGateway->setText(tr("Gateway")); - labelWifiName->setText(tr("WiFi name")); - labelIpAddress->setText(tr("IP Address")); - labelApPassword->setText(tr("Password")); - labelDnsAddress->setText(tr("DNS Address")); - labelMaskAddress->setText(tr("Subnet mask")); - labelWifiPassword->setText(tr("Password")); - pushButtonScan->setText(tr("Scan")); - pushButtonApSet->setText(tr("Set")); - pushButtonWiFiModel->setText(tr("Set")); - btnLanSet->setText(tr("Set")); - pushButtonReadbackWiFiModel->setText(tr("Readback")); - btnLanGet->setText(tr("Readback")); - groupBox_3->setTitle(tr("WiFi On/Off")); - groupBox_4->setTitle(tr("Ap Mode")); - label_5->setText(tr("WIFI Configuration")); - lineEditApPassword->setPlaceholderText(tr("Input password")); - lineEditWifiPassword->setPlaceholderText(tr("Input password")); - lineEditHotspotName->setPlaceholderText(tr("Input ap name")); - label->setText(tr("4G/5G Configuration")); - label_8->setText(tr("Check SIM can automatically match to MCC, and then select carrier get apn param,if not found carrier,you can check the CUSTOM checkbox,then enter custom param.")); - checkBox4g->setText(tr("Open 4G/5G")); - - - groupBox_5->setTitle(tr("Set Apn Info,Check SIM can automatically match to MCC, and then select carrier get apn param")); - checkBoxCustom->setText(tr("CUSTOM")); - pushButtonGetMcc->setText(tr("Check SIM")); - label_2->setText(tr("Country ID(mcc):")); - label_3->setText(tr("Carrier Name")); - label_4->setText(tr("APN:")); - label_6->setText(tr("User:")); - label_7->setText(tr("Password:")); - pushButtonSet4GInfo->setText(tr("Set")); - lineEditAPN->setPlaceholderText(tr("APN(Required)")); - lineEditUser->setPlaceholderText(tr("Not required")); - lineEditPassword->setPlaceholderText(tr("Not required")); - pushButtonReadback4G->setText(tr("Readback APN Info")); - pushButtonReadbackFlightModel->setText(tr("Readback")); - pushButtonRead4GStatus->setText(tr("Get cellular network status information")); - label_10->setText(tr("Flight Mode")); -} - -void ControlNetConfigWidget::OnDhcpOrSpecifyIp(int iIndex) -{ - if(iIndex==0) - { - gBoxSpecifyIp->setEnabled(false); - fdDns->setStyleSheet("QLineEdit{background:rgba(216,216,216,1);}"); - fdIP->setStyleSheet("QLineEdit{background:rgba(216,216,216,1);}"); - fdMask->setStyleSheet("QLineEdit{background:rgba(216,216,216,1);}"); - fdGateWay->setStyleSheet("QLineEdit{background:rgba(216,216,216,1);}"); - fdDns->MySetColor(QColor::fromRgb(216,216,216)); - fdIP->MySetColor(QColor::fromRgb(216,216,216)); - fdMask->MySetColor(QColor::fromRgb(216,216,216)); - fdGateWay->MySetColor(QColor::fromRgb(216,216,216)); - } - else { - gBoxSpecifyIp->setEnabled(true); - fdDns->setStyleSheet("QLineEdit{background:rgba(255,255,255,1);}"); - fdIP->setStyleSheet("QLineEdit{background:rgba(255,255,255,1);}" ); - fdMask->setStyleSheet("QLineEdit{background:rgba(255,255,255,1);}" ); - fdGateWay->setStyleSheet("QLineEdit{background:rgba(255,255,255,1);}"); - fdDns->MySetColor(QColor::fromRgb(255,255,255)); - fdIP->MySetColor(QColor::fromRgb(255,255,255)); - fdMask->MySetColor(QColor::fromRgb(255,255,255)); - fdGateWay->MySetColor(QColor::fromRgb(255,255,255)); - } - -} -void ControlNetConfigWidget::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()==1) - { - if(groupBox_3->isChecked()) - pushButtonScan->setEnabled(true); - } - else { - if(groupBox_3->isChecked()) - pushButtonScan->setEnabled(false); - } - //MACRO_DEFINE_CONTROL_FUNC3 - if(m_pLedlist->count()==1) - { - m_pLedCard=list->at(0); - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings"; - if(m_oldLedlist!=m_pLedCard&&m_bSelected==true) - { - m_oldLedlist=m_pLedCard; - onReadbackAllThisPage(); - } - } -} -void ControlNetConfigWidget::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - - QJsonObject json; - json.insert("_id", "GetEthernet"); - json.insert("_type", "GetEthernet"); - if(gSelCards->count() == 1) { - auto card = gSelCards->at(0); - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [this, reply] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - if(json["dhcp"].toBool()) { - fdDhcp->setChecked(true); - emit sigGetDhcpOrSpecifyIp(0); - } else { - fdSpecifyIp->setChecked(true); - emit sigGetDhcpOrSpecifyIp(1); - } - fdIP->setText(json["ipAddr"].toString()); - fdGateWay->setText(json["gateWay"].toString()); - fdMask->setText(json["netMask"].toString()); - fdDns->setText(json["dnsAddr"].toString()); - }); - } - - QJsonObject json1; - json1.insert("_id", getRandomString(10)); - json1.insert("_type", "GetWifiList"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json1); - comboBox->clear(); - QJsonObject json55; - json55.insert("_id", getRandomString(10)); - json55.insert("_type", "GetSwitchSimData"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json55); - QJsonObject json2; - json2.insert("_id", getRandomString(10)); - json2.insert("_type", "IsPortableHotSpot"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json2); - QJsonObject json66; - json66.insert("_id", getRandomString(10)); - json66.insert("_type", "GetSwitchWiFi"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json66); - QJsonObject json3; - json3.insert("_id", getRandomString(10)); - json3.insert("_type", "GetAPNList"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json3); - - QJsonObject json4; - json4.insert("_id", getRandomString(10)); - json4.insert("_type", "GetCurrentAPN"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json4); - - QJsonObject json5; - json5.insert("_id", getRandomString(10)); - json5.insert("_type", "GetTimezone"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json5); - - QJsonObject json6; - json6.insert("_id", getRandomString(10)); - json6.insert("_type", "GetFlightModeState"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json6); - MACRO_DEFINE_TIPDLG_ALL_FUCN(tr("Readback"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget::onSetWiFiModel() -{ - CHECK_CARD_SELECTED - - if(groupBox_3->isChecked()) - { - comboBox->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditWifiPassword->setStyleSheet("background:rgba(216,216,216,1);"); - - } - else { - comboBox->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditWifiPassword->setStyleSheet("background:rgba(216,216,216,1);"); - - } - - if(m_pLedlist->count()==1) - { - if(groupBox_3->isChecked()) - { - comboBox->setStyleSheet("background:rgba(255,255,255,1);"); - lineEditWifiPassword->setStyleSheet("background:rgba(255,255,255,1);"); - QJsonObject json1; - json1.insert("_id", getRandomString(10)); - json1.insert("_type", "SetSwitchWiFi"); - json1.insert("enable", true); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json1); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "ConfigurationWiFi"); - QString strSsid=comboBox->currentText(); - if(strSsid.contains(tr("SignalPower"))) - { - int itempOffset=strSsid.indexOf(tr("SignalPower")); - strSsid=strSsid.left(itempOffset-4); - } - qDebug()<<"strSsid="<text()); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - MACRO_DEFINE_TIPDLG_FUCN(tr("ConfigurationWiFi"),tr("Success"),tr("failed")) - } - - } - else { - if(groupBox_3->isChecked()) - { - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "ConfigurationWiFi"); - QString strSsid=comboBox->currentText(); - if(strSsid.contains(tr("SignalPower"))) - { - int itempOffset=strSsid.indexOf(tr("SignalPower")); - strSsid=strSsid.left(itempOffset-4); - } - qDebug()<<"strSsid="<text()); - emit sigSend(json,tr("ConfigurationWiFi")); - } - } -} - -void ControlNetConfigWidget:: onReadbackWiFiModel() -{ - - CHECK_CARD_SELECTED - QJsonObject json66; - json66.insert("_id", getRandomString(10)); - json66.insert("_type", "GetSwitchWiFi"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json66); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "IsPortableHotSpot"); - - MACRO_DEFINE_TIPDLG_FUCN(tr("IsPortableHotSpot"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget:: OnScanWifi() -{ - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetWifiList"); - comboBox->clear(); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetWifiList"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget:: onSetAp() -{ - CHECK_CARD_SELECTED - if(groupBox_4->isChecked()) - { - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "ConfigurationHotSpot"); - json.insert("apName", lineEditHotspotName->text()); - json.insert("password", lineEditApPassword->text()); - MACRO_DEFINE_TIPDLG_FUCN(tr("ConfigurationHotSpot"),tr("Success"),tr("failed")) - } -} - -void ControlNetConfigWidget::onReadback4G() -{ - CHECK_CARD_SELECTED - lineEditApnInfo->setText(""); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetCurrentAPN"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetCurrentAPN"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget::onGetMcc() -{ - m_buttonFlagClick=1; - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetSIMStatus"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetSIMStatus"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget::onGet4GStatus() -{ - m_buttonFlagClick=0; - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetSIMStatus"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetSIMStatus"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget::onSet4GInfo() -{ - CHECK_CARD_SELECTED - - QJsonObject json; - if(checkBoxCustom->isChecked()) - { - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetAPN"); - json.insert("carrier", comboBoxCarrierName->currentText()); - json.insert("apn",lineEditAPN->text()); - json.insert("user", lineEditUser->text()); - json.insert("password", lineEditPassword->text()); - json.insert("type",""); - json.insert("server", ""); - json.insert("proxy", ""); - json.insert("port",""); - json.insert("mmsc",""); - json.insert("mmsproxy",""); - json.insert("mmsport",""); - } - else { - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetAPN"); - json.insert("carrier", m_4gObj["carrier"].toString()); - json.insert("apn",lineEditAPN->text()); - json.insert("user", lineEditUser->text()); - json.insert("password", lineEditPassword->text()); - json.insert("type", m_4gObj["type"].toString()); - json.insert("server", m_4gObj["server"].toString()); - json.insert("proxy", m_4gObj["proxy"].toString()); - json.insert("port", m_4gObj["port"].toString()); - json.insert("mmsc", m_4gObj["mmsc"].toString()); - json.insert("mmsproxy", m_4gObj["mmsproxy"].toString()); - json.insert("mmsport", m_4gObj["mmsport"].toString()); - } - MACRO_DEFINE_TIPDLG_FUCN(tr("SetAPN"),tr("Success"),tr("failed")) -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlNetConfigWidget::OnProHttpResponse(QString url, QString postMD5, QByteArray data) { - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<setChecked(jsonObject["enable"].toBool()); - } - else if(strType == "GetWifiList") - { - //QVariant iTemp=jsonObject["wifiList"].toVariant(); - QJsonValue value = jsonObject.take("wifiList"); - QJsonArray array= value.toArray(); - int iSize=array.size(); - QList wifInfoiList; - for(int i=0;i infoB.signal;}); - for(int j=0;jaddItem(wifInfoiList.at(j).ssid+"...["+tr("SignalPower")+":"+strSignalPower+"]"); - - } - } - else if(strType == "IsPortableHotSpot") - { - QString iTemp=jsonObject["wifi"].toString(); -// if(iTemp.isEmpty()) -// groupBox_3->setChecked(false); -// else -// { -// groupBox_3->setChecked(true); -// } - QString strKong=""; - comboBox->setCurrentText(iTemp+strKong); - QString iTempHotSpot=jsonObject["hotSpots"].toString(); - if(iTempHotSpot.isEmpty()) - groupBox_4->setChecked(false); - else - groupBox_4->setChecked(true); - lineEditHotspotName->setText(iTempHotSpot); - } - else if(strType == "SetAPN") - { - onReadback4G(); - } - else if(strType == "GetSIMStatus") { - QString str4GStatus=""; - if(m_buttonFlagClick==0) { - str4GStatus = tr("状态:"); - switch(jsonObject["state"].toInt()) { - case 0: - case 1: - str4GStatus+=tr("未知"); - break; - case 2: - str4GStatus+=tr("锁定状态,需要用户的PIN码解锁"); - break; - case 3: - str4GStatus+=tr("锁定状态,需要用户的PUK码解锁"); - break; - case 4: - str4GStatus+=tr("锁定状态,需要网络的PIN码解锁"); - break; - case 5: - str4GStatus+=tr("就绪"); - break; - } - } - QString strImsi=jsonObject["imsi"].toString(); - if(strImsi.isEmpty()) { - str4GStatus+="\r\n"+tr("no checked sim card"); - QMessageBox::information(gMainWin, tr("Tip"),str4GStatus); - } else { - str4GStatus+="\r\nAPN: "+apn+"\r\nIMSI: "+strImsi+"\r\n"; - mcc = strImsi.left(3); - //comboBoxCountryID->setCurrentText(m_mcc); - comboBoxCountryID->setCurrentText(""); - comboBoxCarrierName->setCurrentText(""); - lineEditAPN->setText(""); - lineEditUser->setText(""); - lineEditPassword->setText(""); - - //SetMcc(m_mcc); - str4GStatus+=tr("国家码:"); - str4GStatus+=jsonObject["countryCode"].toString()+"("+mcc+")\r\n"; - str4GStatus+=tr("号码:"); - str4GStatus+=jsonObject["phoneNumber"].toString()+"\r\n"; - if(m_buttonFlagClick==0) - { - str4GStatus+=tr("用户:"); - str4GStatus+=jsonObject["user"].toString()+"\r\n"; - str4GStatus+=tr("信号:"); - switch(jsonObject["serviceState"].toInt()) - { - case 0: str4GStatus+=tr("信号正常")+"\r\n"; break; - case 1: str4GStatus+=tr("不在服务区")+"\r\n"; break; - case 2: str4GStatus+=tr("仅限紧急呼叫")+"\r\n"; break; - case 3: str4GStatus+=tr("射频已经关闭")+"\r\n"; break; - } - str4GStatus+=tr("网络:"); - switch(jsonObject["networkType"].toInt()) - { - case 0: str4GStatus+=tr("网络类型未知")+"\r\n"; break; - case 1: str4GStatus+=tr("GPRS网络")+"\r\n"; break; - case 2: str4GStatus+=tr("EDGE网络")+"\r\n"; break; - case 3: str4GStatus+=tr("UMTS网络")+"\r\n"; break; - case 4: str4GStatus+=tr("CDMA网络,IS95A 或 IS95B.")+"\r\n"; break; - case 5: str4GStatus+=tr("EVDO网络, revision 0.")+"\r\n"; break; - case 6: str4GStatus+=tr("EVDO网络, revision A.")+"\r\n"; break; - case 7: str4GStatus+=tr("1xRTT网络")+"\r\n"; break; - case 8: str4GStatus+=tr("HSDPA网络")+"\r\n"; break; - case 9: str4GStatus+=tr("HSUPA网络")+"\r\n"; break; - case 10: str4GStatus+=tr("HSPA网络")+"\r\n"; break; - } - str4GStatus+=tr("漫游:"); - - // 是否为漫游 - if(jsonObject["roaming"].toBool()) - { - str4GStatus+=tr("Yes")+"\r\n"; - } - else - { - str4GStatus+=tr("No")+"\r\n"; - } - str4GStatus+=tr("数据连接状态:"); - switch(jsonObject["dataState"].toInt()) - { - case 0: str4GStatus+=tr("断开")+"\r\n"; break; - case 1: str4GStatus+=tr("正在连接")+"\r\n"; break; - case 2: str4GStatus+=tr("已连接")+"\r\n"; break; - case 3: str4GStatus+=tr("暂停")+"\r\n"; break; - } - str4GStatus+=tr("数据活动休眠状态:"); - switch(jsonObject["dataActivity"].toInt()) - { - case 0: str4GStatus+=tr("活动,但无数据发送和接收")+"\r\n"; break; - case 1: str4GStatus+=tr("活动,正在接收数据")+"\r\n"; break; - case 2: str4GStatus+=tr("活动,正在发送数据")+"\r\n"; break; - case 3: str4GStatus+=tr("活动,正在接收和发送数据")+"\r\n"; break; - case 4: str4GStatus+=tr("休眠状态")+"\r\n"; break; - } - str4GStatus+=tr("信号强度:"); - QString strSignalStrength=QString::number(jsonObject["signalStrength"].toInt()); - str4GStatus+=strSignalStrength+"\r\n"; - } - QMessageBox::information(gMainWin, tr("Tip"),str4GStatus); - } - } - else if(strType == "GetCurrentAPN"){ -// lineEditAPN->setText(jsonObject["apn"].toString()); -// lineEditUser->setText(jsonObject["user"].toString()); -// lineEditPassword->setText(jsonObject["password"].toString()); - apn = jsonObject["apn"].toString(); - if(jsonObject["user"].toString().isEmpty()) lineEditApnInfo->setText(apn); - else lineEditApnInfo->setText(apn+",USER:"+jsonObject["user"].toString()+",PASSWORD:"+jsonObject["password"].toString()); - } - else if(strType == "SetSwitchSimData"){ - } - else if(strType=="ContrFlightMode"){ - } - else if(strType=="GetFlightModeState"){ - //widgetFightModel->setChecked(jsonObject["result"].toBool()); - widgetFightModel->setCheckedStatus(jsonObject["result"].toBool()); - widgetFightModel->update(); - } - else if(strType == "GetTimezone"){ - QString strtemp=jsonObject["timezone"].toString(); - // strtemp=strtemp.right(strtemp.length()-strtemp.indexOf("/")-1); - //comboBox_Timezone->setCurrentText(strtemp); - } - else if(strType == "SetTimezone"){ - - } - - - if(strType!="SetSwitchWiFi") - { - if(iEnableFlag==true) - { - iEnableFlag=false; - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - - } - - } - } -} - -void ControlNetConfigWidget::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<setChecked(jsonObject["enable"].toBool()); - else if(strType == "GetWifiList") { - QJsonValue value = jsonObject.take("wifiList"); - QJsonArray array= value.toArray(); - int iSize=array.size(); - QList wifInfoiList; - for(int i=0;iaddItem(wifInfoiList.at(j).ssid+"...["+tr("SignalPower")+":"+strSignalPower+"]"); - } - - } - else if(strType == "IsPortableHotSpot") - { - QString iTemp=jsonObject["wifi"].toString(); - QString strKong=""; - comboBox->setCurrentText(iTemp+strKong); - QString iTempHotSpot=jsonObject["hotSpots"].toString(); - if(iTempHotSpot.isEmpty()) - groupBox_4->setChecked(false); - else - groupBox_4->setChecked(true); - lineEditHotspotName->setText(iTempHotSpot); - if(iEnableFlag==true) - { - iEnableFlag=false; - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - } - else if(strType == "GetAPNList") - { - qDebug()<<"GetAPNList"; - if(m_ApnInfoiList.count()<=0) - { -// if(m_ApnInfoiList.count()>0) -// m_ApnInfoiList.clear(); -// if(comboBoxCountryID->count()>0) -// comboBoxCountryID->clear(); -// if(comboBoxCarrierName->count()>0) -// comboBoxCarrierName->clear(); - foreach(QJsonValue value, jsonObject["apns"].toArray()) { - QJsonObject oApn = value.toObject(); - QString strtempmcc=oApn["mcc"].toString(); - bool itempHave=false; - for (int i=0;icount();i++) { - if(strtempmcc==comboBoxCountryID->itemText(i)) - { - itempHave=true; - break; - } - - } - qDebug()<addItem(strtempmcc); - m_ApnInfoiList.append(oApn); - } - } - comboBoxCountryID->setCurrentText(""); - - - } - else if(strType=="GetFlightModeState") - { - //widgetFightModel->setChecked(jsonObject["result"].toBool()); - widgetFightModel->setCheckedStatus(jsonObject["result"].toBool()); - widgetFightModel->update(); - } - else if(strType == "GetCurrentAPN") { - apn = jsonObject["apn"].toString(); -// lineEditAPN->setText(strApn); -// lineEditUser->setText(jsonObject["user"].toString()); -// lineEditPassword->setText(jsonObject["password"].toString()); - if(jsonObject["user"].toString().isEmpty()) lineEditApnInfo->setText(apn); - else lineEditApnInfo->setText(apn+",USER:"+jsonObject["user"].toString()+",PASSWORD:"+jsonObject["password"].toString()); - } - else if(strType == "GetTimezone"){ - QString strtemp=jsonObject["timezone"].toString(); - //comboBox_Timezone->setCurrentText(strtemp); - } - else if(strType == "SetTimezone"){ - - } - else if(strType == "GetSwitchSimData"){ - bool b=jsonObject["enable"].toBool(); - checkBox4g->setChecked(b); - pushButtonSet4GInfo->setVisible(b); - pushButtonReadback4G->setVisible(b); - pushButtonGetMcc->setVisible(b); -#ifndef MACRO_YUANHENG_VERSION - comboBoxCountryID->setVisible(b); - comboBoxCarrierName->setVisible(b); - //checkBoxCustom->setVisible(b); - lineEditAPN->setVisible(b); - lineEditUser->setVisible(b); - lineEditPassword->setVisible(b); - label_2->setVisible(b); - label_3->setVisible(b); - label_4->setVisible(b); - label_6->setVisible(b); - label_7->setVisible(b); - label_8->setVisible(b); -#else - lineEditAPN->setVisible(b); - -#endif - } - } - } -} -void ControlNetConfigWidget::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_NetCfg) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlNetConfigWidget::OnComboMccChanged(int index) -{ - Q_UNUSED(index); - SetMcc(comboBoxCountryID->currentText()); -} - -void ControlNetConfigWidget::SetMcc(QString strMcc) -{ - qDebug()<<"SetMcc:"<clear(); - foreach(QJsonObject obj, m_ApnInfoiList) - { - if(obj["mcc"].toString()==strMcc) - { - m_MccCarrierInfoiList.append(obj); - comboBoxCarrierName->addItem(obj["carrier"].toString()); - // comboBoxCarrierName->insertItem(0,obj["carrier"].toString()); - } - } - comboBoxCarrierName->clearEditText(); -// if(comboBoxCarrierName->isEditable()==false) -// { -// comboBoxCarrierName->setEditable(true); -// comboBoxCarrierName->setCurrentText(""); -// comboBoxCarrierName->setEditable(false); -// } - - -} -void ControlNetConfigWidget::OnComboCarrierChanged(int index) -{ - if(m_MccCarrierInfoiList.count()>0 && indexsetText(m_4gObj["apn"].toString()); - lineEditUser->setText(m_4gObj["user"].toString()); - lineEditPassword->setText(m_4gObj["password"].toString()); - } -} -void ControlNetConfigWidget::OnCustom4G(bool b) -{ - //pushButtonGetMcc->setEnabled(b); - comboBoxCountryID->setEditable(b); - comboBoxCarrierName->setEditable(b); - - lineEditUser->setReadOnly(!b); - lineEditPassword->setReadOnly(!b); - if(b) - { - comboBoxCountryID->setStyleSheet("background:rgba(255,255,255,1);"); - comboBoxCarrierName->setStyleSheet("background:rgba(255,255,255,1);"); - lineEditAPN->setStyleSheet("background:rgba(255,255,255,1);"); - lineEditUser->setStyleSheet("background:rgba(255,255,255,1);"); - lineEditPassword->setStyleSheet("background:rgba(255,255,255,1);"); - - } - else { - comboBoxCountryID->setStyleSheet("background:rgba(216,216,216,1);"); - comboBoxCarrierName->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditAPN->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditUser->setStyleSheet("background:rgba(216,216,216,1);"); - lineEditPassword->setStyleSheet("background:rgba(216,216,216,1);"); - - } -#ifndef MACRO_YUANHENG_VERSION - lineEditAPN->setReadOnly(false); -#else - lineEditAPN->setReadOnly(!b); - lineEditAPN->setStyleSheet("background:rgba(255,255,255,1);"); - -#endif -} -void ControlNetConfigWidget::OnOpne4G(bool b) -{ - CHECK_CARD_SELECTED - pushButtonSet4GInfo->setVisible(b); - pushButtonReadback4G->setVisible(b); - pushButtonGetMcc->setVisible(b); - groupBox_5->setVisible(b); - comboBoxCountryID->setVisible(b); - comboBoxCarrierName->setVisible(b); - lineEditAPN->setVisible(b); - lineEditUser->setVisible(b); - lineEditPassword->setVisible(b); - label_2->setVisible(b); - label_3->setVisible(b); - label_4->setVisible(b); - label_6->setVisible(b); - label_7->setVisible(b); - label_8->setVisible(b); - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetSwitchSimData"); - json.insert("enable", b); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetSwitchSimData"),tr("Success"),tr("failed")) -} - -void ControlNetConfigWidget::DeletePostingDlg() -{ - qDebug()<<"ControlNetConfigWidget::DeletePostingDlg"; - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - iEnableFlag=true; - } -} -void ControlNetConfigWidget::onFightModelChecked(bool b) -{ - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "ContrFlightMode"); - json.insert("state", b); - MACRO_DEFINE_TIPDLG_FUCN(tr("ContrFlightMode"),tr("Success"),tr("failed")) -} -void ControlNetConfigWidget::onReadbackFlightModel() -{ - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetFlightModeState"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetFlightModeState"),tr("Success"),tr("failed")) -} diff --git a/LedOK/wDevicesManager/controlnetconfigwidget.h b/LedOK/wDevicesManager/controlnetconfigwidget.h deleted file mode 100644 index 201af2d..0000000 --- a/LedOK/wDevicesManager/controlnetconfigwidget.h +++ /dev/null @@ -1,182 +0,0 @@ -#ifndef CONTROLNETCONFIGWIDGET_H -#define CONTROLNETCONFIGWIDGET_H - -#include -#include -#include -#include "base/qiplineedit.h" -#include "base/switchcontrol.h" -#include -#include -#include -#include -#include - -typedef struct wifiInfo{ - QString ssid; - int signal; - QString encryptionMethod; - -}ST_WIFiINFO; -typedef struct ApnInfo{ - QString apn; - QString carrier; - QString mcc; - QString mmsc; - QString mmsport; - QString mmsproxy; - QString mnc; - QString password; - QString port; - QString proxy; - QString server; - QString type; - QString user; -}ST_APNINFO; -class ControlNetConfigWidget : public QWidget { - Q_OBJECT -public: - explicit ControlNetConfigWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlNetConfigWidget(); -protected slots: - void changeEvent(QEvent *) override; - void transUi(); - - void onSetWiFiModel(); - void onReadbackWiFiModel(); - void onSetAp(); - void OnDhcpOrSpecifyIp(int iIndex); - void OnScanWifi(); - void onSet4GInfo(); - void onReadback4G(); - void onReadbackFlightModel(); - void onGetMcc(); - void onGet4GStatus(); - void SetMcc(QString strMcc); - void onFightModelChecked(bool b); -signals: - void sigSend(QJsonObject &,QString); - void sigGetDhcpOrSpecifyIp(int); -protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - void OnComboMccChanged(int); - void OnComboCarrierChanged(int index); - void OnCustom4G(bool b); - void OnOpne4G(bool b); - -private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; - QList m_ApnInfoiList; - QList m_MccCarrierInfoiList; - QJsonObject m_4gObj; - QString mcc; - QString apn; - bool iEnableFlag=true; - int m_buttonFlagClick=0; - - - QButtonGroup *m_buttonGroup; - QLabel *lbLanCfg; - QRadioButton *fdDhcp; - QRadioButton *fdSpecifyIp; - QVBoxLayout *vBoxSpecifyIp; - QGroupBox *gBoxSpecifyIp; - QLabel *labelIpAddress; - QIPLineEdit *fdIP; - QLabel *labelMaskAddress; - QIPLineEdit *fdGateWay; - QLabel *labelGateway; - QIPLineEdit *fdMask; - QLabel *labelDnsAddress; - QIPLineEdit *fdDns; - QPushButton *btnLanSet; - QPushButton *btnLanGet; - QLabel *label_5; - QHBoxLayout *horizontalLayout_2; - QVBoxLayout *verticalLayout_6; - QGroupBox *groupBox_3; - QVBoxLayout *verticalLayout_7; - QHBoxLayout *horizontalLayout_9; - QVBoxLayout *verticalLayout_11; - QLabel *labelWifiName; - QLabel *labelWifiPassword; - QVBoxLayout *verticalLayout_12; - QComboBox *comboBox; - QLineEdit *lineEditWifiPassword; - QVBoxLayout *verticalLayout_13; - QPushButton *pushButtonScan; - QSpacerItem *horizontalSpacer_10; - QPushButton *pushButtonWiFiModel; - QPushButton *pushButtonReadbackWiFiModel; - QVBoxLayout *verticalLayout_4; - QGroupBox *groupBox_4; - QVBoxLayout *verticalLayout_8; - QHBoxLayout *horizontalLayout_12; - QVBoxLayout *verticalLayout_14; - QLabel *labelApName; - QLabel *labelApPassword; - QVBoxLayout *verticalLayout_15; - QLineEdit *lineEditHotspotName; - QLineEdit *lineEditApPassword; - QPushButton *pushButtonApSet; - QSpacerItem *horizontalSpacer_2; - QFrame *line_3; - QLabel *label; - QCheckBox *checkBox4g; - QHBoxLayout *horizontalLayout_13; - QPushButton *pushButtonReadback4G; - QLabel *label_ApnInfo; - QLineEdit *lineEditApnInfo; - QPushButton *pushButtonRead4GStatus; - QSpacerItem *horizontalSpacer_6; - QSpacerItem *verticalSpacer_2; - QGroupBox *groupBox_5; - QVBoxLayout *verticalLayout_16; - QLabel *label_8; - QCheckBox *checkBoxCustom; - QHBoxLayout *horizontalLayout_10; - QPushButton *pushButtonGetMcc; - QLabel *label_9; - QLabel *label_2; - QComboBox *comboBoxCountryID; - QLabel *label_11; - QLabel *label_3; - QComboBox *comboBoxCarrierName; - QLabel *label_12; - QLabel *label_4; - QLineEdit *lineEditAPN; - QSpacerItem *horizontalSpacer_3; - QHBoxLayout *horizontalLayout_11; - QLabel *label_6; - QLineEdit *lineEditUser; - QLabel *label_7; - QLineEdit *lineEditPassword; - QSpacerItem *horizontalSpacer_7; - QHBoxLayout *horizontalLayout_8; - QSpacerItem *horizontalSpacer_5; - QPushButton *pushButtonSet4GInfo; - QPushButton *pushButtonSetYuanHengApn; - QSpacerItem *horizontalSpacer_4; - QSpacerItem *verticalSpacer_4; - QHBoxLayout *horizontalLayout_15; - QLabel *label_10; - SwitchControl *widgetFightModel; - QPushButton *pushButtonReadbackFlightModel; - QSpacerItem *horizontalSpacer_8; - QSpacerItem *verticalSpacer; -}; - -#endif // CONTROLNETCONFIGWIDGET_H diff --git a/LedOK/wDevicesManager/controlpowermanual.cpp b/LedOK/wDevicesManager/controlpowermanual.cpp deleted file mode 100644 index 58a56c3..0000000 --- a/LedOK/wDevicesManager/controlpowermanual.cpp +++ /dev/null @@ -1,222 +0,0 @@ -#include "controlpowermanual.h" -#include "ui_controlpowermanual.h" -#include "base/x_uimsgboxok.h" -#include -#include -#include -#include -#include "tools.h" -ControlPowerManual::ControlPowerManual(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlPowerManual) -{ - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - ui->pushButtonReadback->setProperty("ssType", "progManageTool"); - ui->widget->setSliderColor(QColor(0, 0, 0),QColor(0, 160, 230)); - ui->widget->setBgColor(QColor(200,200,200),QColor(0,200,0)); - ui->widget->setTextColor(QColor(100,100,100),QColor(0, 160, 230)); - ui->widget->setText(tr("OFF"),tr("ON")); - //按钮槽函数绑定 - connect(ui->widget, SIGNAL(checkedChanged(bool)), this, SLOT(onPowerChecked(bool))); - connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnReadback())); - MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) - -} - -ControlPowerManual::~ControlPowerManual() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void ControlPowerManual::refreshLable() -{ - ui->labelPower->setText(tr("POWER")); - ui->pushButtonReadback->setText(tr("Readback")); -} - -void ControlPowerManual::OnReadback() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "IsScreenOn"); - MACRO_DEFINE_TIPDLG_FUCN(tr("IsScreenOn"),tr("Success"),tr("failed")) - -} -void ControlPowerManual::onPowerChecked(bool b) -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard==nullptr||m_pLedlist->count()==0) - { - X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1); - pDlg->exec(); - return; - } - } - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetScreenOn"); - json.insert("on", b); - if(m_pLedlist->count()==1) - { - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - if(m_PostingDlg==nullptr) - { - m_PostingDlg = new LoEmptyDialog(this); - connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg())); - connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock())); - if(b) - m_PostingDlg->lock(tr("SetScreenOn"),tr("Success"),tr("SetScreenOn")+tr("on")+tr("failed")); - else - m_PostingDlg->lock(tr("SetScreenOn"),tr("Success"),tr("SetScreenOff")+tr("off")+tr("failed")); - m_pGetAskTimer->start(3000); - m_PostingDlg->exec(); - - } - } - else { - if(b) - emit sigSend(json,tr("SetScreenOn")+":"+tr("on")); - else - emit sigSend(json,tr("SetScreenOff")+":"+tr("off")); - } -} -void ControlPowerManual::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - if(m_pLedlist==nullptr) - return; - MACRO_DEFINE_CONTROL_FUNC3 -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlPowerManual::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "SetScreenOn") - { - //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetBrightness")+":"+tr("success")); - } - else if(strType == "IsScreenOn"){ - - ui->widget->setCheckedStatus(jsonObject["on"].toBool()); - - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlPowerManual::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "IsScreenOn"){ - - ui->widget->setCheckedStatus(jsonObject["on"].toBool()); - - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -void ControlPowerManual::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_PowerControl) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlPowerManual::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "IsScreenOn"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - MACRO_DEFINE_TIPDLG_ALL_FUCN(tr("Readback"),tr("Success"),tr("failed")) -} -void ControlPowerManual::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} diff --git a/LedOK/wDevicesManager/controlpowermanual.h b/LedOK/wDevicesManager/controlpowermanual.h deleted file mode 100644 index 430a44c..0000000 --- a/LedOK/wDevicesManager/controlpowermanual.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef CONTROLPOWERMANUAL_H -#define CONTROLPOWERMANUAL_H - -#include -#include -#include -#include -namespace Ui { -class ControlPowerManual; -} - -class ControlPowerManual : public QWidget -{ - Q_OBJECT - -public: - explicit ControlPowerManual(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlPowerManual(); -protected slots: - void onPowerChecked(bool b); - void OnReadback(); - void refreshLable(); -private: - Ui::ControlPowerManual *ui; - - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigSend(QJsonObject &,QString); - protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; -}; - -#endif // CONTROLPOWERMANUAL_H diff --git a/LedOK/wDevicesManager/controlpowermanual.ui b/LedOK/wDevicesManager/controlpowermanual.ui deleted file mode 100644 index 9f778fc..0000000 --- a/LedOK/wDevicesManager/controlpowermanual.ui +++ /dev/null @@ -1,162 +0,0 @@ - - - ControlPowerManual - - - - 0 - 0 - 576 - 401 - - - - Form - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 40 - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - POWER - - - - - - - - 0 - 0 - - - - - 80 - 33 - - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 60 - 30 - - - - Readback - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - SwitchControl - QWidget -
base/switchcontrol.h
- 1 -
-
- - -
diff --git a/LedOK/wDevicesManager/controlpowerwidget.cpp b/LedOK/wDevicesManager/controlpowerwidget.cpp deleted file mode 100644 index cb0a2dc..0000000 --- a/LedOK/wDevicesManager/controlpowerwidget.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "controlpowerwidget.h" -#include "ui_controlpowerwidget.h" -#include "tools.h" - -ControlPowerWidget::ControlPowerWidget(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlPowerWidget) -{ - m_pLedlist=list; - ui->setupUi(this); -setStyleSheet(Tools::styleSheet()); - m_pStackedW = new QStackedWidget; - m_pManual = new ControlPowerManual(this,m_pLedlist); - m_pSchedule = new ControlPowerSchedule(this,m_pLedlist); - m_pStackedW->addWidget(m_pManual); - m_pStackedW->addWidget(m_pSchedule); - ui->horizontalLayout_2->addWidget(m_pStackedW); - init(); - connect(m_pSchedule,SIGNAL(sigHaveSchedule(bool)),this,SLOT(OnGetPowerModeType(bool))); - - } - -ControlPowerWidget::~ControlPowerWidget() -{ - m_pStackedW->deleteLater() ; - m_pManual->deleteLater() ; - m_pSchedule->deleteLater() ; - delete ui; -} -void ControlPowerWidget::refreshLable() -{ - ui->labelPowerConfiguration->setText(tr("Power Configuration")); - ui->radioButtonManual->setText(tr("Manual")); - ui->radioButtonSchedule->setText(tr("Schedule")); -} - -void ControlPowerWidget::init() -{ - m_buttonGroup = new QButtonGroup; - //第二个参数id可以自行定义 - m_buttonGroup->addButton(ui->radioButtonManual,0); - m_buttonGroup->addButton(ui->radioButtonSchedule,1); - connect(m_buttonGroup,SIGNAL(buttonClicked(int)),m_pStackedW,SLOT(setCurrentIndex(int))); - ui->radioButtonManual->setChecked(true); - m_pStackedW->setCurrentIndex(0); - -} - -void ControlPowerWidget::OnGetPowerModeType(bool b) -{ - if(b) - { - m_pStackedW->setCurrentIndex(1); - ui->radioButtonSchedule->setChecked(true); - } - else { - m_pStackedW->setCurrentIndex(0); - ui->radioButtonManual->setChecked(true); - - } -} diff --git a/LedOK/wDevicesManager/controlpowerwidget.h b/LedOK/wDevicesManager/controlpowerwidget.h deleted file mode 100644 index 0534282..0000000 --- a/LedOK/wDevicesManager/controlpowerwidget.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef CONTROLPOWERWIDGET_H -#define CONTROLPOWERWIDGET_H - -#include -#include -#include -#include "QStackedWidget" -#include -namespace Ui { -class ControlPowerWidget; -} - -class ControlPowerWidget : public QWidget -{ - Q_OBJECT - -public: - explicit ControlPowerWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlPowerWidget(); -protected slots: - void refreshLable(); - void OnGetPowerModeType(bool b); - -private: - void init(); -private: - Ui::ControlPowerWidget *ui; - ControlPowerManual *m_pManual=nullptr; - ControlPowerSchedule *m_pSchedule=nullptr; - QStackedWidget *m_pStackedW; - QButtonGroup *m_buttonGroup; - QList *m_pLedlist=nullptr; - -}; - -#endif // CONTROLPOWERWIDGET_H diff --git a/LedOK/wDevicesManager/controlpowerwidget.ui b/LedOK/wDevicesManager/controlpowerwidget.ui deleted file mode 100644 index 48321ac..0000000 --- a/LedOK/wDevicesManager/controlpowerwidget.ui +++ /dev/null @@ -1,145 +0,0 @@ - - - ControlPowerWidget - - - - 0 - 0 - 234 - 423 - - - - Form - - - background-color: #F5F5F5; - - - - - - - Arial - 12 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - Power Configuration - - - Qt::AlignCenter - - - - - - - Qt::Horizontal - - - - - - - 9 - - - 9 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - background-color:transparent - - - Manual - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - background-color:transparent - - - Schedule - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - diff --git a/LedOK/wDevicesManager/controlvolumemanual.cpp b/LedOK/wDevicesManager/controlvolumemanual.cpp deleted file mode 100644 index d4e39ea..0000000 --- a/LedOK/wDevicesManager/controlvolumemanual.cpp +++ /dev/null @@ -1,184 +0,0 @@ -#include "controlvolumemanual.h" -#include "ui_controlvolumemanual.h" -#include -#include -#include -#include -#include "tools.h" -extern QWidget *gMainWin; - -ControlVolumeManual::ControlVolumeManual(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlVolumeManual) -{ - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - onSelectedDeviceList(list); - ui->horizontalSlider->setRange(0,15); - ui->horizontalSlider->setTickPosition(QSlider::TicksAbove); - ui->pushButtonReadback->setProperty("ssType", "progManageTool"); - connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnReadback())); - connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), ui->labelCurValue, SLOT(setNum(int))); - connect(ui->horizontalSlider, SIGNAL(sliderReleased()), this, SLOT(setVolumeValue())); - - MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent()) -} - -ControlVolumeManual::~ControlVolumeManual() -{ - delete ui; - if(pHpptClient != nullptr) - { - qDebug() <<"delete pHpptClient in ~NetComm"; - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr) - { - qDebug() <<"delete pHpptClientAll in ~NetComm"; - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void ControlVolumeManual::setVolumeValue() -{ - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetVolume"); - json.insert("volume", ui->labelCurValue->text().toInt()); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetVolume"),tr("Success"),tr("failed")) - -} -void ControlVolumeManual::refreshLable() -{ - ui->labelVolume->setText(tr("Volume(min:0-max:15)")); - ui->pushButtonReadback->setText(tr("Readback")); -} - - -void ControlVolumeManual::OnReadback() -{ - CHECK_CARD_SELECTED - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetVolume"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetVolume"),tr("Success"),tr("failed")) - -} -void ControlVolumeManual::onSelectedDeviceList(QList *list) -{ - m_pLedlist=list; - MACRO_DEFINE_CONTROL_FUNC3 - -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlVolumeManual::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "SetVolume") - { - //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetBrightness")+":"+tr("success")); - } - else if(strType == "GetVolume"){ - - int itempVolume=jsonObject["volume"].toInt(); - ui->horizontalSlider->setValue(itempVolume); - ui->labelCurValue->setNum(itempVolume); - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void ControlVolumeManual::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetVolume"){ - int itempVolume=jsonObject["volume"].toInt(); - ui->horizontalSlider->setValue(itempVolume); - ui->labelCurValue->setNum(itempVolume); - - } - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - } -} -void ControlVolumeManual::OnControlTypeSwitchIndexChanged(int index) -{ - if(index==Setting_Volume) - { - m_bSelected=true; - if(m_pLedCard!=nullptr) - onReadbackAllThisPage(); - } - else { - m_bSelected=false; - } -} -void ControlVolumeManual::onReadbackAllThisPage() -{ - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()!=1) - return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetVolume"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - MACRO_DEFINE_TIPDLG_ALL_FUCN(tr("Readback"),tr("Success"),tr("failed")) - -} -void ControlVolumeManual::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} diff --git a/LedOK/wDevicesManager/controlvolumemanual.h b/LedOK/wDevicesManager/controlvolumemanual.h deleted file mode 100644 index 2cb4302..0000000 --- a/LedOK/wDevicesManager/controlvolumemanual.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef CONTROLVOLUMEMANUAL_H -#define CONTROLVOLUMEMANUAL_H - -#include -#include -#include -#include -namespace Ui { -class ControlVolumeManual; -} - -class ControlVolumeManual : public QWidget -{ - Q_OBJECT - -public: - explicit ControlVolumeManual(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlVolumeManual(); -protected slots: - void OnReadback(); - void refreshLable(); - -private: - Ui::ControlVolumeManual *ui; - //类似的控制操作信号和槽函数和变量定义 - signals: - void sigSend(QJsonObject &,QString); - protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void onSelectedDeviceList(QList *); - void onReadbackAllThisPage(); - void OnControlTypeSwitchIndexChanged(int index); - void setVolumeValue(); - private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - LedCard *m_oldLedlist = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_bSelected=false; -}; - -#endif // CONTROLVOLUMEMANUAL_H diff --git a/LedOK/wDevicesManager/controlvolumemanual.ui b/LedOK/wDevicesManager/controlvolumemanual.ui deleted file mode 100644 index 78ea608..0000000 --- a/LedOK/wDevicesManager/controlvolumemanual.ui +++ /dev/null @@ -1,123 +0,0 @@ - - - ControlVolumeManual - - - - 0 - 0 - 555 - 416 - - - - Form - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - Volume(0-15) - - - - - - - Qt::Horizontal - - - - - - - - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 60 - 30 - - - - Readback - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - diff --git a/LedOK/wDevicesManager/controlvolumewidget.cpp b/LedOK/wDevicesManager/controlvolumewidget.cpp deleted file mode 100644 index 736fa7e..0000000 --- a/LedOK/wDevicesManager/controlvolumewidget.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "controlvolumewidget.h" -#include "ui_controlvolumewidget.h" -#include "tools.h" - -ControlVolumeWidget::ControlVolumeWidget(QWidget *parent,QList *list) : - QWidget(parent), - ui(new Ui::ControlVolumeWidget) -{ - m_pLedlist=list; - ui->setupUi(this); - refreshLable(); -setStyleSheet(Tools::styleSheet()); - m_pStackedW = new QStackedWidget; - m_pManual = new ControlVolumeManual(this,m_pLedlist); - m_pSchedule = new ControlVolumeSchedule(this,m_pLedlist); - m_pStackedW->addWidget(m_pManual); - m_pStackedW->addWidget(m_pSchedule); - ui->horizontalLayout_2->addWidget(m_pStackedW); - init(); - connect(parent->parent(),SIGNAL(sigSelectedDeviceList(QList *)),this,SLOT(onSelectedDeviceList(QList *))); - connect(m_pSchedule,SIGNAL(sigHaveSchedule(bool)),this,SLOT(OnGetVolumeModeType(bool))); - -} - -ControlVolumeWidget::~ControlVolumeWidget() -{ - m_pStackedW->deleteLater() ; - m_pManual->deleteLater() ; - m_pSchedule->deleteLater() ; - delete ui; -} -void ControlVolumeWidget::refreshLable() -{ - ui->labelVolumeControl->setText(tr("Volume Control")); - ui->radioButtonManual->setText(tr("Manual")); - ui->radioButtonSchedule->setText(tr("Schedule")); -} - -void ControlVolumeWidget::init() -{ - m_buttonGroup = new QButtonGroup; - //第二个参数id可以自行定义 - m_buttonGroup->addButton(ui->radioButtonManual,0); - m_buttonGroup->addButton(ui->radioButtonSchedule,1); - connect(m_buttonGroup,SIGNAL(buttonClicked(int)),m_pStackedW,SLOT(setCurrentIndex(int))); - ui->radioButtonManual->setChecked(true); - m_pStackedW->setCurrentIndex(0); - -} -void ControlVolumeWidget::OnGetVolumeModeType(bool b) -{ - if(b) - { - m_pStackedW->setCurrentIndex(1); - ui->radioButtonSchedule->setChecked(true); - } - else - { - m_pStackedW->setCurrentIndex(0); - ui->radioButtonManual->setChecked(true); - } -} diff --git a/LedOK/wDevicesManager/controlvolumewidget.h b/LedOK/wDevicesManager/controlvolumewidget.h deleted file mode 100644 index 1b65eff..0000000 --- a/LedOK/wDevicesManager/controlvolumewidget.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef CONTROLVOLUMEWIDGET_H -#define CONTROLVOLUMEWIDGET_H - -#include -#include -#include -#include "QStackedWidget" -#include -namespace Ui { -class ControlVolumeWidget; -} - -class ControlVolumeWidget : public QWidget -{ - Q_OBJECT - -public: - explicit ControlVolumeWidget(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~ControlVolumeWidget(); -private: - void init(); -protected slots: - void refreshLable(); - void OnGetVolumeModeType(bool b); -private: - Ui::ControlVolumeWidget *ui; - ControlVolumeManual *m_pManual=nullptr; - ControlVolumeSchedule *m_pSchedule=nullptr; - QStackedWidget *m_pStackedW; - QButtonGroup *m_buttonGroup; - QList *m_pLedlist=nullptr; -}; - -#endif // CONTROLVOLUMEWIDGET_H diff --git a/LedOK/wDevicesManager/controlvolumewidget.ui b/LedOK/wDevicesManager/controlvolumewidget.ui deleted file mode 100644 index 4e3cd05..0000000 --- a/LedOK/wDevicesManager/controlvolumewidget.ui +++ /dev/null @@ -1,154 +0,0 @@ - - - ControlVolumeWidget - - - - 0 - 0 - 407 - 512 - - - - Form - - - - - - - Arial - 12 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - Volume Control - - - Qt::AlignCenter - - - - - - - Qt::Horizontal - - - - - - - 9 - - - 9 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - Arial - 12 - - - - background-color:transparent - - - Manual - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - Arial - 12 - - - - background-color:transparent - - - Schedule - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - diff --git a/LedOK/wDevicesManager/ctrladvancedpanel.cpp b/LedOK/wDevicesManager/ctrladvancedpanel.cpp deleted file mode 100644 index ba011b5..0000000 --- a/LedOK/wDevicesManager/ctrladvancedpanel.cpp +++ /dev/null @@ -1,2044 +0,0 @@ -#include "ctrladvancedpanel.h" -#include "deviceitem.h" -#include "globaldefine.h" -#include "base/waitingdlg.h" -#include "base/changepasswordform.h" -#include "base/updateledset3dialog.h" -#include "passwordindlg.h" -#include "tools.h" -#include "wProgramManager/ephoto.h" -#include "upgradeapkdialog.h" -#include "base/table.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "tcpsocket.h" - -CtrlAdvancedPanel::CtrlAdvancedPanel(QWidget *parent,QList *list) : QWidget(parent), m_pLedlist(list) { - m_pLedlist = gSelCards; - setFocusPolicy(Qt::StrongFocus); - auto vBox = new QVBoxLayout(this); - - lbTitle = new QLabel; - lbTitle->setAlignment(Qt::AlignCenter); - vBox->addWidget(lbTitle); - - auto hBox = new QHBoxLayout; - - lbScreenWidth = new QLabel; - hBox->addWidget(lbScreenWidth); - - fdScreenWidth = new QLineEdit; - fdScreenWidth->setMaximumWidth(60); - hBox->addWidget(fdScreenWidth); - - lbScreenHeight = new QLabel; - hBox->addWidget(lbScreenHeight); - - fdScreenHeight = new QLineEdit; - fdScreenHeight->setMaximumWidth(60); - hBox->addWidget(fdScreenHeight); - - btnScreenSet = new QPushButton; - btnScreenSet->setProperty("ssType", "progManageTool"); - connect(btnScreenSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - auto width = fdScreenWidth->text(); - if(width.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"),tr("InputWidthTip")); - fdScreenWidth->setFocus(); - return; - } - auto height = fdScreenHeight->text(); - if(height.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"),tr("InputHeightTip")); - fdScreenHeight->setFocus(); - return; - } - QJsonObject json; - json.insert("_id", "SetScreenSize"); - json.insert("_type", "SetScreenSize"); - json.insert("width", width.toInt()); - json.insert("height", height.toInt()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetScreenSize")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetScreenSize")) - } - } - }); - hBox->addWidget(btnScreenSet); - - hBox->addSpacing(20); - - lbAlias = new QLabel; - hBox->addWidget(lbAlias); - - fdAlias = new QLineEdit; - fdAlias->setMaximumWidth(200); - hBox->addWidget(fdAlias); - - btnAliasSet = new QPushButton; - btnAliasSet->setProperty("ssType", "progManageTool"); - connect(btnAliasSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - auto alias = fdAlias->text(); - if(alias.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"),tr("InputAliasTip")); - fdAlias->setFocus(); - return; - } - QJsonObject json; - json.insert("_id", "SetCardAlias"); - json.insert("_type", "SetCardAlias"); - json.insert("alias", QString::fromLatin1(alias.toUtf8().toBase64())); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetCardAlias")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetCardAlias")) - } - } - }); - hBox->addWidget(btnAliasSet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - labelWebServer = new QLabel; - hBox->addWidget(labelWebServer); - - fdWebServerAddr = new QComboBox; - fdWebServerAddr->addItem(tr("www.m2mled.net")); - fdWebServerAddr->addItem(tr("www.ledaips.com")); - fdWebServerAddr->addItem(tr("https://www.taxihub.cn:2340")); - fdWebServerAddr->addItem(tr("https://www.ledaips.com:2340")); - fdWebServerAddr->addItem(tr("https://www.36taxi.com:2340")); - fdWebServerAddr->addItem(tr("www.tlzxled.com")); - fdWebServerAddr->setMinimumWidth(260); - fdWebServerAddr->setEditable(true); - hBox->addWidget(fdWebServerAddr); - - lbCompanyId = new QLabel; - hBox->addWidget(lbCompanyId); - - fdCompanyId = new QLineEdit; - fdCompanyId->setFixedWidth(100); - hBox->addWidget(fdCompanyId); - - btnWebServerSet = new QPushButton; - btnWebServerSet->setProperty("ssType", "progManageTool"); - connect(btnWebServerSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - - QString serverAddr = fdWebServerAddr->currentText(); - if(serverAddr.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"),tr("InputWebServerAddressTip")); - fdWebServerAddr->setFocus(); - return; - } - auto companyId = fdCompanyId->text(); - if(companyId.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"),tr("InputCompanyIdTip")); - fdCompanyId->setFocus(); - return; - } - auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Do you want to modify webserveraddress and companyId?")); - if(res != QMessageBox::Yes) return; - QJsonObject json; - json.insert("_id", "SetOnlineAddr"); - json.insert("_type", "SetOnlineAddr"); - json.insert("server", serverAddr); - json.insert("companyID", companyId); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("SetOnlineAddr")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("SetOnlineAddr")) - } - } - }); - hBox->addWidget(btnWebServerSet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - label = new QLabel; - hBox->addWidget(label); - - comboBox_realtimeServer = new QComboBox; - comboBox_realtimeServer->addItem(tr("www.ledokcloud.com/realtime")); - comboBox_realtimeServer->setMinimumWidth(260); - comboBox_realtimeServer->setEditable(true); - hBox->addWidget(comboBox_realtimeServer); - - pushButtonSetREaltimeServer = new QPushButton; - hBox->addWidget(pushButtonSetREaltimeServer); - - pushButtonClearRealtimerAddress = new QPushButton; - hBox->addWidget(pushButtonClearRealtimerAddress); - - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - btnApkCheck = new QPushButton; - btnApkCheck->setProperty("ssType", "progManageTool"); - connect(btnApkCheck, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "CheckSoftVersions"); - json.insert("_type", "CheckSoftVersions"); - if(gSelCards->count() != 1) return; - auto waitingDlg = new WaitingDlg(this, tr("Check Apk Version")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->close(); - fdPkg->clear(); - auto apps = json["apps"].toArray(); - auto infoDlg = new QDialog(this); - infoDlg->setWindowFlag(Qt::WindowContextHelpButtonHint, false); - infoDlg->resize(500, 500); - infoDlg->setWindowTitle(tr("Software Version Info")); - auto vBox = new QVBoxLayout(infoDlg); - vBox->setContentsMargins(0, 0, 0, 0); - auto table = new Table{ - {"apk", "Apk"}, - {"ver", tr("Version")}, - {"pkg", tr("Package")} - }; - table->setDefs(); - table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - table->setRowCount(apps.size()); - vBox->addWidget(table); - for(int i=0; isetItem(i, "apk", new QTableWidgetItem{app["appName"].toString()}); - table->setItem(i, "ver", new QTableWidgetItem{app["versionName"].toString()}); - table->setItem(i, "pkg", new QTableWidgetItem{packageName}); - if(! (packageName.endsWith(".cardsystem") || packageName.endsWith(".systemcore") || packageName.endsWith(".update"))) fdPkg->addItem(packageName); - } - infoDlg->show(); - }); - }); - hBox->addWidget(btnApkCheck); - - btnApkUpgrade = new QPushButton; - btnApkUpgrade->setProperty("ssType", "progManageTool"); - connect(btnApkUpgrade, &QPushButton::clicked, this, [this] { - if(m_pLedlist==0) return; - if(m_pLedlist->count()==0 || (m_pLedlist->count()==1 && m_pLedCard==nullptr)) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - if(m_pLedlist->count() != 1) return; - if(m_pLedCard->bPassword && m_pLedCard->m_bLockStatus && m_lockFlag) { - QMessageBox::information(gMainWin, tr("Tip"),tr("This screen is encrypted,Please decrypt and upgrade APK!")); - return; - } - QString url = "http://"+m_pLedCard->m_strCardIp+":2016/upload?type=software"; - m_strUpgradeApkFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("apk package (*.apk *.zip)")); - QFileInfo file1(m_strUpgradeApkFile); - QFile file(m_strUpgradeApkFile); - QMap params_send; //上传的普通参数 在本程序中 需要上传一个普通参数为"username" - params_send.insert("username","10005"); - UpLoadForm(url, params_send, file1.fileName(), &file, 0); - }); - hBox->addWidget(btnApkUpgrade); - - fdPkg = new QComboBox; - fdPkg->setEditable(true); - fdPkg->setMinimumWidth(200); - hBox->addWidget(fdPkg); - - fdUnload = new QPushButton; - connect(fdUnload, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - auto pkg = fdPkg->currentText(); - if(pkg.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("Package name is null")); - return; - } - QJsonObject json; - json.insert("_id", "UninstallSoftware"); - json.insert("_type", "UninstallSoftware"); - json.insert("packageName", pkg); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("UninstallSoftware")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("UninstallSoftware")) - } - } - }); - hBox->addWidget(fdUnload); - - btnRunningCheck = new QPushButton; - connect(btnRunningCheck, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - auto pkg = fdPkg->currentText(); - if(pkg.isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("Package name is null")); - return; - } - QJsonObject json; - json.insert("_id", "IsSoftwareRunning"); - json.insert("_type", "IsSoftwareRunning"); - json.insert("packageName", pkg); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("IsSoftwareRunning")); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->close(); - QMessageBox::information(gMainWin, tr("Tip"), json["running"].toBool() ? tr("running") : tr("no running")); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - gFdResInfo->append(card->m_strCardId+" "+tr("IsSoftwareRunning")+" "+(err.isEmpty() ? (json["running"].toBool() ? tr("running") : tr("no running")) : err)); - }); - } - } - }); - hBox->addWidget(btnRunningCheck); - - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - pushButtonFpgaUpgrade = new QPushButton; - hBox->addWidget(pushButtonFpgaUpgrade); - - pushButtonFpgaVerCheck = new QPushButton; - hBox->addWidget(pushButtonFpgaVerCheck); - - pushButtonSyncFpgaVer = new QPushButton; - hBox->addWidget(pushButtonSyncFpgaVer); - - pushButtonRestart = new QPushButton; - hBox->addWidget(pushButtonRestart); - - hBox->addStretch(); - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - btnClearProg = new QPushButton; - btnClearProg->setProperty("ssType", "progManageTool"); - connect(btnClearProg, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Clearing Program")+" ..."); - waitingDlg->show(); - auto card = gSelCards->at(0); - auto tcp = new QTcpSocket(); - auto timer = new QTimer(tcp); - timer->setSingleShot(true); - connect(timer, &QTimer::timeout, tcp, [tcp] { - tcp->close(); - QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear Program")+" "+tr("Timeout")); - }); - connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater); - connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { - timer->stop(); - tcp->write("{\"_type\":\"DelPrograms\",\"_id\":\"DelPrograms\",\"zVer\":\"xixun1\"}"); - timer->start(10000); - }); - connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, waitingDlg] { - timer->stop(); - QByteArray resp = tcp->readAll(); - tcp->close(); - QJsonParseError parseErr; - QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); - if(parseErr.error != QJsonParseError::NoError) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), parseErr.errorString()); - } - else if(! json["success"].toBool()) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear Program")+" "+tr("Failed")); - } else waitingDlg->success(); - }); - connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, waitingDlg](QAbstractSocket::SocketError err) { - timer->stop(); - tcp->close(); - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), QString(socketErrKey(err))+" ("+QString::number(err)+") "+tcp->errorString()); - }); - tcp->connectToHost(card->m_strCardIp, 3333); - timer->start(10000); - } else { - foreach(auto card, *gSelCards) { - auto tcp = new QTcpSocket(); - auto timer = new QTimer(tcp); - timer->setSingleShot(true); - connect(timer, &QTimer::timeout, tcp, [tcp, card] { - tcp->close(); - gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+tr("Timeout")); - }); - connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater); - connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { - timer->stop(); - tcp->write("{\"_type\":\"DelPrograms\",\"_id\":\"DelPrograms\",\"zVer\":\"xixun1\"}"); - timer->start(10000); - }); - connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, card] { - timer->stop(); - QByteArray resp = tcp->readAll(); - tcp->close(); - QJsonParseError parseErr; - QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); - if(parseErr.error != QJsonParseError::NoError) gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+parseErr.errorString()); - else if(! json["success"].toBool()) gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+tr("Failed")); - else gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+tr("Success")); - }); - connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, card](QAbstractSocket::SocketError err) { - timer->stop(); - tcp->close(); - gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+QMetaEnum::fromType().valueToKey(err)+" ("+QString::number(err)+") "+tcp->errorString()); - }); - tcp->connectToHost(card->m_strCardIp, 3333); - timer->start(10000); - } - } - }); - - hBox->addWidget(btnClearProg); - - btnGetLog = new QPushButton; - btnGetLog->setProperty("ssType", "progManageTool"); - connect(btnGetLog, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Getting Log")+" ..."); - waitingDlg->show(); - auto card = gSelCards->at(0); - auto reply = Tools::netManager().get(netReq("http://"+card->m_strCardIp+":2016/download?file=logs")); - connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] { - waitingDlg->close(); - QString err = parseReplyJson(reply); - if(! err.isEmpty()) { - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - QString logFile = QApplication::applicationDirPath()+"/log_"+m_pLedCard->m_strCardId+".txt"; - QFile file(logFile); - if(! file.open(QIODevice::WriteOnly)) { - QMessageBox::critical(gMainWin, tr("Error"), "Open for Write Fail"); - return; - } - file.write(reply->readAll()); - file.close(); - QProcess::execute("notepad", {logFile}); - }); - } - }); - hBox->addWidget(btnGetLog); - - hBox->addStretch(); - vBox->addLayout(hBox); - - groupM80 = new QGroupBox; - hBox = new QHBoxLayout(groupM80); - - fdM80 = new QComboBox(); - fdM80->setMinimumWidth(160); - fdM80->setEditable(true); - mM80Map.insert("576×3840","625×3960"); - mM80Map.insert("640×3840","660×3960"); - mM80Map.insert("720×3200","750×3300"); - mM80Map.insert("864×2672","900×2750"); - mM80Map.insert("1080×1920","1125×2200"); - mM80Map.insert("1280×1760","1320×1850"); - mM80Map.insert("1472×1536","1500×1650"); - mM80Map.insert("1536×1472","1650×1500"); - mM80Map.insert("1760×1280","1850×1320"); - mM80Map.insert("1920×1080","2200×1125"); - mM80Map.insert("2672×864","2750×900"); - mM80Map.insert("3200×760","3300×825"); - mM80Map.insert("3200×720","3300×750"); - mM80Map.insert("3840×640","3960×660"); - mM80Map.insert("3840×576","3960×625"); - mM80Map.insert("4096×480","4500×550"); - fdM80->addItems(mM80Map.keys()); - hBox->addWidget(fdM80); - - btnM80Set = new QPushButton(); - hBox->addWidget(btnM80Set); - - btnM80Refresh = new QPushButton(); - hBox->addWidget(btnM80Refresh); - - btnM80Restore = new QPushButton(); - hBox->addWidget(btnM80Restore); - - hBox->addStretch(); - - vBox->addWidget(groupM80); - - hBox = new QHBoxLayout(); - - btnLedSet3 = new QPushButton; - btnLedSet3->setMinimumHeight(34); - btnLedSet3->setProperty("ssType", "progManageTool"); - connect(btnLedSet3, SIGNAL(clicked()),this,SLOT(OnStartConfigLedScreenSoft())); - hBox->addWidget(btnLedSet3); - - btnLedSet4 = new QPushButton; - btnLedSet4->setMinimumHeight(34); - btnLedSet4->setProperty("ssType", "progManageTool"); - connect(btnLedSet4, &QPushButton::clicked, btnLedSet4, [] { - QFileInfo file("LedSet4.0/LedSet4.0.exe"); - if(file.exists()) QProcess::startDetached(file.absoluteFilePath(), QStringList()); - }); - hBox->addWidget(btnLedSet4); - - vBox->addLayout(hBox); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - vBox->addWidget(line); - - hBox = new QHBoxLayout(); - btnBindTaxiIc = new QPushButton; - btnBindTaxiIc->setProperty("ssType", "progManageTool"); - connect(btnBindTaxiIc, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QString icFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("indentity voucher (*.ic)")); - if(icFile.isEmpty()) return; - QFile file(icFile); - if(! file.open(QIODevice::ReadOnly)) { - QMessageBox::information(gMainWin, tr("Tip"), tr("Open file Failed")); - return; - } - auto data = file.readAll(); - file.close(); - QJsonParseError jsonErr; - QJsonDocument icJson = QJsonDocument::fromJson(data, &jsonErr); - if(jsonErr.error != QJsonParseError::NoError) { - QMessageBox::information(gMainWin, tr("Tip"), "JsonError "+jsonErr.errorString()+"\n"+data); - return; - } - QJsonObject jsonCommand; - jsonCommand.insert("action", "BindAccount"); - jsonCommand.insert("accountIdToken", icJson["account_id_token"]); - jsonCommand.insert("server", icJson["taxiServerURL"]); - jsonCommand.insert("tlsServer", icJson["taxiServerTLSURL"]); - QJsonObject json; - json.insert("action", "InvokeTaxiAppFunction"); - json.insert("jsonCommand", jsonCommand); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("InvokeTaxiAppFunction")); - waitingDlg->show(); - auto reply = Tools::netManager().post(reqForJson("http://"+gSelCards->at(0)->m_strCardIp+":3000"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - QString err = parseReplyJson(reply); - if(! err.isEmpty()) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Error"), err); - return; - } - auto data = reply->readAll(); - QJsonParseError jsonErr; - QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr); - if(jsonErr.error != QJsonParseError::NoError) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Error"), "JsonError "+jsonErr.errorString()+"\n"+data); - return; - } - if(json["result"].toString() != "true") { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Error"), data); - return; - } - waitingDlg->success(); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":3000"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QString err = parseReplyJson(reply); - if(! err.isEmpty()) { - gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" "+err); - return; - } - auto data = reply->readAll(); - QJsonParseError jsonErr; - QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr); - if(jsonErr.error != QJsonParseError::NoError) { - gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" JsonError "+jsonErr.errorString()+"\n"+data); - return; - } - if(json["result"].toString() != "true") { - gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" "+data); - return; - } - gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+QCoreApplication::translate("Def","Success")); - }); - } - } - }); - hBox->addWidget(btnBindTaxiIc); - hBox->addStretch(); - - vBox->addLayout(hBox); - - groupTopLevel = new QGroupBox(); - hBox = new QHBoxLayout(groupTopLevel); - - fdTopLevelHL = new QRadioButton(groupTopLevel); - fdTopLevelHL->setChecked(true); - hBox->addWidget(fdTopLevelHL); - - fdTopLevelLH = new QRadioButton(groupTopLevel); - hBox->addWidget(fdTopLevelLH); - - btnSetTopLevel = new QPushButton(groupTopLevel); - hBox->addWidget(btnSetTopLevel); - - btnGetTopLevel = new QPushButton(groupTopLevel); - hBox->addWidget(btnGetTopLevel); - - hBox->addStretch(); - - vBox->addWidget(groupTopLevel); - - groupBoxRotate = new QGroupBox(); - hBox = new QHBoxLayout(groupBoxRotate); - - radioButton0degrees = new QRadioButton(groupBoxRotate); - hBox->addWidget(radioButton0degrees); - - radioButton90degrees = new QRadioButton(groupBoxRotate); - hBox->addWidget(radioButton90degrees); - - radioButton180degrees = new QRadioButton(groupBoxRotate); - hBox->addWidget(radioButton180degrees); - - radioButton270degrees = new QRadioButton(groupBoxRotate); - hBox->addWidget(radioButton270degrees); - - hBox->addStretch(); - - vBox->addWidget(groupBoxRotate); - - groupBoxMinMaxBrightness = new QGroupBox(); - hBox = new QHBoxLayout(groupBoxMinMaxBrightness); - - lbMinBright = new QLabel(); - hBox->addWidget(lbMinBright); - - fdMinBright = new QLineEdit("1"); - fdMinBright->setMaximumWidth(50); - hBox->addWidget(fdMinBright); - - lbMinBrightTip = new QLabel(); - hBox->addWidget(lbMinBrightTip); - - btnMinBrightGet = new QPushButton(); - hBox->addWidget(btnMinBrightGet); - - btnMinBrightSet = new QPushButton(); - hBox->addWidget(btnMinBrightSet); - - label_3 = new QLabel(); - hBox->addWidget(label_3); - - lineEdit_4 = new QLineEdit("255"); - lineEdit_4->setMaximumWidth(50); - hBox->addWidget(lineEdit_4); - - label_5 = new QLabel(); - hBox->addWidget(label_5); - - pushButtonReadbackMaxBrightess = new QPushButton(); - hBox->addWidget(pushButtonReadbackMaxBrightess); - - pushButtonSendMaxBrightness = new QPushButton(); - hBox->addWidget(pushButtonSendMaxBrightness); - - hBox->addStretch(); - vBox->addWidget(groupBoxMinMaxBrightness); - - vBox->addSpacing(20); - - grpBoxHiddenSettings = new QGroupBox; - grpBoxHiddenSettings->setVisible(false); - { - auto vBox = new QVBoxLayout(grpBoxHiddenSettings); - vBox->setContentsMargins(6,6,6,6); - - hBox = new QHBoxLayout; - - btnSetBack = new QPushButton; - btnSetBack->setProperty("ssType", "progManageTool"); - connect(btnSetBack, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QColorDialog colorDlg(this); - colorDlg.setOption(QColorDialog::DontUseNativeDialog); - - if(colorDlg.exec() != QColorDialog::Accepted) return; - QColor color = colorDlg.selectedColor(); - if(! color.isValid()) return; - QJsonObject json; - json.insert("_id", "SetWallpaper"); - json.insert("_type", "SetWallpaper"); - json.insert("rgb", color.name()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Setting Wallpaper")+" ..."); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("Set Wallpaper")) - } - } - }); - hBox->addWidget(btnSetBack); - - btnSysUpd = new QPushButton; - btnSysUpd->setProperty("ssType", "progManageTool"); - connect(btnSysUpd, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SystemUpdate"); - json.insert("_type", "SystemUpdate"); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("System Updating")+" ..."); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("System Update")) - } - } - }); - hBox->addWidget(btnSysUpd); - - hBox->addSpacing(20); - - btnPlayerBackSet = new QPushButton; - btnPlayerBackSet->setProperty("ssType", "progManageTool"); - connect(btnPlayerBackSet, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QString file = QFileDialog::getOpenFileName(gMainWin, tr("Select File"), gFileHome, EPhoto::filters()); - if(file.isEmpty()) return; - QFileInfo info(file); - if(! info.isFile()) return; - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Setting player background")+" ..."); - waitingDlg->show(); - auto thread = new PlayerBackSendThread(file, gSelCards->at(0)->m_strCardIp); - connect(thread, &PlayerBackSendThread::emErr, this, [waitingDlg](QString err) { - if(err.isEmpty()) waitingDlg->success(); - else { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Error"), err); - } - }); - thread->start(); - } else { - foreach(auto card, *gSelCards) { - auto thread = new PlayerBackSendThread(file, card->m_strCardIp); - connect(thread, &PlayerBackSendThread::emErr, this, [card](QString err) { - gFdResInfo->append(card->m_strCardId+" "+tr("Set player background")+" "+(err.isEmpty() ? tr("Success") : err)); - }); - thread->start(); - } - } - }); - hBox->addWidget(btnPlayerBackSet); - - btnPlayerBackClear = new QPushButton; - btnPlayerBackClear->setProperty("ssType", "progManageTool"); - connect(btnPlayerBackClear, &QPushButton::clicked, this, [this] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Clearing player background")+" ..."); - waitingDlg->show(); - auto card = gSelCards->at(0); - auto tcp = new QTcpSocket(); - auto timer = new QTimer(tcp); - timer->setSingleShot(true); - connect(timer, &QTimer::timeout, tcp, [tcp, waitingDlg] { - tcp->close(); - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear player background")+" "+tr("Timeout")); - }); - connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater); - connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { - timer->stop(); - tcp->write("{\"_type\":\"DelBackImg\",\"_id\":\"DelBackImg\",\"zVer\":\"xixun1\"}"); - timer->start(10000); - }); - connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, waitingDlg] { - timer->stop(); - QByteArray resp = tcp->readAll(); - tcp->close(); - QJsonParseError parseErr; - QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); - if(parseErr.error != QJsonParseError::NoError) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), parseErr.errorString()); - } else if(! json["success"].toBool()) { - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear player background")+" "+tr("Failed")); - } else waitingDlg->success(); - }); - connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, waitingDlg](QAbstractSocket::SocketError err) { - timer->stop(); - tcp->close(); - waitingDlg->close(); - QMessageBox::critical(gMainWin, tr("Tip"), QString(socketErrKey(err))+" ("+QString::number(err)+") "+tcp->errorString()); - }); - tcp->connectToHost(card->m_strCardIp, 3333); - timer->start(10000); - } else { - foreach(auto card, *gSelCards) { - auto tcp = new QTcpSocket(); - auto timer = new QTimer(tcp); - timer->setSingleShot(true); - connect(timer, &QTimer::timeout, tcp, [tcp, card] { - tcp->close(); - gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+tr("Timeout")); - }); - connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater); - connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] { - timer->stop(); - tcp->write("{\"_type\":\"DelBackImg\",\"_id\":\"DelBackImg\",\"zVer\":\"xixun1\"}"); - timer->start(10000); - }); - connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, card] { - timer->stop(); - QByteArray resp = tcp->readAll(); - tcp->close(); - QJsonParseError parseErr; - QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr); - if(parseErr.error != QJsonParseError::NoError) gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+parseErr.errorString()); - else if(! json["success"].toBool()) gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+tr("Failed")); - else gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+tr("Success")); - }); - connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, card](QAbstractSocket::SocketError err) { - timer->stop(); - tcp->close(); - gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+QMetaEnum::fromType().valueToKey(err)+" ("+QString::number(err)+") "+tcp->errorString()); - }); - tcp->connectToHost(card->m_strCardIp, 3333); - timer->start(10000); - } - } - }); - hBox->addWidget(btnPlayerBackClear); - - hBox->addStretch(); - vBox->addLayout(hBox); - - lbBaudCfg = new QLabel; - vBox->addWidget(lbBaudCfg); - - hBox = new QHBoxLayout; - - lbBaudModel = new QLabel; - hBox->addWidget(lbBaudModel); - - auto fdBaudDevMod = new QComboBox; - fdBaudDevMod->addItems({ - "M5x/M6x", - "M7x/Y7x", - "E2x/Y6x", - "L20" - }); - hBox->addWidget(fdBaudDevMod); - - lbUart = new QLabel; - hBox->addWidget(lbUart); - - auto fdUart = new QComboBox; - fdUart->setEditable(true); - fdUart->setMinimumWidth(140); - fdUart->setSizeAdjustPolicy(QComboBox::AdjustToContents); - fdUart->addItems({ - "/dev/ttyS3", - "/dev/ttyS4", - "/dev/ttyS5" - }); - hBox->addWidget(fdUart); - - connect(fdBaudDevMod, &QComboBox::currentTextChanged, fdUart, [fdUart](const QString &text) { - fdUart->clear(); - if(text.startsWith("M5x")) fdUart->addItems({ - "/dev/ttyS3", - "/dev/ttyS4", - "/dev/ttyS5" - }); - else if(text.startsWith("M7x")) fdUart->addItem("/dev/ttyS4"); - else if(text.startsWith("E2x")) fdUart->addItems({ - "/dev/ttysWK0", - "/dev/ttysWK1", - "/dev/ttysWK2", - "/dev/ttysWK3", - "/dev/tty232", - "/dev/tty485", - "/dev/ttyTTL" - }); - else if(text.startsWith("L20")) fdUart->addItems({ - "/dev/ttyS0", - "/dev/ttyS1", - "/dev/ttyS4" - }); - }); - - lbBaud = new QLabel; - hBox->addWidget(lbBaud); - - auto fdBaud = new QLineEdit; - fdBaud->setMaximumWidth(70); - hBox->addWidget(fdBaud); - - btnBaudSet = new QPushButton; - btnBaudSet->setProperty("ssType", "progManageTool"); - connect(btnBaudSet, &QPushButton::clicked, this, [this, fdUart, fdBaud] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "SetBaudRateByCardType"); - json.insert("_type", "SetBaudRateByCardType"); - json.insert("uartName", fdUart->currentText()); - json.insert("baud", fdBaud->text().toInt()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Setting Baud Rate")+" ..."); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] { - Def_CtrlSetReqAfter - }); - } else { - foreach(auto card, *gSelCards) { - Def_CtrlSetMulti(tr("Set Baud Rate")) - } - } - }); - hBox->addWidget(btnBaudSet); - - btnBaudGet = new QPushButton; - btnBaudGet->setProperty("ssType", "progManageTool"); - connect(btnBaudGet, &QPushButton::clicked, this, [this, fdUart, fdBaud] { - if(gSelCards->isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController")); - return; - } - QJsonObject json; - json.insert("_id", "GetBaudRateByCardType"); - json.insert("_type", "GetBaudRateByCardType"); - json.insert("uartName", fdUart->currentText()); - if(gSelCards->count() == 1) { - auto waitingDlg = new WaitingDlg(this, tr("Getting Baud Rate")+" ..."); - Def_CtrlReqPre - connect(reply, &QNetworkReply::finished, this, [reply, fdBaud, waitingDlg] { - Def_CtrlSingleGetReply - waitingDlg->success(); - fdBaud->setText(QString::number(json["baud"].toInt())); - }); - } else { - foreach(auto card, *gSelCards) { - auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact)); - connect(reply, &QNetworkReply::finished, this, [reply, card] { - QJsonDocument json; - QString err = checkReplyForJson(reply, &json); - gFdResInfo->append(card->m_strCardId+" "+tr("Get Baud Rate")+" "+(err.isEmpty()?QString::number(json["baud"].toInt()):err)); - }); - } - } - }); - hBox->addWidget(btnBaudGet); - - hBox->addStretch(); - vBox->addLayout(hBox); - - - fdIsOpenADB = new QCheckBox; - vBox->addWidget(fdIsOpenADB); - - hBox = new QHBoxLayout(); - - lbCustomJson = new QLabel; - hBox->addWidget(lbCustomJson); - - hBox->addSpacing(40); - - btnSendCustomJson = new QPushButton; - hBox->addWidget(btnSendCustomJson); - - hBox->addStretch(); - vBox->addLayout(hBox); - - fdCustomJson = new QTextEdit; - fdCustomJson->setMinimumHeight(120); - vBox->addWidget(fdCustomJson); - } - vBox->addWidget(grpBoxHiddenSettings); - vBox->addStretch(); - - pushButtonSetREaltimeServer->setProperty("ssType", "progManageTool"); - pushButtonClearRealtimerAddress->setProperty("ssType", "progManageTool"); - pushButtonRestart->setProperty("ssType", "progManageTool"); - fdUnload->setProperty("ssType", "progManageTool"); - btnRunningCheck->setProperty("ssType", "progManageTool"); - pushButtonFpgaUpgrade->setProperty("ssType", "progManageTool"); - pushButtonFpgaVerCheck->setProperty("ssType", "progManageTool"); - pushButtonSyncFpgaVer->setProperty("ssType", "progManageTool"); - btnMinBrightGet->setProperty("ssType", "progManageTool"); - pushButtonReadbackMaxBrightess->setProperty("ssType", "progManageTool"); - btnMinBrightSet->setProperty("ssType", "progManageTool"); - pushButtonSendMaxBrightness->setProperty("ssType", "progManageTool"); - btnM80Set->setProperty("ssType", "progManageTool"); - btnM80Refresh->setProperty("ssType", "progManageTool"); - btnM80Restore->setProperty("ssType", "progManageTool"); - btnGetTopLevel->setProperty("ssType", "progManageTool"); - btnSetTopLevel->setProperty("ssType", "progManageTool"); - btnSendCustomJson->setProperty("ssType", "progManageTool"); - - groupBoxRotate->setVisible(false); - groupBoxMinMaxBrightness->setVisible(false); - groupTopLevel->setVisible(false); - - - connect(pushButtonSetREaltimeServer,SIGNAL(clicked()),this,SLOT(OnSetRealtimeServer())); - connect(pushButtonClearRealtimerAddress,SIGNAL(clicked()),this,SLOT(OnClearRealtimeServer())); - - connect(pushButtonRestart, SIGNAL(clicked()),this,SLOT(OnRestart())); - - connect(pushButtonFpgaUpgrade,SIGNAL(clicked()),this,SLOT(OnFpgaUpgrade())); - connect(pushButtonFpgaVerCheck,SIGNAL(clicked()),this,SLOT(OnFpgaVerCheck())); - connect(pushButtonSyncFpgaVer,SIGNAL(clicked()),this,SLOT(OnSyncFpgaVer())); - - connect(radioButton0degrees,SIGNAL(clicked()),this,SLOT(On0degrees())); - connect(radioButton90degrees,SIGNAL(clicked()),this,SLOT(On90degrees())); - connect(radioButton180degrees,SIGNAL(clicked()),this,SLOT(On180degrees())); - connect(radioButton270degrees,SIGNAL(clicked()),this,SLOT(On270degrees())); - - connect(btnMinBrightSet,SIGNAL(clicked()),this,SLOT(OnSendMinBrightness())); - connect(pushButtonSendMaxBrightness,SIGNAL(clicked()),this,SLOT(OnSendMaxBrightness())); - connect(btnMinBrightGet,SIGNAL(clicked()),this,SLOT(OnGetMinBrightness())); - - connect(pushButtonReadbackMaxBrightess,SIGNAL(clicked()),this,SLOT(OnGetMaxBrightness())); - connect(btnSendCustomJson,SIGNAL(clicked()),this,SLOT(OnSendCustomJson())); - - pHpptClient = new HpptClient(this); - connect(pHpptClient, &HpptClient::httpPostRspReady, this, &CtrlAdvancedPanel::OnProHttpResponse); - pHpptClientAll = new HpptClient(this); - connect(pHpptClientAll,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this, SLOT(OnProHttpResponseAll(QString , QString , QByteArray))); - m_pGetAskTimer = new QTimer(this); - connect(this, SIGNAL(sigSend(QJsonObject &,QString)), parent->parent(), SLOT(OnControlSendJson(QJsonObject &,QString))); - - connect(pHpptClient,SIGNAL(httpGetRspReady(QString , QByteArray )),this,SLOT(OnProHttpGetResponse(QString , QByteArray))); - - connect(btnM80Set,SIGNAL(clicked()),this,SLOT(OnM80Set())); - connect(btnM80Refresh,SIGNAL(clicked()),this,SLOT(OnM80Refresh())); - connect(btnM80Restore,SIGNAL(clicked()),this,SLOT(OnM80Restore())); - connect(btnSetTopLevel,SIGNAL(clicked()),this,SLOT(OnSetTaxiTopScreen())); - connect(btnGetTopLevel,SIGNAL(clicked()),this,SLOT(OnReadbackTaxiTopScreen())); - connect(fdIsOpenADB,SIGNAL(clicked()),this,SLOT(OnOpenAdb())); - - connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] { - if(isVisible()) init(); - }); - transUi(); -} - -CtrlAdvancedPanel::~CtrlAdvancedPanel(){ - if(pHpptClient != nullptr){ - delete pHpptClient; - pHpptClient=nullptr; - } - if(pHpptClientAll != nullptr){ - delete pHpptClientAll; - pHpptClientAll=nullptr; - } -} -void CtrlAdvancedPanel::showEvent(QShowEvent *event) { - QWidget::showEvent(event); - init(); -} -void CtrlAdvancedPanel::init() { - m_pLedCard = gSelCards->at(0); - if(! m_passwordOk) { - hide(); - PasswordInChDlg dlg(gMainWin); - connect(dlg.btnBox, &QDialogButtonBox::accepted, &dlg, [&dlg]() { - QString passRaw = QSettings().value("advUiPs").toString(); - QString password = passRaw.isEmpty() ? "888" : QTextCodec::codecForName("GBK")->toUnicode(QByteArray::fromBase64(passRaw.toLocal8Bit())); - if(dlg.fdPassword->text() == password) dlg.accept(); - else QMessageBox::critical(&dlg, tr("Tip"),tr("Password is error")); - }); - if(dlg.exec()==QDialog::Accepted) { - if(m_pLedlist->count()==1) btnScreenSet->setEnabled(true); - m_passwordOk = true; - show(); - } else return; - } - - bool isSingle = gSelCards->count()==1; - btnApkUpgrade->setEnabled(isSingle); - btnApkCheck->setEnabled(isSingle); - pushButtonFpgaUpgrade->setEnabled(isSingle); - pushButtonFpgaVerCheck->setEnabled(isSingle); - pushButtonSyncFpgaVer->setEnabled(isSingle); - pushButtonRestart->setEnabled(isSingle); - btnGetLog->setEnabled(isSingle); - if(isSingle) groupM80->setVisible(m_pLedCard->m_strCardId.startsWith("M8", Qt::CaseInsensitive)); - else groupM80->setVisible(true); - - if(! isSingle) return; - m_strUrl = "http://"+m_pLedCard->m_strCardIp+":2016/settings"; - - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetScreenSize"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json); - - QJsonObject json1; - json1.insert("_id", getRandomString(10)); - json1.insert("_type", "GetOnlineAddr"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json1); - - QJsonObject json2; - json2.insert("_id", getRandomString(10)); - json2.insert("_type", "GetRealtimeServer"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json2); - - QJsonObject json3; - json3.insert("_id", getRandomString(10)); - json3.insert("_type", "GetCardAlias"); - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json3); - - if(m_pLedCard->m_strCardId.startsWith("M8", Qt::CaseInsensitive)) { - QJsonObject json3; - json3.insert("_id", getRandomString(10)); - json3.insert("_type", "GetAllScreenSizeM80"); - qDebug()<<"GetAllScreenSizeM80 send"; - HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json3); - } -} -void CtrlAdvancedPanel::changeEvent(QEvent *event) { - QWidget::changeEvent(event); - if(event->type() == QEvent::LanguageChange) transUi(); -} -void CtrlAdvancedPanel::transUi() { - btnBindTaxiIc->setText(tr("Binding *.ic account indentity voucher")); - btnGetTopLevel->setText(tr("Readback")); - btnLedSet3->setText(tr("Start LedSet3.0 configure LED module")); - btnLedSet4->setText(tr("Start LedSet4")); - btnM80Refresh->setText(tr("Refresh")); - btnM80Restore->setText(tr("Restore to default")); - btnM80Set->setText(tr("Set")); - btnAliasSet->setText(tr("Set")); - btnScreenSet->setText(tr("Set")); - btnSetTopLevel->setText(tr("Set")); - fdScreenHeight->setPlaceholderText(tr("Height")); - fdScreenWidth->setPlaceholderText(tr("Width")); - fdTopLevelHL->setText(tr("Service:High Out of service:Low")); - fdTopLevelLH->setText(tr("Service:Low Out of service:High")); - groupBoxRotate->setTitle(tr("Rotate")); - - grpBoxHiddenSettings->setTitle(tr("Hidden Settings")+" ("+tr("Click right button to hide")+")"); - btnSysUpd->setText(tr("System Update")); - lbBaudCfg->setText(tr("Baud Config")); - lbBaudModel->setText(tr("Model")); - lbUart->setText(tr("Uart")); - lbBaud->setText(tr("Baud")); - btnBaudSet->setText(tr("Set")); - btnBaudGet->setText(tr("Get")); - fdIsOpenADB->setText(tr("Open ADB")); - lbCustomJson->setText(tr("Post Custom JSON")); - btnSendCustomJson->setText(tr("Send")); - - groupM80->setTitle(tr("M80 configuration")); - groupTopLevel->setTitle(tr("Taxi top screen configuration")); - label->setText(tr("Realtimer Server Address:")); - lbTitle->setText(tr("Advanced parameters")); - lbCompanyId->setText(tr("Compant ID:")); - labelWebServer->setText(tr("Web Server Address:")); - lbMinBright->setText(tr("Min brightness")); - label_3->setText(tr("Max brightness ")); - lbMinBrightTip->setText(tr("(min:1)")); - label_5->setText(tr("(max:255)")); - lbAlias->setText(tr("Alias")); - lbScreenHeight->setText(tr("Height")); - lbScreenWidth->setText(tr("Screen Width(pixel)")); - fdCompanyId->setPlaceholderText(tr("Compant ID")); - btnApkCheck->setText(tr("Check Apk")); - btnApkUpgrade->setText(tr("Apk upgrade")); - btnGetLog->setText(tr("Check Log")); - btnSetBack->setText(tr("Set Wallpaper")); - btnClearProg->setText(tr("Clear Program")); - btnPlayerBackSet->setText(tr("Set player background")); - btnPlayerBackClear->setText(tr("Clear player background")); - - pushButtonClearRealtimerAddress->setText(tr("Clear")); - pushButtonFpgaUpgrade->setText(tr("FPGA Upgrade")); - pushButtonFpgaVerCheck->setText(tr("FPGA version check")); - btnMinBrightGet->setText(tr("Readback")); - pushButtonReadbackMaxBrightess->setText(tr("Readback")); - pushButtonRestart->setText(tr("Restart led controller system")); - btnRunningCheck->setText(tr("Running check")); - pushButtonSendMaxBrightness->setText(tr("Send")); - btnMinBrightSet->setText(tr("Send")); - pushButtonSetREaltimeServer->setText(tr("Set")); - btnWebServerSet->setText(tr("Set")); - pushButtonSyncFpgaVer->setText(tr("Sync FPGA version")); - fdUnload->setText(tr("Uninstall")); - radioButton0degrees->setText(tr("0 degrees")); - radioButton180degrees->setText(tr("180 degrees")); - radioButton270degrees->setText(tr("270 degrees")); - radioButton90degrees->setText(tr("90 degrees")); -} - -void CtrlAdvancedPanel::OnClearRealtimeServer(){ - CHECK_CARD_SELECTED - comboBox_realtimeServer->clearEditText(); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetRealtimeServer"); - json.insert("server", ""); - MACRO_DEFINE_TIPDLG_FUCN(tr("ClearRealtimeServer"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnSetRealtimeServer(){ - CHECK_CARD_SELECTED - if(comboBox_realtimeServer->currentText().isEmpty()) { - QMessageBox::information(gMainWin, tr("Tip"),tr("InputRealTimeAddressTip")); - comboBox_realtimeServer->setFocus(); - return; - } - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetRealtimeServer"); - json.insert("server", comboBox_realtimeServer->currentText()); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetRealtimeServer"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnStartConfigLedScreenSoft() { - QString strLedSetFile = QApplication::applicationDirPath()+"/LedSet/LedSet3.0.exe"; - QFileInfo cc22(strLedSetFile); - if(cc22.exists()) { - QProcess::startDetached(strLedSetFile,QStringList()); - return; - } - QSettings reg("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\sysolution\\LedSet3.0", QSettings::NativeFormat); - QString strLedsetPath = reg.value("Program_path").toString(); - if(!strLedsetPath.isEmpty()) { - QFileInfo cc(strLedsetPath); - if(cc.exists()) QProcess::startDetached(strLedsetPath,QStringList()); - else { - auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath); - if(res == QMessageBox::Yes) { - UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this); - pDlg->exec(); - } - } - return; - } - QSettings reg1("HKEY_LOCAL_MACHINE\\SOFTWARE\\sysolution\\LedSet3.0", QSettings::NativeFormat); - strLedsetPath = reg1.value("Program_path").toString(); - QFileInfo cc(strLedsetPath); - if(!strLedsetPath.isEmpty()) { - if(cc.exists()) QProcess::startDetached(strLedsetPath,QStringList()); - else { - QString str1="C:/Program Files/sysolution/LedSet3.0/LedSet3.0.exe"; - QFileInfo cc1(str1); - if(cc1.exists()) QProcess::startDetached(str1,QStringList()); - else { - QString str2="C:/Program Files (x86)/sysolution/LedSet3.0/LedSet3.0.exe"; - QFileInfo cc2(str1); - if(cc2.exists()) QProcess::startDetached(str2,QStringList()); - else { - auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath); - if(res == QMessageBox::Yes) { - UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this); - pDlg->exec(); - } - } - } - } - } else { - QString str1="C:/Program Files/sysolution/LedSet3.0/LedSet3.0.exe"; - QFileInfo cc1(str1); - if(cc1.exists()) QProcess::startDetached(str1,QStringList()); - else { - QString str2="C:/Program Files (x86)/sysolution/LedSet3.0/LedSet3.0.exe"; - QFileInfo cc2(str1); - if(cc2.exists())QProcess::startDetached(str2,QStringList()); - else { - auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath); - if(res == QMessageBox::Yes) { - UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this); - pDlg->exec(); - } - } - } - } -} -void CtrlAdvancedPanel::OnRestart(){ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "RestartAndroid"); - MACRO_DEFINE_TIPDLG_FUCN(tr("RestartAndroid"),tr("Success"),tr("failed")) -} - -//获取到httpPost的应答,如果参数变化需要出发修改控件item的内容 -void CtrlAdvancedPanel::OnProHttpResponse(QString url, QString, QByteArray data){ - if(url == m_strUrl) { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(parseJsonErr.error != QJsonParseError::NoError){ - if(data.size()!=0) qDebug()<setCurrentText(jsonObject["server"].toString()); - fdCompanyId->setText(jsonObject["companuID"].toString()); - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType == "GetRealtimeServer"){ - comboBox_realtimeServer->setCurrentText(jsonObject["server"].toString()); - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType == "GetCardAlias") - { - fdAlias->setText(QString::fromUtf8(QByteArray::fromBase64(jsonObject["alias"].toString().toLatin1()))); - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType =="UpgradeSoftware") - { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - QMessageBox::information(gMainWin, tr("Tip"),tr("UpgradeSoftware")+tr("Success")); - } - else if(strType == "SynchronousHardwareVersion"){ - - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - QMessageBox::information(gMainWin, tr("Tip"),tr("SynchronousHardwareVersion")+" "+tr("Success")); - } - else if(strType == "DelPrograms") - { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - else if(strType == "SetScreenRotation") - { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - else if(strType == "SetMinBrightness") - { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType == "SetMaxBrightness") - { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType == "GetMinBrightness") - { - - fdMinBright->setText(QString::number(jsonObject["brightness"].toInt())); - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType == "GetMaxBrightness") - { - lineEdit_4->setText(QString::number(jsonObject["brightness"].toInt())); - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if(strType == "GetSpecialResolution") - { - - QString strCurDisplayResolution = jsonObject["displayResolution"].toString(); - fdM80->setCurrentText(strCurDisplayResolution); - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - - else if(strType == "CheckHardwareVersions"){ - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - QString strtempVer=""; - int itempVerCount=0; - foreach(QJsonValue value, jsonObject["versions"].toArray()) { - QString strtempIcount=QString::number(itempVerCount); - strtempVer += "[card"+strtempIcount+"]:"+value.toString()+"\r\n"; - itempVerCount++; - - } - QMessageBox::information(gMainWin, tr("FPGA Version"),strtempVer); - } - else if (strType == "SetHighForBusy") { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - - } - else if(strType == "OpenAdb") - { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - else if (strType == "GetStateForBusy") { - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - if(jsonObject["result"].toInt()==0) - { - fdTopLevelLH->setChecked(true); - fdTopLevelHL->setChecked(false); - } - else { - fdTopLevelLH->setChecked(false); - fdTopLevelHL->setChecked(true); - - } - } - }else { - if(strType =="UpgradeSoftware"){ - qDebug()<<"slotUploadFinished failed ack"; - MACRO_ASKTIME_STOP - MACRO_POSTING_DLG_UNLOCK - } - } - } - if(url == m_strStartUrl) - { - QJsonParseError parseJsonErr; - QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr); - if(!(parseJsonErr.error == QJsonParseError::NoError)) - { - if(data.size()==0) - qDebug()<<"json is empty"; - else - qDebug()<m_strCardId +"---------"+ strType; - if(strType == "GetScreenSize") - { - fdScreenWidth->setText(QString::number(jsonObject["width"].toInt())); - fdScreenHeight->setText(QString::number(jsonObject["height"].toInt())); - } - - else if(strType == "GetCardAlias") - { - fdAlias->setText(QString::fromUtf8(QByteArray::fromBase64(jsonObject["alias"].toString().toLatin1()))); - - } - else if(strType == "GetOnlineAddr") - { - fdWebServerAddr->setCurrentText(jsonObject["server"].toString()); - fdCompanyId->setText(jsonObject["companuID"].toString()); - } - else if(strType == "GetRealtimeServer") - { - qDebug()<<"GetRealtimeServer ack"<setCurrentText(jsonObject["server"].toString()); - } - else if(strType == "GetAllScreenSizeM80") - { - mM80Map=jsonObject["result"].toObject(); - QStringList strlist=mM80Map.keys(); - fdM80->clear(); - fdM80->addItems(strlist); - comboBox_realtimeServer->setCurrentText(jsonObject["server"].toString()); - } - - } - - } -} -void CtrlAdvancedPanel::OnFpgaUpgrade() -{ - QString url="http://"+m_pLedCard->m_strCardIp+":2016/upload?type=hardware"; - QFileDialog dlg; - m_strUpgradeFpgaFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("apk package (*.rpd)")); - QFileInfo file1(m_strUpgradeFpgaFile); - QFile file(m_strUpgradeFpgaFile); - QMap params_send; //上传的普通参数 在本程序中 需要上传一个普通参数为"username" - params_send.insert("username","10005"); - UpLoadForm(url, params_send, file1.fileName(), &file, 1); -} -void CtrlAdvancedPanel::OnFpgaVerCheck() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "CheckHardwareVersions"); - MACRO_DEFINE_TIPDLG_FUCN(tr("CheckHardwareVersions"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnSyncFpgaVer() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SynchronousHardwareVersion"); - MACRO_DEFINE_TIPDLG_FUCN(tr("SynchronousHardwareVersion"),tr("Check Screen untile fpga update finished"),tr("failed")) -} -void CtrlAdvancedPanel::slotUploadFpgaFinished() -{ - QFileInfo file(m_strUpgradeApkFile); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SynchronousHardwareVersion"); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - emit sigSetTipTextContent(tr("SynchronousHardwareVersion")); - qDebug()<<"slotUploadFinished"; - -} -void CtrlAdvancedPanel::slotUploadFinished() -{ - QFileInfo file(m_strUpgradeApkFile); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "UpgradeSoftware"); - json.insert("fileName", file.fileName()); - json.insert("isCustom", true); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - emit sigSetTipTextContent(tr("install start...")); - MACRO_ASKTIME_STOP - m_pGetAskTimer->start(50000); - - qDebug()<<"slotUploadFinished"; - -} -void CtrlAdvancedPanel::slotUploadProgress(qint64 A,qint64 B) -{ - if(B!=0) - { - QString strbaifenbi=tr("Uploadding")+":"+QString("%1%").arg(A*100/B); - emit sigSetTipTextContent(strbaifenbi); - m_pGetAskTimer->stop(); - m_pGetAskTimer->start(30000); - } -} - -void CtrlAdvancedPanel::UpLoadForm(QString Path, QMap params, QString fileName, QFile *uploadFile, int iType) { - auto boundary = QUuid::createUuid().toByteArray(); - QByteArray data; - for(QMap::iterator t=params.begin(); t!=params.end(); t++) { - data.append("--").append(boundary).append("\r\n"); - data.append("Content-Disposition: form-data;name=\"").append(t.key().toUtf8()).append("\"\r\n"); - data.append("\r\n"); - data.append(t.value().toUtf8()).append("\r\n"); - } - //上传文件的头部 - data.append("--").append(boundary).append("\r\n"); - data.append("Content-Disposition: form-data;name=\"").append(fileName.toUtf8()).append("\";filename=\"").append(fileName.toUtf8()).append("\"\r\n"); - data.append("\r\n"); - //上传文件内容 - if(!uploadFile->open(QIODevice::ReadOnly)) return; - data.append(uploadFile->readAll()); - uploadFile->close(); - data.append("\r\n"); - data.append("--").append(boundary).append("\r\n"); - - //编辑HTTP头部 - QNetworkRequest request = netReq(Path, 15000, "multipart/form-data;boundary="+boundary); - request.setHeader(QNetworkRequest::ContentLengthHeader, data.length()); - //执行post请求 - if(m_PostingDlg==nullptr) - { - m_PostingDlg = new LoEmptyDialog(); - connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg())); - connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock())); - m_PostingDlg->lock(tr("UpgradeSoftware"),tr("Success"),tr("UpgradeSoftware")+tr("failed")); - m_pGetAskTimer->start(60000); - QNetworkReply * m_netReply = Tools::netManager().post(request, data); - connect(m_netReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64))); - connect(this, SIGNAL(sigSetTipTextContent ( QString )), m_PostingDlg, SLOT( SetTipTextContent(QString))); - if(iType==0)//apk - { - connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFinished())); - - } - else if(iType==1)//fpga.rpd - { - connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFpgaFinished())); - - } - m_PostingDlg->exec(); - } -} -void messageHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) { - auto cur = QDateTime::currentDateTime(); - QFile file("D:/LedOK-advanced-"+cur.toString("yy-MM-dd")+".log"); - file.open(QIODevice::WriteOnly | QIODevice::Append); - file.write(cur.toString("yy-MM-dd hh:mm:ss ").toUtf8()); - if(type==QtDebugMsg) file.write(" Debug: "); - else if(type==QtWarningMsg) file.write(" Warning: "); - else if(type==QtCriticalMsg)file.write("Critical: "); - else if(type==QtFatalMsg) file.write(" Fatal: "); - else if(type==QtInfoMsg) file.write(" Info: "); - else if(type==QtSystemMsg) file.write(" System: "); - file.write(msg.toUtf8()); - file.close(); -} -void CtrlAdvancedPanel::keyReleaseEvent(QKeyEvent *event) { - auto key = event->key(); - if(key == Qt::Key_F3) m_lockFlag = false; - else if(key == Qt::Key_F5) groupBoxRotate->setVisible(! groupBoxRotate->isVisible()); - else if(key == Qt::Key_F6) groupBoxMinMaxBrightness->setVisible(! groupBoxMinMaxBrightness->isVisible()); - else if(key == Qt::Key_F8) groupTopLevel->setVisible(! groupTopLevel->isVisible()); - else if(key == Qt::Key_F12) qInstallMessageHandler(messageHandler); - QWidget::keyPressEvent(event); -} -void CtrlAdvancedPanel::mouseReleaseEvent(QMouseEvent *event){ - if(event->button()==Qt::RightButton) grpBoxHiddenSettings->setVisible(! grpBoxHiddenSettings->isVisible()); -} -void CtrlAdvancedPanel::On0degrees() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetScreenRotation"); - json.insert("rotation", 0); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed")) -} - -void CtrlAdvancedPanel::On90degrees() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetScreenRotation"); - json.insert("rotation", 1); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::On180degrees() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetScreenRotation"); - json.insert("rotation", 2); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::On270degrees() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetScreenRotation"); - json.insert("rotation", 3); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnSendMinBrightness() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetMinBrightness"); - json.insert("brightness", fdMinBright->text().toInt()); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetMinBrightness"),tr("Success"),tr("failed")) - - -} -void CtrlAdvancedPanel::OnSendMaxBrightness() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetMaxBrightness"); - json.insert("brightness", lineEdit_4->text().toInt()); - MACRO_DEFINE_TIPDLG_FUCN(tr("SetMaxBrightness"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnGetMinBrightness() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetMinBrightness"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetMinBrightness"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnGetMaxBrightness() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetMaxBrightness"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetMaxBrightness"),tr("Success"),tr("failed")) -} - -void CtrlAdvancedPanel::OnM80Set() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetSpecialResolution"); - json.insert("displayResolution",fdM80->currentText()), //显示分辨率 - json.insert("totalResolution",mM80Map[fdM80->currentText()].toString() ); //显示分辨率 - MACRO_DEFINE_TIPDLG_FUCN(tr("SetSpecialResolution"),tr("Success"),tr("failed")) -} - -void CtrlAdvancedPanel::OnM80Refresh() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetSpecialResolution"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetSpecialResolution"),tr("Success"),tr("failed")) -} - -void CtrlAdvancedPanel::OnM80Restore() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "CleanDisplayScreenSize"); - MACRO_DEFINE_TIPDLG_FUCN(tr("CleanDisplayScreenSize"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnSetTaxiTopScreen() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SetHighForBusy"); - if(fdTopLevelLH->isChecked()) - json.insert("busyState", 0); - else if(fdTopLevelHL->isChecked()) - json.insert("busyState", 1); - else { - json.insert("busyState", 1); - } - - MACRO_DEFINE_TIPDLG_FUCN(tr("SetHighForBusy"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::OnReadbackTaxiTopScreen() -{ - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "GetStateForBusy"); - MACRO_DEFINE_TIPDLG_FUCN(tr("GetStateForBusy"),tr("Success"),tr("failed")) -} - -void CtrlAdvancedPanel::OnOpenAdb() -{ - - CHECK_CARD_SELECTED - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "OpenAdb"); - if(fdIsOpenADB->isChecked()) - { - json.insert("open", true); - } - else { - json.insert("open", false); - } - MACRO_DEFINE_TIPDLG_FUCN(tr("OpenAdb"),tr("Success"),tr("failed")) -} -void CtrlAdvancedPanel::DeletePostingDlg() -{ - if(m_PostingDlg!=nullptr) - { - delete m_PostingDlg; - m_PostingDlg=nullptr; - } -} -void CtrlAdvancedPanel::OnSendCustomJson(){//ok - - CHECK_CARD_SELECTED - m_strStartUrl="http://"+m_pLedCard->m_strCardIp+":3000"; - - QJsonObject json; - - QJsonParseError l_err; - QJsonDocument l_doc = QJsonDocument::fromJson(fdCustomJson->toPlainText().toUtf8(), &l_err); - if (l_err.error == QJsonParseError::NoError) - { - if (l_doc.isObject()) - { - json = l_doc.object(); - } - } - - if(json.count()<=0) - { - QMessageBox::information(gMainWin, tr("Tip"),tr("Json format is error!")); - return; - } - if(m_pLedlist==nullptr) - return; - if(m_pLedlist->count()<=1) - { - if(m_pLedCard!=nullptr) - { - HttpPostByTypeJsonObject(pHpptClient,m_strStartUrl,json); - if(m_PostingDlg==nullptr) - { - m_PostingDlg = new LoEmptyDialog(this); - connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg())); - connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock())); - m_PostingDlg->lock(tr("AliIotSetting"),tr("Success"),tr("failed")); - m_pGetAskTimer->start(5000); - m_PostingDlg->exec(); - - } - } - } - else { - emit sigSend(json,tr("AliIotSetting")); - } -} - -PlayerBackSendThread::PlayerBackSendThread(const QString &file, const QString &ip) : file(file), ip(ip) { - connect(this, &QThread::finished, this, &QThread::deleteLater); -} -void PlayerBackSendThread::run() { - TcpSocket tcp; - tcp.connectToHost(ip, 3333); - if(! tcp.waitForConnected()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForConnected"); - tcp.close(); - return; - } - QFileInfo info(file); - auto baseName = info.baseName(); - auto remain = info.size(); - - auto req = QJsonObject(); - req.insert("_type", "proStart"); - req.insert("proName", "program"); - req.insert("proSize", remain); - req.insert("zVer","xixun1"); - auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proStart'"); - tcp.close(); - return; - } - req = QJsonObject(); - req.insert("_type", "imgFileStart"); - req.insert("id", baseName); - req.insert("size", remain); - req.insert("zVer","xixun1"); - resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'imgFileStart'"); - tcp.close(); - return; - } - auto file = new QFile(info.filePath()); - if(! file->open(QFile::ReadOnly)) { - emit emErr(tr("Open file failed")+" "+file->errorString()); - tcp.close(); - return; - } - while(remain > 0) { - auto readed = file->read(qMin(4096LL, remain)); - if(readed.isEmpty()) { - emit emErr(tr("Read file failed")+" "+file->errorString()); - tcp.close(); - file->close(); - return; - } - resNum = tcp.write(readed); - if(resNum == -1) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write file: "+file->fileName()); - tcp.close(); - file->close(); - return; - } - if(! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForWritten file: "+file->fileName()); - tcp.close(); - file->close(); - return; - } - remain -= resNum; - } - file->close(); - req = QJsonObject(); - req.insert("_type", "imgFileEnd"); - req.insert("id", baseName); - req.insert("zVer","xixun1"); - resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileEnd'"); - tcp.close(); - return; - } - req = QJsonObject(); - req.insert("_type", "proEnd"); - req.insert("proName", "program"); - req.insert("zVer","xixun1"); - resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact)); - if(resNum == -1 || ! tcp.waitForBytesWritten()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proEnd'"); - tcp.close(); - return; - }; - if(! tcp.waitForReadyRead()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'proEnd'"); - tcp.close(); - return; - } - auto resp = tcp.readAll(); - if(resp.isEmpty()) { - emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'proEnd'"); - tcp.close(); - return; - } - tcp.close(); - emit emErr(""); -} diff --git a/LedOK/wDevicesManager/ctrladvancedpanel.h b/LedOK/wDevicesManager/ctrladvancedpanel.h deleted file mode 100644 index 8f921f7..0000000 --- a/LedOK/wDevicesManager/ctrladvancedpanel.h +++ /dev/null @@ -1,163 +0,0 @@ -#ifndef CTRLADVANCEDPANEL_H -#define CTRLADVANCEDPANEL_H - -#include "wDevicesManager/ledcard.h" -#include "communication/hpptclient.h" -#include "base/loemptydialog.h" -#include -#include -#include -#include -#include -#include -#include -#include - -class CtrlAdvancedPanel : public QWidget { - Q_OBJECT -public: - explicit CtrlAdvancedPanel(QWidget *parent = nullptr,QList *m_pLedlist=nullptr); - ~CtrlAdvancedPanel(); -protected: - void showEvent(QShowEvent *event) override; - void init(); - void changeEvent(QEvent *) override; - void transUi(); - - void keyReleaseEvent(QKeyEvent *) override; - void mouseReleaseEvent(QMouseEvent *) override; - -protected slots: - void On0degrees(); - void On90degrees(); - void On180degrees(); - void On270degrees(); - void OnSendMinBrightness(); - void OnSendMaxBrightness(); - void OnGetMinBrightness(); - void OnGetMaxBrightness(); - void OnSendCustomJson(); -signals: - void sigSend(QJsonObject &,QString); - void sigSetTipTextContent(QString); -protected slots: - void DeletePostingDlg(); - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnProHttpResponseAll(QString url, QString postMD5, QByteArray data); - void OnSetRealtimeServer(); - void OnClearRealtimeServer(); - void OnStartConfigLedScreenSoft(); - void OnRestart(); - void OnFpgaUpgrade(); - void OnFpgaVerCheck(); - void OnSyncFpgaVer(); - void slotUploadFinished(); - void slotUploadFpgaFinished(); - void slotUploadProgress(qint64 A,qint64 B); - void OnM80Set(); - void OnM80Refresh(); - void OnM80Restore(); - void OnSetTaxiTopScreen(); - void OnReadbackTaxiTopScreen(); - void OnOpenAdb(); -private: - QList *m_pLedlist=nullptr; - LedCard *m_pLedCard = nullptr; - HpptClient *pHpptClient = nullptr; - HpptClient *pHpptClientAll = nullptr; - QString m_strUrl=""; - QString m_strStartUrl=""; - LoEmptyDialog * m_PostingDlg=nullptr; - QTimer *m_pGetAskTimer=nullptr; - bool m_passwordOk=false; - QString m_strUpgradeApkFile=""; - QString m_strUpgradeFpgaFile=""; - QJsonObject mM80Map; - bool m_lockFlag=true; - void UpLoadForm(QString Path, QMap params, QString fileFormName, QFile *uploadFile, int iType); - - QLabel *lbTitle; - QLabel *lbScreenWidth; - QLineEdit *fdScreenWidth; - QLabel *lbScreenHeight; - QLineEdit *fdScreenHeight; - QPushButton *btnScreenSet; - QLabel *lbAlias; - QLineEdit *fdAlias; - QPushButton *btnAliasSet; - QLabel *labelWebServer; - QComboBox *fdWebServerAddr; - QLabel *lbCompanyId; - QLineEdit *fdCompanyId; - QPushButton *btnWebServerSet; - QLabel *label; - QComboBox *comboBox_realtimeServer; - QPushButton *pushButtonSetREaltimeServer; - QPushButton *pushButtonClearRealtimerAddress; - QPushButton *btnApkCheck; - QPushButton *btnApkUpgrade; - QComboBox *fdPkg; - QPushButton *fdUnload; - QPushButton *btnRunningCheck; - QPushButton *pushButtonFpgaUpgrade; - QPushButton *pushButtonFpgaVerCheck; - QPushButton *pushButtonSyncFpgaVer; - QPushButton *pushButtonRestart; - QPushButton *btnClearProg; - QPushButton *btnGetLog; - QPushButton *btnSetBack, *btnPlayerBackSet, *btnPlayerBackClear; - - QGroupBox *groupM80; - QComboBox *fdM80; - QPushButton *btnM80Set; - QPushButton *btnM80Refresh; - QPushButton *btnM80Restore; - QGroupBox *groupTopLevel; - QRadioButton *fdTopLevelHL; - QRadioButton *fdTopLevelLH; - QPushButton *btnSetTopLevel; - QPushButton *btnGetTopLevel; - QPushButton *btnLedSet3; - QPushButton *btnLedSet4; - QPushButton *btnBindTaxiIc; - - QGroupBox *groupBoxRotate; - QRadioButton *radioButton0degrees; - QRadioButton *radioButton90degrees; - QRadioButton *radioButton180degrees; - QRadioButton *radioButton270degrees; - QGroupBox *groupBoxMinMaxBrightness; - QLabel *lbMinBright; - QLineEdit *fdMinBright; - QLabel *lbMinBrightTip; - QPushButton *btnMinBrightGet; - QPushButton *btnMinBrightSet; - QLabel *label_3; - QLineEdit *lineEdit_4; - QLabel *label_5; - QPushButton *pushButtonReadbackMaxBrightess; - QPushButton *pushButtonSendMaxBrightness; - - QGroupBox *grpBoxHiddenSettings; - QPushButton *btnSysUpd; - QLabel *lbBaudCfg, *lbBaudModel, *lbUart, *lbBaud; - QPushButton *btnBaudSet, *btnBaudGet; - QCheckBox *fdIsOpenADB; - QLabel *lbCustomJson; - QTextEdit *fdCustomJson; - QPushButton *btnSendCustomJson; -}; - -class PlayerBackSendThread : public QThread { - Q_OBJECT -public: - PlayerBackSendThread(const QString &file, const QString &ip); - QString file, ip; - QString err; -protected: - void run(); -signals: - void emErr(QString); -}; - -#endif // CTRLADVANCEDPANEL_H diff --git a/LedOK/wDevicesManager/threadupgradeapk.cpp b/LedOK/wDevicesManager/threadupgradeapk.cpp deleted file mode 100644 index 494b641..0000000 --- a/LedOK/wDevicesManager/threadupgradeapk.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include "threadupgradeapk.h" -#include "QFileInfo" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -ThreadUpgradeApk::ThreadUpgradeApk(QString strApkPathAndName,QString url,int iType) -{ - m_strApkName=strApkPathAndName; - m_strUrl=url; - m_iType=iType; -} -ThreadUpgradeApk::~ThreadUpgradeApk() -{ - -} -void ThreadUpgradeApk::run() -{ - // QCoreApplication::processEvents(); - if(bSendCloseFlag==true) - bSendCloseFlag=false; - else { - return; - } - QFileInfo file1(m_strApkName); - QFile file(m_strApkName); - QMap params_send; //上传的普通参数 在本程序中 需要上传一个普通参数为"username" - params_send.insert("username","10005"); - //emit sigSetLableText(tr("UpLoadForm")); - UpLoadForm(m_strUrl,params_send,file1.fileName(),&file,file1.fileName(),m_iType); - -} - - -//void ThreadUpgradeApk::UpLoadForm(QString strUrl,QString strFilePathName) -//{ -//QString xlname = "text.xlsx"; -// QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); -// QHttpPart imagePart; -// imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xlsx")); -// imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\""+ xlname + "\"")); // file为后端定义的key,filename即为excel文件名 - -// QFile *file = new QFile(strFilePathName);//pathbuf1 为文件路径 -// file->open(QIODevice::ReadOnly); -// imagePart.setBodyDevice(file); -// file->setParent(multiPart); -// multiPart->append(imagePart); - -// QUrl url(strUrl); -// QNetworkRequest netReq; -// netReq.setUrl(url); -// QNetworkAccessManager *_uploadManager=new QNetworkAccessManager(); - -// connect(_uploadManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(send_xlsdata(QNetworkReply*))); -// _uploadManager->post(netReq,multiPart); -//} -void ThreadUpgradeApk::UpLoadForm(QString Path,QMap params,QString fileFormName,QFile *uploadFile,QString newFileName,int iType) -{ - QString BOUNDARY=QUuid::createUuid().toString(); - QByteArray sb=QByteArray(); - //先上传普通的表单数据 -// for(QMap::iterator t=params.begin();t!=params.end();t++) - { - sb.append("--"+BOUNDARY+"\r\n"); - sb.append(QString("Content-Disposition: form-data;name=\"")+t.key()+QString("\"")+QString("\r\n")); - sb.append("\r\n"); - sb.append(t.value()+"\r\n"); - } - //上传文件的头部 - sb.append("--"+BOUNDARY+"\r\n"); - sb.append(QString("Content-Disposition: form-data;name=\"")+fileFormName+QString("\";filename=\"")+newFileName+QString("\"")+QString("\r\n")); - sb.append("\r\n"); - //上传文件内容 - if(!uploadFile->open(QIODevice::ReadOnly)){ - return; - } - sb.append(uploadFile->readAll()); - sb.append("\r\n"); - sb.append("--"+BOUNDARY+"\r\n"); - - //编辑HTTP头部 - QNetworkAccessManager *_uploadManager=new QNetworkAccessManager(); - QNetworkRequest request=QNetworkRequest(QUrl(Path)); - request.setRawHeader(QString("Content-Type").toLatin1(),QString("multipart/form-data;boundary="+BOUNDARY).toLatin1()); - request.setRawHeader(QString("Content-Length").toLatin1(),QString::number(sb.length()).toLatin1()); - //执行post请求 - // if(m_PostingDlg==nullptr) - { - //m_PostingDlg = new LoEmptyDialog(); - //connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg())); - //connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock())); - //m_PostingDlg->lock(tr("UpgradeSoftware"),tr("Success"),tr("UpgradeSoftware")+tr("failed")); - //m_pGetAskTimer->start(60000); - QNetworkReply * m_netReply =_uploadManager->post(request,sb); - connect(m_netReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64))); - // connect(this, SIGNAL(sigSetTipTextContent ( QString )), m_PostingDlg, SLOT( SetTipTextContent(QString))); - if(iType==0)//apk - { - connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFinished())); - - } - else if(iType==1)//fpga.rpd - { - connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFpgaFinished())); - - } - QEventLoop eventLoop; - QTimer timer; - - connect(m_netReply, SIGNAL(finished()), &eventLoop, SLOT(quit())); - connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit())); - timer.start(600 * 1000); - eventLoop.exec(); // block until finish - - if (timer.isActive()) { - timer.stop(); - } else { - disconnect(m_netReply, SIGNAL(finished()), &eventLoop, SLOT(quit())); - m_netReply->abort(); - m_netReply->deleteLater(); - return ; - } - //m_PostingDlg->exec(); - } - - -} -void ThreadUpgradeApk::slotTimerOutUnlock() -{ - emit sigTimerOut(); - bSendCloseFlag=true; -} -void ThreadUpgradeApk::slotUploadProgress(qint64 A,qint64 B) -{ - if(B!=0) - { - QString strbaifenbi=tr("Uploadding")+":"+QString("%1%").arg(A*100/B); - emit sigSetProgressValue(A*100/B); - emit sigSetLableText(strbaifenbi); -// m_pGetAskTimer->stop(); -// m_pGetAskTimer->start(30000); - } -} -void ThreadUpgradeApk::slotUploadFinished() -{ - emit sigFinished(); -// MACRO_ASKTIME_STOP -// m_pGetAskTimer->start(40000); - - qDebug()<<"slotUploadFinished"; - -} -void ThreadUpgradeApk::slotUploadFpgaFinished() -{ - emit sigFpgaFinished(); -// MACRO_ASKTIME_STOP -// m_pGetAskTimer->start(40000); - - qDebug()<<"slotUploadFinished"; - -} - -void ThreadUpgradeApk::OnUpgradeSuccess() -{ -// MACRO_ASKTIME_STOP - bSendCloseFlag=true; - -} -void ThreadUpgradeApk::OnUpgradeFail() -{ -// MACRO_ASKTIME_STOP - bSendCloseFlag=true; - -} diff --git a/LedOK/wDevicesManager/threadupgradeapk.h b/LedOK/wDevicesManager/threadupgradeapk.h deleted file mode 100644 index ab29a4e..0000000 --- a/LedOK/wDevicesManager/threadupgradeapk.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef THREADUPGRADEAPK_H -#define THREADUPGRADEAPK_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -const quint16 PORT = 3333; -const qint64 LOADBYTES = 4 * 1024; // 4 kilo-byte -const int DATA_STREAM_VERSION = QDataStream::Qt_4_8; -class ThreadUpgradeApk:public QThread -{ - Q_OBJECT -public: - ThreadUpgradeApk(QString strApkPathAndName,QString url="",int iPort=3333); - ~ThreadUpgradeApk(); - void run(); -protected slots: - void slotUploadProgress(qint64 A,qint64 B); - void slotUploadFinished(); - void slotUploadFpgaFinished(); - void slotTimerOutUnlock(); - void OnUpgradeSuccess(); - void OnUpgradeFail(); -signals: - void sigSetLableText(QString); - - void sigSetProgressValue(int); - void sigSetProgressMax(int); - void sigFinished(); - void sigFpgaFinished(); - void sigTimerOut(); -private: - bool bSendCloseFlag=true; - QString m_strApkName; - QString m_strUrl; - int m_reSendCount=0; - QTimer *m_pGetAskTimer=nullptr; - int m_iType=0; - void UpLoadForm(QString Path,QMap params,QString fileFormName,QFile *uploadFile,QString newFileName,int iType); -// void UpLoadForm(QString strUrl,QString strFilePathName); - -}; - -#endif // THREADSENDPRO_H diff --git a/LedOK/wDevicesManager/upgradeapkdialog.cpp b/LedOK/wDevicesManager/upgradeapkdialog.cpp deleted file mode 100644 index b3f1139..0000000 --- a/LedOK/wDevicesManager/upgradeapkdialog.cpp +++ /dev/null @@ -1,493 +0,0 @@ -#include "upgradeapkdialog.h" -#include "tools.h" -#include "ui_upgradeapkdialog.h" -#include -#include -#include -#include -UpgradeApkDialog::UpgradeApkDialog(QWidget *parent) : QDialog(parent) { - resize(1280, 720); - setWindowState(Qt::WindowMaximized); - setSizeGripEnabled(false); - - setWindowTitle(tr("Upgrade apk")); - - auto vBox = new QVBoxLayout(this); - auto hBox = new QHBoxLayout(); - auto pushButtonSelectApk = new QPushButton(tr("Select apk")); - pushButtonSelectApk->setMinimumSize(QSize(100, 30)); - hBox->addWidget(pushButtonSelectApk); - - auto label_ApkPath = new QLabel(); - label_ApkPath->setMinimumSize(QSize(200, 30)); - label_ApkPath->setStyleSheet("background-color: #ffffff;"); - label_ApkPath->setFrameShape(QFrame::NoFrame); - label_ApkPath->setFrameShadow(QFrame::Plain); - label_ApkPath->setScaledContents(false); - - hBox->addWidget(label_ApkPath); - - auto pushButtonPublish = new QPushButton(tr("Upgrade")); - pushButtonPublish->setMinimumSize(QSize(80, 30)); - hBox->addWidget(pushButtonPublish); - hBox->addStretch(); - - auto label_4 = new QLabel(tr("APK:")); - hBox->addWidget(label_4); - - auto comboBoxApk = new QComboBox(); - comboBoxApk->setEnabled(true); - comboBoxApk->setMinimumSize(QSize(200, 30)); - comboBoxApk->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - comboBoxApk->setEditable(false); - comboBoxApk->setFrame(false); - - hBox->addWidget(comboBoxApk); - - auto lineEditPackageName = new QLineEdit(); - lineEditPackageName->setMinimumSize(QSize(120, 30)); - lineEditPackageName->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - - hBox->addWidget(lineEditPackageName); - - auto pushButtonUninstall = new QPushButton(tr("Uninstall")); - pushButtonUninstall->setMinimumSize(QSize(80, 30)); - hBox->addWidget(pushButtonUninstall); - - auto pushButtonCheckRuningState = new QPushButton(tr("check running state")); - pushButtonCheckRuningState->setMinimumSize(QSize(140, 30)); - hBox->addWidget(pushButtonCheckRuningState); - - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - auto pushButtonSelectFpga = new QPushButton(tr("Select Fpga")); - pushButtonSelectFpga->setMinimumSize(QSize(100, 30)); - hBox->addWidget(pushButtonSelectFpga); - - auto label_FpgaPath = new QLabel(); - label_FpgaPath->setMinimumSize(QSize(200, 30)); - label_FpgaPath->setStyleSheet("QLabel{background: #fff;}"); - hBox->addWidget(label_FpgaPath); - - auto pushButtonUpgradeFpga = new QPushButton(tr("Upgrade")); - pushButtonUpgradeFpga->setMinimumSize(QSize(0, 30)); - hBox->addWidget(pushButtonUpgradeFpga); - - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - auto label = new QLabel(tr("success info")); - hBox->addWidget(label); - - hBox->addStretch(); - - auto pushButtonRefresh = new QPushButton(tr("Refresh")); - pushButtonRefresh->setMinimumSize(QSize(0, 30)); - hBox->addWidget(pushButtonRefresh); - - auto txtSearch = new QLineEdit(); - txtSearch->setStyleSheet(QString::fromUtf8("background-color: #FFFFFF;")); - txtSearch->setClearButtonEnabled(false); - hBox->addWidget(txtSearch, 0, Qt::AlignRight); - - vBox->addLayout(hBox); - - wDevicePublishList = new LoQTreeWidget(); - vBox->addWidget(wDevicePublishList); - - hBox = new QHBoxLayout(); - hBox->addStretch(); - - auto pushButtonCancel = new QPushButton(tr("Cancel")); - pushButtonCancel->setMinimumSize(QSize(0, 30)); - connect(pushButtonCancel, &QPushButton::clicked, this, &UpgradeApkDialog::reject); - hBox->addWidget(pushButtonCancel, 0, Qt::AlignRight); - - vBox->addLayout(hBox); - - QAction *search = new QAction(txtSearch); - search->setIcon(QIcon(":/res/ProgramManager/bnSearch.png")); - txtSearch->addAction(search, QLineEdit::LeadingPosition); - txtSearch->setClearButtonEnabled(true); - txtSearch->setStyleSheet("border: 2px solid #aaaaaa;"); - wDevicePublishList->setProperty("ssType", "topList"); - pushButtonRefresh->setProperty("ssType", "progManageTool"); - pushButtonPublish->setProperty("ssType", "progManageTool"); - pushButtonSelectApk->setProperty("ssType", "progManageTool"); - pushButtonSelectFpga->setProperty("ssType", "progManageTool"); - pushButtonUpgradeFpga->setProperty("ssType", "progManageTool"); - pushButtonUninstall->setProperty("ssType", "progManageTool"); - pushButtonCheckRuningState->setProperty("ssType", "progManageTool"); - pushButtonCancel->setProperty("ssType", "progManageTool"); - - m_headerItem = new QTreeWidgetItem(); - m_headerItem->setTextAlignment(1, Qt::AlignHCenter | Qt::AlignVCenter); - - for(int i=1; isetTextAlignment(i, Qt::AlignCenter); - - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 0, ""); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, tr("Screen ID")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, tr("Remark Name")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 0, tr("Online")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, tr("Screen IP")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT,0,tr("Security")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 0, tr("Progress")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION, 0, tr("xixunplayer")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION,0,tr("cardsystem")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION,0,tr("taxiapp")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION,0,tr("starter")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION,0,tr("connection")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION,0,tr("displayer")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_FPAG_VERSION,0,tr("FPGA")); - - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION,0,tr("update")); - m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS,0,tr("State")); - - wDevicePublishList->setHeaderItem(m_headerItem); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_CHECK, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, QHeaderView::Fixed); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION, QHeaderView::Stretch); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION, QHeaderView::Stretch); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_FPAG_VERSION, QHeaderView::ResizeToContents); - - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION, QHeaderView::ResizeToContents); - wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, QHeaderView::Stretch); - - wDevicePublishList->header()->setStretchLastSection(false); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 50); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 120); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 50); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, 50); - wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 100); - lineEditPackageName->setVisible(false); - comboBoxApk->addItem("com.xixun.xixunplayer"); - comboBoxApk->addItem("com.xixun.joey.cardsystem"); - comboBoxApk->addItem("com.xixun.joey.systemcore"); - comboBoxApk->addItem("net.sysolution.taxiapp"); - comboBoxApk->addItem("net.sysolution.starter"); - comboBoxApk->addItem("com.xixun.display"); - comboBoxApk->addItem("com.xixun.xy.conn"); - comboBoxApk->addItem("com.xixun.xy.update"); - comboBoxApk->addItem("net.sysolution.basicapp"); - comboBoxApk->addItem("PackageName"); - - comboBoxApk->setCurrentIndex(0); - comboBoxApk->setFocus(); - pushButtonPublish->setEnabled(false); - pushButtonUpgradeFpga->setEnabled(false); - connect(pushButtonRefresh, &QPushButton::clicked, this, [this, label] { - wDevicePublishList->clear(); - wDevicePublishList->onCheckAll(false); - int iCount = gDevicePanel->LedCardList.count(); - for(int i=0;iLedCardList.at(i)); - label->setText(tr("All")+":"+QString::number(iCount)); - }); - connect(pushButtonPublish, &QPushButton::clicked, this, [this, label_ApkPath] { - QString strApkName = label_ApkPath->text(); - if(strApkName.length()<3) return; - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) static_cast(wDevicePublishList->topLevelItem(i))->onUpgradeApk(strApkName); - }); - connect(pushButtonUpgradeFpga, &QPushButton::clicked, this, [this, label_FpgaPath] { - QString strFpgaName = label_FpgaPath->text(); - if(strFpgaName.length()<3) return; - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) static_cast(wDevicePublishList->topLevelItem(i))->onUpgradeFpga(strFpgaName); - }); - - connect(pushButtonSelectApk,&QPushButton::clicked, this, [this, label_ApkPath, pushButtonPublish] { - QString strUpgradeApkFile = QFileDialog::getOpenFileName(this, "Open file", QString(), tr("apk package (*.apk *.zip)")); - label_ApkPath->setText(strUpgradeApkFile); - pushButtonPublish->setEnabled(QFileInfo::exists(strUpgradeApkFile)); - }); - connect(pushButtonSelectFpga, &QPushButton::clicked, this, [this, label_FpgaPath, pushButtonUpgradeFpga] { - QString m_strUpgradeFpgaFile = QFileDialog::getOpenFileName(this, "Open File", QString(), tr("apk package (*.rpd)")); - label_FpgaPath->setText(m_strUpgradeFpgaFile); - pushButtonUpgradeFpga->setEnabled(QFileInfo::exists(m_strUpgradeFpgaFile)); - }); - connect(pushButtonUninstall, &QPushButton::clicked, this, [this, comboBoxApk, lineEditPackageName] { - QString strApkName = comboBoxApk->currentText(); - if(strApkName=="PackageName") strApkName = lineEditPackageName->text(); - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) static_cast(wDevicePublishList->topLevelItem(i))->onUninstallApk(strApkName); - }); - connect(pushButtonCheckRuningState, &QPushButton::clicked, this, [this, comboBoxApk, lineEditPackageName] { - QString strApkName = comboBoxApk->currentText(); - if(strApkName=="PackageName") strApkName= lineEditPackageName->text(); - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; itopLevelItem(i)->checkState(0) == Qt::Checked) static_cast(wDevicePublishList->topLevelItem(i))->onCheckRuningState(strApkName); - }); - - connect(txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &))); - connect(comboBoxApk, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [comboBoxApk, lineEditPackageName](int) { - if(comboBoxApk->currentText()=="PackageName") { - lineEditPackageName->setVisible(true); - lineEditPackageName->setFocus(); - } else lineEditPackageName->setVisible(false); - }); - - int iCount = gDevicePanel->LedCardList.count(); - for(int i=0; iLedCardList.at(i)); - label->setText(tr("All")+":"+QString::number(iCount)); - - auto timer = new QTimer(this); - connect(timer, &QTimer::timeout, this, [this, label] { - int iCount = gDevicePanel->LedCardList.count(); - for(int i=0;iLedCardList.at(i)); - label->setText(tr("All")+":"+QString::number(iCount)); - }); - timer->start(500000); -} - -void UpgradeApkDialog::onAddLedCard(LedCard *card) { - int iExistFlg=0; - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; i(wDevicePublishList->topLevelItem(i))->m_pLedCard->m_strCardId; - if(strTempCardId == card->m_strCardId) { - iExistFlg=1; - static_cast(wDevicePublishList->topLevelItem(i))->SetItemParam(card); - break; - } - } - if(iExistFlg==0) new wUpgradeApkItem(card, wDevicePublishList, this); -} - -void UpgradeApkDialog::keyPressEvent(QKeyEvent *ev) { - if(ev->key() == Qt::Key_F3) { - QMessageBox::warning(this, "Tip", tr("The encrypted control card can be upgraded directly")); - int cnt = wDevicePublishList->topLevelItemCount(); - for(int i=0; i(wDevicePublishList->topLevelItem(i))->SetLockFlagFalse(); - } -} -void UpgradeApkDialog::FilterProgram(const QString &strtemp) -{ - if (strtemp.isEmpty()) //显示全部 - { - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); - } - } - else - { - QList resultList = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID); //搜索结果 - if (resultList.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - - QList resultList6 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME); //搜索结果 - if (resultList6.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList6.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - - - //QMessageBox::warning(this, "Export", "FilterProgram"); - QList resultList1 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION); //搜索结果 - if (resultList1.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList1.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_FPAG_VERSION); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - QList resultList2 = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_REMARKS); //搜索结果 - if (resultList2.size() > 0) - { - //QMessageBox::warning(this, "Export", QString(resultList.size())); - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - if (resultList2.contains(topItem)) - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false); //显示匹配的结果 - else - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - else { - for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i) - { - QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i); - wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true); //隐藏不匹配的结果 - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } -} diff --git a/LedOK/wDevicesManager/upgradeapkdialog.ui b/LedOK/wDevicesManager/upgradeapkdialog.ui deleted file mode 100644 index 4433f28..0000000 --- a/LedOK/wDevicesManager/upgradeapkdialog.ui +++ /dev/null @@ -1,468 +0,0 @@ - - - UpgradeApkDialog - - - Qt::NonModal - - - - 0 - 0 - 1024 - 640 - - - - false - - - false - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 19 - - - - - 0 - - - - - Upgrade apk - - - - - - - - 32 - 16777215 - - - - - - - - - - - - 32 - 16777215 - - - - X - - - - - - - - - border-top: 1px solid gray; - - - Qt::Horizontal - - - - - - - 10 - - - - - - 0 - 0 - - - - - 100 - 30 - - - - Select apk - - - - - - - - 200 - 30 - - - - background-color: #ffffff; - - - QFrame::NoFrame - - - QFrame::Plain - - - - - - false - - - - - - - - 80 - 30 - - - - Upgrade - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - APK: - - - - - - - true - - - - 200 - 30 - - - - background-color: #FFFFFF; - - - false - - - false - - - - - - - - 120 - 30 - - - - background-color: #FFFFFF; - - - - - - - - 80 - 30 - - - - Uninstall - - - - - - - - 140 - 30 - - - - check running state - - - - - - - - - 10 - - - - - - 0 - 0 - - - - - 100 - 30 - - - - Select Fpga - - - - - - - - 200 - 30 - - - - background-color: #ffffff; - - - - - - - - - - - 0 - 30 - - - - Upgrade - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - success info - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Refresh - - - - - - - background-color: #FFFFFF; - - - false - - - - - - - - - - 1 - - - - - - - - - 0 - 0 - - - - border-top: 2px solid gray; - - - Qt::Horizontal - - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - Cancel - - - - - - - - - - - - - LoQTreeWidget - QTreeWidget -
base/loqtreewidget.h
-
-
- - - - pushButtonClose - clicked() - UpgradeApkDialog - close() - - - 987 - 31 - - - 511 - 383 - - - - - pushButtonCancel - clicked() - UpgradeApkDialog - reject() - - - 966 - 736 - - - 511 - 383 - - - - -
diff --git a/LedOK/wDevicesManager/wupgradeapkitem.cpp b/LedOK/wDevicesManager/wupgradeapkitem.cpp deleted file mode 100644 index 9901626..0000000 --- a/LedOK/wDevicesManager/wupgradeapkitem.cpp +++ /dev/null @@ -1,525 +0,0 @@ -#include "wupgradeapkitem.h" -#include "tools.h" -#include "base/x_uimsgboxok.h" -#include "passwordindlg.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -wUpgradeApkItem::wUpgradeApkItem(LedCard *pLedCard, LoQTreeWidget *parent, QWidget *pWnd) : - QObject(parent), - QTreeWidgetItem(UserType), - m_parent(parent) -{ - m_pWnd=pWnd; - m_pLedCard=pLedCard; - pHpptClient = new HpptClient(this); - connect(pHpptClient,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponse(QString , QString , QByteArray))); - init(); - -} -wUpgradeApkItem::~wUpgradeApkItem() -{ - if(pHpptClient!=nullptr) - { - qDebug() <<"delete pHpptClient in ~wUpgradeApkItem"; - delete pHpptClient; - pHpptClient=nullptr; - } -} - -void wUpgradeApkItem::init() -{ - setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); - setCheckState(0, Qt::Unchecked); - m_parent->addTopLevelItem(this); - m_ImageOnline = new QLabel(); - m_ImageOnline->setStyleSheet("margin-top:12px; margin-bottom:12px"); - m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ONLINE, m_ImageOnline); - m_ImageOnline->setAlignment(Qt::AlignCenter); - for(int i=1; isetMaximumHeight(16); - m_pProgress->setStyleSheet("margin-top:12px; margin-bottom:12px"); - //setData(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS,) - m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, m_pProgress); - m_pProgress->setAlignment(Qt::AlignCenter); - QSizePolicy policy = m_pProgress->sizePolicy(); - policy.setHorizontalStretch(1); - policy.setVerticalStretch(1); - policy.setHorizontalPolicy(QSizePolicy::Expanding); - m_pProgress->setSizePolicy(policy); - m_pProgress->setValue(0); - m_pProgress->setFixedWidth(100); - //启动心跳,监测设备在线和下线,3次超时表示下线 - OnCheckSoftVersions(); - OnCheckFpgaVersions(); - -} -void wUpgradeApkItem::SetLockFlagFalse() -{ - m_lockFlag=false; - -} - -void wUpgradeApkItem::refreshLable() -{ - -} -void wUpgradeApkItem::OnCheckFpgaVersions() -{ - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings"; - QJsonObject json1; - json1.insert("_id", getRandomString(10)); - json1.insert("_type", "CheckHardwareVersions"); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json1); -} -void wUpgradeApkItem::OnCheckSoftVersions() -{ - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings"; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "CheckSoftVersions"); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - -} -extern QWidget *gMainWin; -void wUpgradeApkItem::onVerifyLockPassword() { - bool ok; - auto pwd = QInputDialog::getText(gMainWin, tr("Input password"), tr("Input password"), QLineEdit::Password, QString(), &ok); - if(! ok) return; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "VerifyPassword"); - json.insert("pwd", pwd); - m_strUrl = "http://"+m_pLedCard->m_strCardIp+":2016/settings"; - HttpPostByTypeJsonObject(pHpptClient, m_strUrl, json); -} -void wUpgradeApkItem::SetPasswordItem(LedCard *p){ - if(p->bPassword) {//加过密 - if(m_bnLock==nullptr){ - m_bnLock = new QPushButton(m_pWnd); - m_bnLock->setStyleSheet("background-color:transparent;"); - m_bnLock->setStyleSheet("margin-left:12px; margin-right:12px;margin-top:12px; margin-bottom:12px;"); - m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock); - connect(m_bnLock, SIGNAL(clicked()), this, SLOT(onVerifyLockPassword())); - } - if(p->m_bLockStatus) m_bnLock->setIcon(QIcon(":/res/DeviceManager/Lock.png")); //如果已经验证通过密码显示绿色图标 - else m_bnLock->setIcon(QIcon(":/res/DeviceManager/UnLock.png")); //如果没有验证显示蓝色锁图标 - m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock); - } -} -void wUpgradeApkItem::onUninstallApk(QString strApkName){ - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "UninstallSoftware"); - json.insert("packageName", strApkName); - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings"; - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - if(strApkName=="com.xixun.xixunplayer"){ - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION); - if(strtemp.isEmpty()) return; - }else if(strApkName=="com.xixun.joey.cardsystem"){ - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION); - if(strtemp.isEmpty()) return; - }else if(strApkName=="net.sysolution.taxiapp"){ - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION); - if(strtemp.isEmpty()) return; - } - else if(strApkName=="net.sysolution.starter") - { - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION); - if(strtemp.isEmpty()) - return; - - } - else if(strApkName=="com.xixun.display") - { - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION); - if(strtemp.isEmpty()) - return; - - } - else if(strApkName=="com.xixun.xy.conn") - { - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION); - if(strtemp.isEmpty()) - return; - - } - else if(strApkName=="com.xixun.xy.update") - { - QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION); - if(strtemp.isEmpty()) - return; - } - OnSendStatusTip(tr("uninstalling"),Qt::blue); -} -void wUpgradeApkItem::onCheckRuningState(QString strApkName) -{ - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "IsSoftwareRunning"); - json.insert("packageName", strApkName); - m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings"; - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - OnSendStatusTip(tr("IsSoftwareRunning"),Qt::blue); -} - -void wUpgradeApkItem::onUpgradeApk(QString strFileName) -{ - if(m_pLedCard->bPassword) - { - if(m_pLedCard->m_bLockStatus&&m_lockFlag == true) - { - OnSendStatusTip(tr("This screen is encrypted"),Qt::red); - return; - } - } - - if(m_iSendingFlag==1) - { - return; - } - m_strApkFilePathName=strFileName; - OnSendStatusTip(tr("Start upgrading"),Qt::blue); - - /* 发送连接请求 */ - ThreadUpgradeApk *m_pThreadSendPro=nullptr; - QString url="http://"+m_pLedCard->m_strCardIp+":2016/upload?type=software"; - m_pThreadSendPro = new ThreadUpgradeApk(strFileName,url,0); - this->moveToThread(m_pThreadSendPro); - - connect(m_pThreadSendPro,SIGNAL(sigSetLableText(QString)),this,SLOT(OnSendStatusTip(QString))); - connect(m_pThreadSendPro,SIGNAL(sigSetProgressValue(int)),m_pProgress,SLOT(setValue(int))); - connect(m_pThreadSendPro,SIGNAL(sigTimerOut()),m_pProgress,SLOT(slotTimeout())); - - - m_pProgress->setMaximum(100); - // connect(m_pThreadSendPro,SIGNAL(sigSetProgressMax(int)),m_pProgress,SLOT(setMaximum(int))); - connect(m_pThreadSendPro,SIGNAL(sigFinished()),this,SLOT(OnThreadFinished())); - connect(this,SIGNAL(sigUpgradeSuccess()),m_pThreadSendPro,SLOT(OnUpgradeSuccess())); - connect(this,SIGNAL(sigUpgradeFail()),m_pThreadSendPro,SLOT(OnUpgradeFail())); - m_iSendingFlag=1; - m_pProgress->setValue(0); - m_pThreadSendPro->start(); - } -void wUpgradeApkItem::onUpgradeFpga(QString strFileName) -{ - if(m_pLedCard->bPassword) - { - if(m_pLedCard->m_bLockStatus&&m_lockFlag == true) - { - OnSendStatusTip(tr("This screen is encrypted"),Qt::red); - return; - } - } - - if(m_iSendingFlag==1) - { - return; - } - m_strFpgaFilePathName=strFileName; - OnSendStatusTip(tr("Start upgrading"),Qt::blue); - /* 发送连接请求 */ - ThreadUpgradeApk *m_pThreadSendPro=nullptr; - QString url="http://"+m_pLedCard->m_strCardIp+":2016/upload?type=hardware"; - - m_pThreadSendPro = new ThreadUpgradeApk(strFileName,url,1); - this->moveToThread(m_pThreadSendPro); - connect(m_pThreadSendPro,SIGNAL(sigSetLableText(QString)),this,SLOT(OnSendStatusTip(QString))); - connect(m_pThreadSendPro,SIGNAL(sigSetProgressValue(int)),m_pProgress,SLOT(setValue(int))); - connect(m_pThreadSendPro,SIGNAL(sigTimerOut()),m_pProgress,SLOT(slotTimeout())); - m_pProgress->setMaximum(100); - // connect(m_pThreadSendPro,SIGNAL(sigSetProgressMax(int)),m_pProgress,SLOT(setMaximum(int))); - connect(m_pThreadSendPro,SIGNAL(sigFpgaFinished()),this,SLOT(OnThreadFpgaFinished())); - connect(this,SIGNAL(sigUpgradeSuccess()),m_pThreadSendPro,SLOT(OnUpgradeSuccess())); - connect(this,SIGNAL(sigUpgradeFail()),m_pThreadSendPro,SLOT(OnUpgradeFail())); - m_iSendingFlag=1; - m_pProgress->setValue(0); - m_pThreadSendPro->start(); - } - -void wUpgradeApkItem::slotTimeout() -{ - OnSendStatusTip(tr("Timeout")); - m_iSendingFlag=0; - OnCheckSoftVersions(); - OnCheckFpgaVersions(); -} -void wUpgradeApkItem::OnSendStatusTip(QString strTip) -{ - QCoreApplication::processEvents(); - - setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip); - this->setTextColor(ENUM_DEVICE_PUBLISH_HEADE_REMARKS,Qt::blue); - if(strTip==tr("Timeout")) - { - - } - -} -void wUpgradeApkItem::OnSendStatusTip(QString strTip,QColor cr) -{ - QCoreApplication::processEvents(); - - setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip); - this->setTextColor(ENUM_DEVICE_PUBLISH_HEADE_REMARKS,cr); - -} -void wUpgradeApkItem::OnThreadFinished() -{ - m_iSendingFlag=0; - m_pProgress->setValue(100); - qDebug()<<"OnThreadFinished"; - QFileInfo file(m_strApkFilePathName); - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "UpgradeSoftware"); - json.insert("fileName", file.fileName()); - json.insert("isCustom", true); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - OnSendStatusTip(tr("install start..."),Qt::blue); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - -} -void wUpgradeApkItem::OnThreadFpgaFinished() -{ - m_iSendingFlag=0; - m_pProgress->setValue(100); - qDebug()<<"OnThreadFinished"; - QJsonObject json; - json.insert("_id", getRandomString(10)); - json.insert("_type", "SynchronousHardwareVersion"); - HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json); - OnSendStatusTip(tr("SynchronousHardwareVersion"),Qt::blue); -} - -void wUpgradeApkItem::SetItemParam(LedCard *p) -{ - setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, p->m_strCardId); - setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, p->m_strCardIp); - m_pLedCard->m_strCardId=p->m_strCardId; - m_pLedCard->m_strCardIp=p->m_strCardIp; - m_pLedCard->m_bOnLine=p->m_bOnLine; - // setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, QString("%1 x %2").arg(p->m_iWidth).arg(p->m_iHeight)); - if(m_pLedCard->m_bOnLine) - { - m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Online.png")); - } - else - { - m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Offline.png")); - } - SetPasswordItem(m_pLedCard); - setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, p->m_strCardRemarkName); - OnCheckSoftVersions(); - OnCheckFpgaVersions(); -// //progresss.append(progress); -// QTableWidgetItem *topLevelItem = new QTableWidgetItem(); //创建一个 TreeItem 容器用于后来装载控件 -// topLevelItem->setData(0,listProgramName->at(i)); -// topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable); -// /*上面用到的两个枚举中:~Qt::ItemIsEnabled可以保证单击该Item时不会被选中,但是在启用Ctrl + A时,全选操作会导致Item被选中。 -// * ~Qt::ItemIsSelectable的使用可以保证全选状态下也不会被选中,但是在单独使用时出现了虚线框,没有真正实现“不存在”的效果。所以必须两个同用。*/ -// ctrlProgramList->setItem(i,0,topLevelItem); -// ctrlProgramList->setCellWidget(i, 1, progress); - -} - - - -QString wUpgradeApkItem::getRandomString(int length) -{ - qsrand(QDateTime::currentMSecsSinceEpoch()); - - const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - int size = sizeof(ch); - - char* str = new char[length + 1]; - - int num = 0; - for (int i = 0; i < length; ++i) - { - num = rand() % (size - 1); - str[i] = ch[num]; - } - - QString res(str); - return res; -} -///////////////////////////////////////////////// - -void wUpgradeApkItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data) -{ - Q_UNUSED(postMD5) - //qDebug()<< url + "\r\n"+m_strUrl; - if(url == m_strUrl) - { -// qDebug()<<"POST"; - //qDebug()<m_strCardId +"---------"+ strType; - if(strType=="TaskCommand" )//发送节目命令应答 - { - qDebug()<<"commandXixunPlayer response successed!"; - } - - else if(strType == "HasControllerPassword") - { - //if(m_pLedCard->bPassword!=jsonObject["result"].toBool()) - { - m_pLedCard->bPassword=jsonObject["result"].toBool(); - SetPasswordItem(m_pLedCard); - } - } - else if(strType == "VerifyPassword") - { - bool bStatus=jsonObject["result"].toBool(); - if(bStatus)//解密成功 - { - qDebug()<<"解密成功"; - m_pLedCard->m_bLockStatus=false; - } - else - { - qDebug()<<"解密失败"; - m_pLedCard->m_bLockStatus=true; - X_UIMsgBoxOk *mb = new X_UIMsgBoxOk(tr("Tip Info"),tr("password is wrong"), m_pWnd,0); - mb->exec(); - - } - SetPasswordItem(m_pLedCard); - } - else if(strType == "UninstallSoftware") - { - OnSendStatusTip(tr("UninstallSoftware")+tr("Success")+"!",Qt::green); - } - else if(strType == "IsSoftwareRunning") - { - if(jsonObject["running"].toBool()) - { - OnSendStatusTip(tr("Running")+"!",Qt::green); - - } - else { - OnSendStatusTip(tr("NoRunning")+"!",Qt::red); - - } - - } - else if(strType =="UpgradeSoftware") - { - emit sigUpgradeSuccess(); - OnSendStatusTip(tr("install success"),Qt::green); - OnCheckSoftVersions(); - - - } - else if(strType == "SynchronousHardwareVersion"){ - emit sigUpgradeSuccess(); - OnSendStatusTip(tr("SynchronousHardwareVersion")+tr("Success"),Qt::green); - OnCheckFpgaVersions(); - - } - else if(strType =="CheckHardwareVersions") - { - QString strtempVer=""; - int itempVerCount=0; - foreach(QJsonValue value, jsonObject["versions"].toArray()) { - QString strtempIcount=QString::number(itempVerCount); - if(itempVerCount==0) - strtempVer += "["+strtempIcount+"]:"+value.toString(); - else - strtempVer +="\r\n["+strtempIcount+"]:"+value.toString(); - itempVerCount++; - - } - setData(ENUM_DEVICE_PUBLISH_HEADE_FPAG_VERSION, 0, strtempVer); - } - else if(strType == "CheckSoftVersions"){ - QString strTip=""; - QStringList strtempApkPackList; - foreach(QJsonValue value, jsonObject["apps"].toArray()) { - QJsonObject oApp = value.toObject(); - QString strtempApkPackageName=oApp["packageName"].toString(); - QString strtempVersion=oApp["versionName"].toString(); - if(strtempApkPackageName=="com.xixun.xixunplayer") - setData(ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION, 0, strtempVersion); - else if(strtempApkPackageName=="com.xixun.joey.cardsystem") - setData(ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION, 0, strtempVersion); - else if(strtempApkPackageName=="net.sysolution.starter") - setData(ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION, 0, strtempVersion); - else if(strtempApkPackageName=="net.sysolution.taxiapp") - setData(ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION, 0, strtempVersion); - else if(strtempApkPackageName=="com.xixun.display") - setData(ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION, 0, strtempVersion); - else if(strtempApkPackageName=="com.xixun.xy.conn") - setData(ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION, 0, strtempVersion); - else if(strtempApkPackageName=="com.xixun.xy.update") - setData(ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION, 0, strtempVersion); -// else if(strtempApkPackageName=="net.sysolution.basicapp") -// setData(ENUM_DEVICE_PUBLISH_HEADE_BASICAPP_VERSION, 0, strtempVersion); - - strtempApkPackList.append(strtempApkPackageName); - - } - - } - } - else//失败应答,打印失败和错误信息 - { - if(strType == "UninstallSoftware") - { - OnSendStatusTip(tr("UninstallSoftware")+tr("Fail")+"!",Qt::red); - } - else if(strType == "IsSoftwareRunning") - { - OnSendStatusTip(tr("IsSoftwareRunning")+tr("Fail")+"!",Qt::red); - } - else if(strType =="UpgradeSoftware") - { - emit sigUpgradeFail(); - OnCheckSoftVersions(); - - } - else if(strType =="SynchronousHardwareVersion") - { - emit sigUpgradeFail(); - OnCheckFpgaVersions(); - - } - } - - } -} diff --git a/LedOK/wDevicesManager/wupgradeapkitem.h b/LedOK/wDevicesManager/wupgradeapkitem.h deleted file mode 100644 index 5ead936..0000000 --- a/LedOK/wDevicesManager/wupgradeapkitem.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef WUPGRADEAPKITEM_H -#define WUPGRADEAPKITEM_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "threadupgradeapk.h" -#include -#include - -class wUpgradeApkItem : public QObject, public QTreeWidgetItem { - Q_OBJECT -public: - explicit wUpgradeApkItem(LedCard *pLedCard, LoQTreeWidget *parent = nullptr,QWidget *pWnd=nullptr); - ~wUpgradeApkItem(); - - void refreshLable(); - void SetItemParam(LedCard *p); - void onUpgradeApk(QString strFileName); - void onUpgradeFpga(QString strFileName); - void onUninstallApk(QString strApkName); - void onCheckRuningState(QString strApkName); - void SetLockFlagFalse(); - - LedCard *m_pLedCard = nullptr; -signals: - void sigUpgradeSuccess(); - void sigUpgradeFail(); - -public slots: - void OnProHttpResponse(QString url, QString postMD5, QByteArray data); - void OnThreadFinished(); - void OnThreadFpgaFinished(); - void OnSendStatusTip(QString); - void onVerifyLockPassword(); - void slotTimeout(); - void OnCheckSoftVersions(); - void OnCheckFpgaVersions(); - -private: - void init(); - QString getRandomString(int length); - void SetPasswordItem(LedCard *p); - bool m_lockFlag=true; - void OnSendStatusTip(QString,QColor cr); - - QLabel *m_ImageOnline=nullptr; - LoQTreeWidget *m_parent = nullptr; - QString m_strUrl=""; - QWidget *m_pWnd=nullptr; - HpptClient *pHpptClient = nullptr; - QProgressBar *m_pProgress=nullptr; - int m_iSendingFlag=0; - QPushButton *m_bnLock = nullptr;// - QString m_strApkFilePathName=""; - QString m_strFpgaFilePathName=""; - - void postFileTask(const QString& strUrl, const QString& strFilePath);//需要的数据 -}; -enum ENUM_DEVICE_PUBLISH_HEADERITEM -{ - ENUM_DEVICE_PUBLISH_HEADE_CHECK=0, - ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, - ENUM_DEVICE_PUBLISH_HEADE_ONLINE, - ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, - ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, - ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, - ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_FPAG_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_REMARKS, - ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, - ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION, -// ENUM_DEVICE_PUBLISH_HEADE_BASICAPP_VERSION, - ENUM_DEVICE_PUBLISH_HEADE_END, -}; - - -#endif // WPROGRAMPUBLISHITEM_H diff --git a/LedOK/wProgramManager/eaclock.h b/LedOK/wProgramManager/eaclock.h deleted file mode 100644 index 5ea7339..0000000 --- a/LedOK/wProgramManager/eaclock.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef EACLOCK_H -#define EACLOCK_H - -#include "ebase.h" -#include "base/locolorselector.h" -#include -#include -#include -#include -#include -#include -#include - -class eAClock : public EBase { - Q_OBJECT -public: - struct Data { - QByteArray timeZoneId; - int hourMark;//时针 - int hourMarkSize;//时针大小 - QColor hourMarkColor;//时针颜色 - int minMark;//分针 - int minMarkSize;//分针大小 - QColor minMarkColor;//分针颜色 - QColor hourHandColor;//秒针 - QColor minHandColor;//秒针大小 - QColor secHandColor;//秒针颜色 - QString text;//标题 - QFont textFont;//标题字体 - QColor textColor;//标题字体颜色 - int playDuration=10;// - QString path=""; - QString name=""; - QString selfCreateDialName; - bool hasDialImg; - }; - - explicit eAClock(EBase *multiWin = nullptr); - explicit eAClock(const QJsonObject &json, EBase *multiWin = nullptr); - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; - int type() const override { return EBase::AClock; } - QWidget* attrWgt() override; - bool save(const QString &pRoot) override; - QJsonObject attrJson() const override; - -protected: - void drawMarkCircular (QPainter *painter, const QPointF &pos, const QColor &color, qreal diameter); - void drawMarkRectangle(QPainter *painter, const QPointF &pos, const QColor &color, qreal len, qreal rotate); - void drawMarkNumber (QPainter *painter, const QPointF &pos, const QColor &color, qreal len, int num); - void drawHand (QPainter *painter, qreal angle, const QColor &color, qreal len, qreal base); - void paintDial(QPainter *painter); - void paintText(QPainter *painter); - - qreal radiusHour() const; - qreal radiusMin() const; - qreal radius() const { return radiusHour() < radiusMin() ? radiusHour() : radiusMin(); } - - void init(); - - Data m_attr; - QImage dial_img; - QTime time; -}; - -#endif // EACLOCK_H diff --git a/LedOK/wProgramManager/etext.cpp b/LedOK/wProgramManager/etext.cpp deleted file mode 100644 index 25b47f7..0000000 --- a/LedOK/wProgramManager/etext.cpp +++ /dev/null @@ -1,1644 +0,0 @@ -#include "etext.h" -#include "base/locolorselector.h" -#include "cfg.h" -#include "globaldefine.h" -#include "tools.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -EText::EText(EBase *multiWin) : EBase(multiWin) { - mType = EBase::Text; - m_attr.text = tr("Enter your text"); - m_attr.cBackground = Qt::transparent; - m_attr.opt.setAlignment(Qt::AlignCenter); - m_attr.opt.setWrapMode(QTextOption::WrapAnywhere); - //Play - m_attr.playStyle = Flip; - m_attr.rolling.headTailConnected = true; - m_attr.rolling.headTailSpacing = 10; - m_attr.rolling.rollingSpeed = 50; - m_attr.rolling.rollingStyle = Left2Right; - m_attr.rolling.playDuration = 30; - connect(this, SIGNAL(sizeChanged()), this, SLOT(RefreshBigPixmap())); - RefreshBigPixmap(); -} -EText::EText(const QJsonObject &json, EBase *multiWin) : EBase(multiWin) { - mType = EBase::Text; - setBaseAttr(json); - setElement(json, m_attr); - connect(this, SIGNAL(sizeChanged()), this, SLOT(RefreshBigPixmap())); - RefreshBigPixmap(); -} - -void EText::setElement(const QJsonObject &json, Data &attr) { - auto widget = json["widget"]; - attr.text = widget["text"].toString(); - attr.lineSpacing = widget["lineSpacing"].toInt(); - attr.letterSpacing = widget["wordSpacing"].toInt(); - attr.opt.setAlignment(static_cast(widget["align"].toInt())); - attr.cBackground = Tools::int2Color(widget["cBackground"].toInt()); - attr.iPageCount = widget["iPageCount"].toInt(); - auto play = json["play"]; - attr.playStyle = play["style"].toInt(); - auto turning = play["turning"]; - attr.turning.effect = turning["strEffect"].toString(); - attr.turning.pageDuration = turning["iEffectTime"].toInt(); - attr.turning.effectDuration = turning["iEffectSpeed"].toInt(); - attr.turning.playDuration = turning["playDuration"].toInt(); - auto rolling = play["rolling"]; - attr.rolling.rollingStyle = rolling["rollingStyle"].toInt(); - attr.rolling.rollingSpeed = rolling["rollingSpeed"].toInt(); - attr.rolling.headTailConnected = rolling["headTailConnected"].toBool(); - attr.rolling.headTailSpacing = rolling["headTailSpacing"].toInt(); - attr.rolling.playDuration = rolling["playDuration"].toInt(); - attr.playDuration = play["static"]["playDuration"].toInt(); -} - -class TTextEdit : public QTextEdit { -public: - explicit TTextEdit(const QString &text) : QTextEdit(text){} - QSize minimumSizeHint() const override { - return sizeHint(); - }; - QSize sizeHint() const override { - auto size = QTextEdit::sizeHint(); - auto minH = minimumHeight(); - if(minH > 0) size.setHeight(minH+0xfff); - return size; - }; -}; -QWidget* EText::attrWgt() { - auto wgtAttr = new QWidget; - auto vBox = new QVBoxLayout(wgtAttr); - vBox->setContentsMargins(4, 0, 4, 0); - vBox->setSpacing(3); - - addBaseAttrWgt(vBox); - - auto hBox = new QHBoxLayout; - hBox->addWidget(new QLabel(tr("Basic Properties"))); - - auto line = new QFrame; - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - hBox->addWidget(line, 1); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout; - - auto fdText = new TTextEdit(m_attr.text); - - auto fdFontFamily = new QFontComboBox; - fdFontFamily->setEditable(false); - connect(fdFontFamily, &QFontComboBox::currentFontChanged, fdText, [fdText](const QFont &f) { - QTextCharFormat fmt; - fmt.setFontFamily(f.family()); - Tools::mergeFormat(fdText, fmt); - }); - hBox->addWidget(fdFontFamily); - - hBox->addStretch(); - - auto fdFontSize = new QSpinBox; - fdFontSize->setRange(4, 9999); - fdFontSize->setValue(16); - connect(fdFontSize, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, fdText, [fdText](int value) { - if(value <= 0) return; - QTextCharFormat fmt; - fmt.setProperty(QTextFormat::FontPixelSize, value); - Tools::mergeFormat(fdText, fmt); - }); - hBox->addWidget(fdFontSize); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout; - hBox->setSpacing(3); - - auto wTextAlignHL = new QPushButton(); - wTextAlignHL->setFixedSize(QSize(24, 24)); - wTextAlignHL->setIconSize(QSize(24, 24)); - QIcon icon3(":/res/ProgramManager/EditProgram/DocAlignHL_u.png"); - icon3.addFile(":/res/ProgramManager/EditProgram/DocAlignHL_s.png", QSize(), QIcon::Normal, QIcon::On); - wTextAlignHL->setIcon(icon3); - wTextAlignHL->setFlat(true); - wTextAlignHL->setCheckable(true); - wTextAlignHL->setChecked(true); - hBox->addWidget(wTextAlignHL); - - auto wTextAlignHC = new QPushButton(); - wTextAlignHC->setFixedSize(QSize(24, 24)); - wTextAlignHC->setIconSize(QSize(24, 24)); - QIcon icon4(":/res/ProgramManager/EditProgram/DocAlignHC_u.png"); - icon4.addFile(":/res/ProgramManager/EditProgram/DocAlignHC_s.png", QSize(), QIcon::Normal, QIcon::On); - wTextAlignHC->setIcon(icon4); - wTextAlignHC->setFlat(true); - wTextAlignHC->setCheckable(true); - hBox->addWidget(wTextAlignHC); - - auto wTextAlignHR = new QPushButton(); - wTextAlignHR->setFixedSize(QSize(24, 24)); - wTextAlignHR->setIconSize(QSize(24, 24)); - QIcon icon5(":/res/ProgramManager/EditProgram/DocAlignHR_u.png"); - icon5.addFile(":/res/ProgramManager/EditProgram/DocAlignHR_s.png", QSize(), QIcon::Normal, QIcon::On); - wTextAlignHR->setIcon(icon5); - wTextAlignHR->setFlat(true); - wTextAlignHR->setCheckable(true); - hBox->addWidget(wTextAlignHR); - - hBox->addStretch(); - - auto wFontBold = new QPushButton; - wFontBold->setFixedSize(QSize(24, 24)); - wFontBold->setIconSize(QSize(24, 24)); - QIcon icon(":/res/ProgramManager/EditProgram/FontBold_u.png"); - icon.addFile(":/res/ProgramManager/EditProgram/FontBold_s.png", QSize(), QIcon::Normal, QIcon::On); - wFontBold->setIcon(icon); - wFontBold->setFlat(true); - wFontBold->setCheckable(true); - connect(wFontBold, &QPushButton::toggled, fdText, [fdText](bool checked) { - QTextCharFormat fmt; - fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal); - Tools::mergeFormat(fdText, fmt); - }); - hBox->addWidget(wFontBold); - - auto fdFontItalic = new QPushButton; - fdFontItalic->setFixedSize(24, 24); - fdFontItalic->setIconSize(QSize(24, 24)); - icon = QIcon(":/res/ProgramManager/EditProgram/FontItalics_u.png"); - icon.addFile(":/res/ProgramManager/EditProgram/FontItalics_s.png", QSize(), QIcon::Normal, QIcon::On); - fdFontItalic->setIcon(icon); - fdFontItalic->setFlat(true); - fdFontItalic->setCheckable(true); - connect(fdFontItalic, &QPushButton::toggled, fdText, [fdText](bool checked) { - QTextCharFormat fmt; - fmt.setFontItalic(checked); - Tools::mergeFormat(fdText, fmt); - }); - hBox->addWidget(fdFontItalic); - - auto wFontUnderline = new QPushButton; - wFontUnderline->setFixedSize(24, 24); - wFontUnderline->setIconSize(QSize(24, 24)); - icon = QIcon(":/res/ProgramManager/EditProgram/FontUnderline_u.png"); - icon.addFile(":/res/ProgramManager/EditProgram/FontUnderline_s.png", QSize(), QIcon::Normal, QIcon::On); - wFontUnderline->setIcon(icon); - wFontUnderline->setFlat(true); - wFontUnderline->setCheckable(true); - connect(wFontUnderline, &QPushButton::toggled, fdText, [fdText](bool checked) { - QTextCharFormat fmt; - fmt.setFontUnderline(checked); - Tools::mergeFormat(fdText, fmt); - }); - hBox->addWidget(wFontUnderline); - - hBox->addStretch(); - - auto fdTextColor = new LoColorSelector(tr("Font Color"), Qt::white); - fdTextColor->setFixedHeight(24); - connect(fdTextColor, &LoColorSelector::sColorChanged, fdText, [fdText](const QColor &color) { - if(! color.isValid()) return; - QTextCharFormat fmt; - fmt.setForeground(color); - Tools::mergeFormat(fdText, fmt); - }); - hBox->addWidget(fdTextColor); - - auto fdBackColor = new LoColorSelector(tr("Back Color"), m_attr.cBackground); - fdBackColor->setFixedHeight(24); - connect(fdBackColor, &LoColorSelector::sColorChanged, this, [this](const QColor &color) { - if(! color.isValid()) return; - m_attr.cBackground = color; - update(); - RefreshBigPixmap(); - }); - hBox->addWidget(fdBackColor); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout; - hBox->setSpacing(3); - - auto wTextAlignVT = new QPushButton; - wTextAlignVT->setFixedSize(QSize(24, 24)); - wTextAlignVT->setIconSize(QSize(24, 24)); - QIcon icon6(":/res/ProgramManager/EditProgram/DocAlignVT_u.png"); - icon6.addFile(":/res/ProgramManager/EditProgram/DocAlignVT_s.png", QSize(), QIcon::Normal, QIcon::On); - wTextAlignVT->setIcon(icon6); - wTextAlignVT->setFlat(true); - wTextAlignVT->setCheckable(true); - wTextAlignVT->setChecked(true); - hBox->addWidget(wTextAlignVT); - - auto wTextAlignVC = new QPushButton(); - wTextAlignVC->setFixedSize(QSize(24, 24)); - wTextAlignVC->setIconSize(QSize(24, 24)); - QIcon icon7(":/res/ProgramManager/EditProgram/DocAlignVC_u.png"); - icon7.addFile(":/res/ProgramManager/EditProgram/DocAlignVC_s.png", QSize(), QIcon::Normal, QIcon::On); - wTextAlignVC->setIcon(icon7); - wTextAlignVC->setFlat(true); - wTextAlignVC->setCheckable(true); - hBox->addWidget(wTextAlignVC); - - auto wTextAlignVB = new QPushButton(); - wTextAlignVB->setFixedSize(QSize(24, 24)); - wTextAlignVB->setIconSize(QSize(24, 24)); - QIcon icon8(":/res/ProgramManager/EditProgram/DocAlignVB_u.png"); - icon8.addFile(":/res/ProgramManager/EditProgram/DocAlignVB_s.png", QSize(), QIcon::Normal, QIcon::On); - wTextAlignVB->setIcon(icon8); - wTextAlignVB->setFlat(true); - wTextAlignVB->setCheckable(true); - hBox->addWidget(wTextAlignVB); - - hBox->addStretch(); - - hBox->addWidget(new QLabel(tr("Kerning"))); - - auto fdLetterSpacing = new QSpinBox(); - fdLetterSpacing->setMaximum(999); - fdLetterSpacing->setValue(m_attr.letterSpacing); - connect(fdLetterSpacing, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { - m_attr.letterSpacing = value; - update(); - RefreshBigPixmap(); - }); - hBox->addWidget(fdLetterSpacing); - - hBox->addWidget(new QLabel(tr("Line Spacing"))); - - auto fdLineSpacing = new QSpinBox(); - fdLineSpacing->setMaximum(999); - fdLineSpacing->setValue(m_attr.lineSpacing); - connect(fdLineSpacing, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { - m_attr.lineSpacing = value; - update(); - RefreshBigPixmap(); - }); - hBox->addWidget(fdLineSpacing); - - vBox->addLayout(hBox); - - auto wTextAlignH = new QButtonGroup(wgtAttr); - wTextAlignH->addButton(wTextAlignHL, Qt::AlignLeft); - wTextAlignH->addButton(wTextAlignHC, Qt::AlignHCenter); - wTextAlignH->addButton(wTextAlignHR, Qt::AlignRight); - connect(wTextAlignH, &QButtonGroup::idClicked, this, [this](int value) { - int res = m_attr.opt.alignment(); - res &= ~Qt::AlignHorizontal_Mask; - res |= value; - m_attr.opt.setAlignment(static_cast(res)); - update(); - RefreshBigPixmap(); - }); - - auto wTextAlignV = new QButtonGroup(wgtAttr); - wTextAlignV->addButton(wTextAlignVT, Qt::AlignTop); - wTextAlignV->addButton(wTextAlignVC, Qt::AlignVCenter); - wTextAlignV->addButton(wTextAlignVB, Qt::AlignBottom); - connect(wTextAlignV, &QButtonGroup::idClicked, this, [this](int value) { - int res = m_attr.opt.alignment(); - res &= ~Qt::AlignVertical_Mask; - res |= value; - m_attr.opt.setAlignment(static_cast(res)); - update(); - RefreshBigPixmap(); - }); - - auto align = m_attr.opt.alignment(); - auto h_align = align & Qt::AlignHorizontal_Mask; - if(h_align==Qt::AlignLeft) wTextAlignHL->setChecked(true); - if(h_align==Qt::AlignHCenter) wTextAlignHC->setChecked(true); - if(h_align==Qt::AlignRight) wTextAlignHR->setChecked(true); - auto v_align = align & Qt::AlignVertical_Mask; - if(v_align==Qt::AlignTop) wTextAlignVT->setChecked(true); - if(v_align==Qt::AlignVCenter) wTextAlignVC->setChecked(true); - if(v_align==Qt::AlignBottom) wTextAlignVB->setChecked(true); - - fdText->setMinimumHeight(160); - auto font = fdText->font(); - font.setPixelSize(16); - fdText->setFont(font); - auto pal = fdText->palette(); - pal.setColor(QPalette::Base, Qt::black); - pal.setColor(QPalette::Text, Qt::white); - fdText->setPalette(pal); - fdText->setFrameShape(QFrame::NoFrame); - fdText->setAcceptRichText(false); - connect(fdText, &QTextEdit::textChanged, this, [this, fdText] { - QString plain = fdText->toPlainText(); - if(plain.isEmpty()) { - fdText->selectAll(); - QTextCharFormat fmt; - fmt.setForeground(Qt::white); - Tools::mergeFormat(fdText, fmt); - } - m_attr.text = fdText->toHtml(); - update(); - RefreshBigPixmap(); - }); - vBox->addWidget(fdText); - - hBox = new QHBoxLayout; - hBox->addStretch(); - hBox->addWidget(new QLabel(tr("PageCount:"))); - - auto fdPageCnt = new QLabel(QString::number(m_attr.iPageCount)); - hBox->addWidget(fdPageCnt); - - hBox->addSpacing(20); - hBox->addWidget(new QLabel(tr("page"))); - - auto fdPageIdx = new QSpinBox(); - fdPageIdx->setRange(1, m_attr.iPageCount); - connect(fdPageIdx, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, &EText::OnPageIndexPreview); - hBox->addWidget(fdPageIdx); - hBox->addStretch(); - - auto btnImport = new QPushButton(tr("Import txt File")); - btnImport->setProperty("ssType", "progManageTool"); - connect(btnImport, &QPushButton::clicked, fdText, [fdText] { - auto filePath = QFileDialog::getOpenFileName(gMainWin, tr("Select File"), gFileHome, "Txt(*.txt)"); - if(filePath.isEmpty()) return; - QFile file(filePath); - if(! file.open(QFile::ReadOnly)) { - QMessageBox::critical(gMainWin, tr("Fail"), tr("File Open Fail")); - return; - } - auto data = file.readAll(); - file.close(); - QTextCodec::ConverterState state; - QString text = QTextCodec::codecForName("UTF-8")->toUnicode(data.constData(), data.size(), &state); - if(state.invalidChars > 0) text = QString::fromLocal8Bit(data); - fdText->setText(text); - }); - hBox->addWidget(btnImport); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout; - hBox->addWidget(new QLabel(tr("Play Properties"))); - - line = new QFrame(); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - hBox->addWidget(line, 1); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout; - hBox->addStretch(); - - auto fdFlip = new QRadioButton(tr("Flip")); - hBox->addWidget(fdFlip); - hBox->addStretch(); - - auto fdScroll = new QRadioButton(tr("Scroll")); - fdScroll->setChecked(true); - hBox->addWidget(fdScroll); - hBox->addStretch(); - - auto fdStatic = new QRadioButton(tr("Static")); - hBox->addWidget(fdStatic); - hBox->addStretch(); - - vBox->addLayout(hBox); - - auto wPlayStyle = new QButtonGroup(wgtAttr); - wPlayStyle->addButton(fdFlip, EText::Flip); - wPlayStyle->addButton(fdScroll, EText::Scroll); - wPlayStyle->addButton(fdStatic, EText::Static); - if(m_attr.playStyle==EText::Flip) fdFlip->setChecked(true); - else if(m_attr.playStyle==EText::Scroll) fdScroll->setChecked(true); - else if(m_attr.playStyle==EText::Static) fdStatic->setChecked(true); - - auto wgtAttrFlip = new QWidget(); - { - auto vBox = new QVBoxLayout(wgtAttrFlip); - vBox->setContentsMargins(2, 0, 2, 0); - vBox->setSpacing(3); - - hBox = new QHBoxLayout; - - auto label = new QLabel(tr("Play Duration")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto fdDur = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.turning.playDuration*1000)); - fdDur->setReadOnly(true); - fdDur->setButtonSymbols(QAbstractSpinBox::NoButtons); - fdDur->setDisplayFormat("H:mm:ss"); - fdDur->setStyleSheet("QTimeEdit{background-color:#ddd;}"); - connect(fdDur, &QTimeEdit::timeChanged, this, [this](const QTime &time) { - m_attr.turning.playDuration = time.msecsSinceStartOfDay()/1000; - }); - hBox->addWidget(fdDur); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - label = new QLabel(tr("Duration/Page")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto fdPageDur = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.turning.pageDuration*1000)); - fdPageDur->setDisplayFormat("H:mm:ss"); - fdPageDur->setCurrentSection(QTimeEdit::SecondSection); - hBox->addWidget(fdPageDur); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - label = new QLabel(tr("Entrance Effect")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto fdEff = new QComboBox(); - fdEff->addItem(tr("no"), "no"); - fdEff->addItem(tr("random"), "random"); - fdEff->addItem(tr("right to left"), "right to left"); - fdEff->addItem(tr("bottom to top"), "bottom to top"); - fdEff->addItem(tr("left to right"), "left to right"); - fdEff->addItem(tr("top to bottom"), "top to bottom"); - int idx = fdEff->findData(m_attr.turning.effect); - if(idx!=-1) fdEff->setCurrentIndex(idx); - connect(fdEff, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this, fdEff] { - m_attr.turning.effect = fdEff->currentData().toString(); - update(); - }); - hBox->addWidget(fdEff); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - label = new QLabel(tr("Effect time")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto wEffectSpeed = new QSpinBox(); - wEffectSpeed->setValue(m_attr.turning.effectDuration); - hBox->addWidget(wEffectSpeed); - hBox->addWidget(new QLabel(tr("s"))); - hBox->addStretch(); - - vBox->addLayout(hBox); - vBox->addStretch(); - - connect(fdPageDur, &QTimeEdit::timeChanged, this, [this, wEffectSpeed, fdPageDur, fdDur](const QTime &time) { - int effDur = wEffectSpeed->value(); - int pageDur = time.msecsSinceStartOfDay()/1000; - if(pageDur < effDur) { - QMessageBox::warning(gMainWin, tr("Tip Info"), tr("Effect time cannot be longer than duration time")); - pageDur = effDur; - fdPageDur->setTime(QTime::fromMSecsSinceStartOfDay(pageDur*1000)); - fdPageDur->setFocus(); - } - m_attr.turning.pageDuration = pageDur; - m_attr.turning.playDuration = pageDur * m_attr.iPageCount; - fdDur->setTime(QTime::fromMSecsSinceStartOfDay(m_attr.turning.playDuration*1000)); - }); - connect(wEffectSpeed, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this, wEffectSpeed, fdPageDur](int value) { - int pageDur = fdPageDur->time().msecsSinceStartOfDay()/1000; - if(value > pageDur) { - QMessageBox::warning(gMainWin, tr("Tip Info"), tr("Effect time cannot be longer than duration time")); - if(pageDur>1) value = pageDur-1; - else value = 0; - wEffectSpeed->setValue(value); - wEffectSpeed->setFocus(); - } - m_attr.turning.effectDuration = value; - }); - connect(this, &EText::sPageCountChanged, wgtAttr, [this, fdPageCnt, fdPageIdx, fdPageDur, fdDur] { - fdPageCnt->setText(QString::number(m_attr.iPageCount)); - fdPageIdx->setRange(1, m_attr.iPageCount); - fdPageIdx->setValue(1); - fdDur->setTime(QTime::fromMSecsSinceStartOfDay(fdPageDur->time().msecsSinceStartOfDay()*m_attr.iPageCount)); - }); - } - auto wgtAttrScroll = new QWidget(); - { - auto vBox = new QVBoxLayout(wgtAttrScroll); - vBox->setContentsMargins(2, 0, 2, 0); - vBox->setSpacing(3); - - auto hBox = new QHBoxLayout(); - - auto label = new QLabel(tr("Play Duration")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto timeEdit = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.rolling.playDuration*1000)); - timeEdit->setDisplayFormat("H:mm:ss"); - timeEdit->setCurrentSectionIndex(2); - connect(timeEdit, &QTimeEdit::timeChanged, this, [this](const QTime &time) { - m_attr.rolling.playDuration = time.msecsSinceStartOfDay()/1000; - }); - hBox->addWidget(timeEdit); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - label = new QLabel(tr("Head-Tail Connected")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto wHeadTailConnected = new QCheckBox(); - wHeadTailConnected->setLayoutDirection(Qt::LeftToRight); - wHeadTailConnected->setStyleSheet("QCheckBox::indicator{width: 16px; height: 16px;}"); - hBox->addWidget(wHeadTailConnected); - - auto lHeadTailSpacing = new QLabel(tr("Head-Tail Spacing")); - hBox->addWidget(lHeadTailSpacing); - - auto wHeadTailSpacing = new QSpinBox(); - wHeadTailSpacing->setMaximum(9999); - wHeadTailSpacing->setValue(m_attr.rolling.headTailSpacing); - connect(wHeadTailSpacing, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { - m_attr.rolling.headTailSpacing = value; - }); - hBox->addWidget(wHeadTailSpacing); - hBox->addStretch(); - - vBox->addLayout(hBox); - - if(m_attr.rolling.headTailConnected) wHeadTailConnected->setChecked(true); - else { - lHeadTailSpacing->setVisible(false); - wHeadTailSpacing->setVisible(false); - } - connect(wHeadTailConnected, &QCheckBox::toggled, this, [this, lHeadTailSpacing, wHeadTailSpacing](bool checked) { - m_attr.rolling.headTailConnected = checked; - lHeadTailSpacing->setVisible(checked); - wHeadTailSpacing->setVisible(checked); - }); - - hBox = new QHBoxLayout(); - - label = new QLabel(tr("Scroll Style")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto wRollingStyle = new QComboBox(); - wRollingStyle->addItem(tr("Right -> Left")); - wRollingStyle->addItem(tr("Bottom -> Top")); - wRollingStyle->addItem(tr("Left -> Right")); - wRollingStyle->addItem(tr("Top -> Bottom")); - wRollingStyle->setCurrentIndex(m_attr.rolling.rollingStyle); - connect(wRollingStyle, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [this](int index) { - m_attr.rolling.rollingStyle = index; - update(); - RefreshBigPixmap(); - }); - hBox->addWidget(wRollingStyle); - hBox->addStretch(); - - vBox->addLayout(hBox); - - hBox = new QHBoxLayout(); - - label = new QLabel(tr("Scroll Speed")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto wRollingSpeed = new QSpinBox(); - wRollingSpeed->setMaximum(9999); - wRollingSpeed->setValue(m_attr.rolling.rollingSpeed); - connect(wRollingSpeed, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this](int value) { - m_attr.rolling.rollingSpeed = value; - }); - hBox->addWidget(wRollingSpeed); - hBox->addStretch(); - - vBox->addLayout(hBox); - vBox->addStretch(); - } - auto wgtAttrStatic = new QWidget(); - { - auto vBox = new QVBoxLayout(wgtAttrStatic); - vBox->setContentsMargins(2, 0, 2, 0); - vBox->setSpacing(3); - - hBox = new QHBoxLayout(); - auto label = new QLabel(tr("Play Duration")); - label->setMinimumWidth(100); - hBox->addWidget(label); - - auto timeEdit = new QTimeEdit(QTime::fromMSecsSinceStartOfDay(m_attr.playDuration*1000)); - timeEdit->setDisplayFormat("H:mm:ss"); - timeEdit->setCurrentSectionIndex(2); - connect(timeEdit, &QTimeEdit::timeChanged, this, [this](const QTime &time) { - m_attr.playDuration = time.msecsSinceStartOfDay() / 1000; - }); - hBox->addWidget(timeEdit); - hBox->addStretch(); - - vBox->addLayout(hBox); - vBox->addStretch(); - } - auto stackBox = new QStackedLayout; - vBox->addLayout(stackBox); - stackBox->addWidget(wgtAttrFlip); - stackBox->addWidget(wgtAttrScroll); - stackBox->addWidget(wgtAttrStatic); - stackBox->setCurrentIndex(m_attr.playStyle); - connect(wPlayStyle, &QButtonGroup::idClicked, this, [this, stackBox](int value) { - m_attr.playStyle = value; - update(); - RefreshBigPixmap(); - stackBox->setCurrentIndex(value); - }); - return wgtAttr; -} - -bool EText::save(const QString &pRoot) { - m_pRootPath=pRoot; - QString strDir = QString("%1%2%3%4%5").arg(zValue()).arg((int)x()).arg((int)y()).arg((int)mWidth).arg((int)mHeight); - //保存图片元素到相应目录 - QDir dirTemp(m_pRootPath+MACRO_FENGEFU+strDir); - if(dirTemp.exists()) - { - if(dirTemp.removeRecursively()) - { - int iReTryCount=0; - QDir dRoot(m_pRootPath); - while(!dRoot.mkdir(strDir)) - { - QThread::sleep(1); - iReTryCount++; - if(iReTryCount>10) - break; - } - } - } - else { - int iReTryCount=0; - QDir dRoot(m_pRootPath); - while(!dRoot.mkdir(strDir)) - { - QThread::sleep(1); - iReTryCount++; - if(iReTryCount>10) - break; - } - } - - - -// QDir dRoot(m_pRootPath); -// if(dRoot.exists(strDir)) { -// QDir dirTemp(m_pRootPath+MACRO_FENGEFU+strDir); -// if(dirTemp.exists()) -// { - -// } -// dRoot.removeRecursively() -// if(dRoot.remove(strDir)) -// { -// removeRecursively -// } -// } -// int iReTryCount=0; -// while(!dRoot.mkdir(strDir)) -// { -// QThread::sleep(1); -// iReTryCount++; -// if(iReTryCount>10) -// break; - -// } - QString strPath=m_pRootPath+ MACRO_FENGEFU +strDir; - if(m_attr.playStyle==EText::Flip)//生成多张图 - { - for (int i=0;i(m_attr.opt.alignment()); - oColor["background"] = Tools::color2Int(m_attr.cBackground); - oWidget["lineSpacing"] = m_attr.lineSpacing; - oWidget["wordSpacing"] = m_attr.letterSpacing; - oWidget["cBackground"] = Tools::color2Int(m_attr.cBackground); - - QJsonObject QJOPngObject; - QJsonArray QJArrayPngItems; - QString strDir=QString("%1%2%3%4%5").arg(zValue()).arg((int)x()).arg((int)y()).arg((int)mWidth).arg((int)mHeight); - if(m_attr.playStyle==EText::Flip)//生成多张图 - { - - for (int i=0;isave(); - painter->drawPixmap(innerRect(), mRenderImg, QRectF()); - painter->restore(); - EBase::paint(painter, option, widget); -} - -void EText::CreateBigOnePixBmp(){ - QPainter painter; - QTextDocument doc; - doc.setDefaultTextOption(m_attr.opt); - doc.setDocumentMargin(0); - doc.setTextWidth(rect().width()); - - QFont font; - if(gTextAntialiasing) font.setHintingPreference(QFont::PreferNoHinting); - else { - font.setLetterSpacing(QFont::AbsoluteSpacing, m_attr.letterSpacing); - font.setStyleStrategy(QFont::NoAntialias); - } - font.setPixelSize(16); - doc.setDefaultFont(font); - m_lineH = m_attr.lineSpacing + QFontMetrics(doc.defaultFont()).lineSpacing(); - doc.setHtml("
"+m_attr.text+"
"); - - int iwidth=this->rect().toRect().width(); - QRectF OutPutBmpRect = QRectF(0, 0, iwidth, doc.size().height());//实际绘制文本的矩形大小 - int iheight=OutPutBmpRect.toRect().height(); - - QPixmap map(iwidth, iheight); - - map.fill(m_attr.cBackground); - painter.begin(&map); - doc.drawContents(&painter, OutPutBmpRect); - painter.end(); - m_bigOnePixBmp=map.copy(OutPutBmpRect.toRect()); -} - -void EText::RefreshBigPixmap(){ - if(m_attr.playStyle==EText::Flip){//生成多张图 - CreateBigOnePixBmp(); - if(m_bigOnePixBmp.height()>6) { - QImage tempQImage=m_bigOnePixBmp.toImage(); - m_ImageBkColor=tempQImage.pixelColor(0,0); - m_list.clear(); - GetPagesPosList(); - } - if(m_list.count()>0) OnPageIndexPreview(1); - m_attr.iPageCount=m_list.count(); - emit sPageCountChanged(m_list.count()); - } - else if(m_attr.playStyle==EText::Scroll)//生成一张大图 - { - if(m_attr.rolling.rollingStyle==0||m_attr.rolling.rollingStyle==2)//上下滚动,生成一张纵向长图 - { - MakeBigMoveLeftOrRightOnePngToDir(); - } - else if(m_attr.rolling.rollingStyle==1||m_attr.rolling.rollingStyle==3)//上下滚动,生成一张纵向长图 - { - MakeBigMoveUpOrDownOnePngToDir(); - } - m_attr.iPageCount=1; - emit sPageCountChanged(1); - } - else if(m_attr.playStyle==EText::Static)//生成一张图 - { - CreateBigOnePixBmp(); - if(m_bigOnePixBmp.height()>6){ - QImage tempQImage=m_bigOnePixBmp.toImage(); - m_ImageBkColor=tempQImage.pixelColor(0,0); - m_list.clear(); - GetPagesPosList(); - } - m_attr.iPageCount=1; - OnPageIndexPreview(1); - emit sPageCountChanged(1); - } -} - -int EText::GetPagesPosList(){ - int iIndex=0; - for (;;) { - if(ClearPixmapTopAndBottomBlack()<=0) return m_list.count(); - txtBmpPage temp=GetFirstPagePixmap(); - if(temp.index==-1) {//表示到最后,bigpixmap已经没有内容了 - temp.index=iIndex; - iIndex++; - m_list.append(temp); - return m_list.count(); - } else { - temp.index=iIndex; - m_list.append(temp); - iIndex++; - if(iIndex > 100) break; - } - } - return m_list.count(); -} -//去除上下的黑边,返回去掉黑边图像的高度 -int EText::ClearPixmapTopAndBottomBlack() -{ - QImage tempQImage=m_bigOnePixBmp.toImage(); - int iFirst=0; - int iEnd=m_bigOnePixBmp.height(); - bool bFirst=false; - bool bEnd=false; - for(int y=0;y=0;m--) - { - for (int n=0;n1) - { - int iCopyHeight=iEnd-iFirst+1; - m_bigOnePixBmp=m_bigOnePixBmp.copy(0,iFirst,m_bigOnePixBmp.width(),iCopyHeight+1); - return iCopyHeight; - } - else { - //空的没有文字的部分 - return -1; - } -} - -txtBmpPage EText::GetFirstPagePixmap() -{ - QImage tempQImage=m_bigOnePixBmp.toImage(); -// tempQImage.save("f://a.png","PNG"); - txtBmpPage tempPageClass; - int iWidth=m_bigOnePixBmp.width(); - int iHeight=m_bigOnePixBmp.height(); - int iRectHeight=rect().height(); - if(iRectHeight>iHeight) iRectHeight=iHeight; - int iType=0; - //判断底边是不是黑 - for (int x=0;x=0;y--) - { - bool bFinished=false; - for (int x=0;x=0;y--) - { - bool bFinished=false; - for (int x=0;xiRectHeight) - m_bigOnePixBmp=m_bigOnePixBmp.copy(0,iRectHeight,iWidth,iHeight-iRectHeight); - else - { - tempPageClass.index=-1; - return tempPageClass; - } - } - else if(iSubType==1) - { - for (int y=iSubEnd;y>=0;y--) - { - bool bFinished=false; - for (int x=0;x=0) { - if(m_list.count()>0 && iPageIndexdiv{color:#fff; line-height:"+QString::number(m_attr.lineSpacing + lineSpacing)+"px; white-space:pre-wrap;}
"+m_attr.text+"
"); - - int iwidth=this->rect().toRect().width(); - QRectF OutPutBmpRect = QRectF(0, 0, iwidth, doc.size().height());//实际绘制文本的矩形大小 - int iheight=OutPutBmpRect.toRect().height(); - - QPixmap map(iwidth,iheight); - map.fill(m_attr.cBackground); - painter.begin(&map); - doc.drawContents(&painter, OutPutBmpRect); - painter.end(); - mRenderImg = QPixmap(rect().size().toSize()); - mRenderImg.fill(m_attr.cBackground); - painter.begin(&mRenderImg); - if(rect().height()>map.height()) { - QBrush bshBackground = Tools::getBrush(m_attr.cBackground); - if(bshBackground != Qt::NoBrush) painter.fillRect(0,map.height(),rect().width(),rect().height()-map.height(), bshBackground); - painter.drawPixmap(map.rect(), map,map.rect()); - } else { - QRectF rectSource(0,0,rect().width(),rect().height()); - painter.drawPixmap(rect(),map,rectSource); - } - painter.end(); - update(); -} -void EText::MakeBigMoveLeftOrRightOnePngToDir() { - QPainter painter; - QTextDocument doc; - //m_attr.opt.setAlignment(Qt::AlignJustify); - m_attr.opt.setAlignment(Qt::AlignLeft); - doc.setDefaultTextOption(m_attr.opt); - doc.setDocumentMargin(0); - // doc.setTextWidth(rect().width()); - doc.setTextWidth(3800); - - QFont font; - if(gTextAntialiasing) font.setHintingPreference(QFont::PreferNoHinting); - else { - font.setLetterSpacing(QFont::AbsoluteSpacing, m_attr.letterSpacing); - font.setStyleStrategy(QFont::NoAntialias); - } - font.setPixelSize(16); - doc.setDefaultFont(font); - - const int lineSpacing = QFontMetrics(doc.defaultFont()).lineSpacing(); - int lineH = m_attr.lineSpacing + lineSpacing; - doc.setHtml("
"+m_attr.text+"
"); - - //int iwidth=this->rect().toRect().width(); - int iwidth=3800; - QRectF OutPutBmpRect = QRectF(0, 0, iwidth, doc.size().height());//实际绘制文本的矩形大小 - int iheight=OutPutBmpRect.toRect().height(); - - QPixmap map(iwidth,iheight); - map.fill(m_attr.cBackground); - painter.begin(&map); - doc.drawContents(&painter, OutPutBmpRect); - painter.end(); - QPixmap bigOnePixmap=map.copy(OutPutBmpRect.toRect()); - //获取 - m_linelist.clear(); - //获取到长图的每页添加到list,并返回最大高度 - GetLinePng(bigOnePixmap); - //把list中的图片拼接起来 - if(m_linelist.count()>0) { - QBrush bshBackground = Tools::getBrush(m_attr.cBackground); - //把长图的开头拷贝到输出pixmap预览 - mRenderImg = QPixmap(rect().size().toSize()); - mRenderImg.fill(m_attr.cBackground); - painter.begin(&mRenderImg); - - txtBmpLine tmpLine=m_linelist.at(0); - int itempHeight=tmpLine.bitmap.height();//tmpLine.iEnd-tmpLine.iStart; - - int iTopOffset=(rect().height()-itempHeight)/2; - painter.fillRect(0,0,rect().width(),iTopOffset, bshBackground); - painter.fillRect(0,iTopOffset+itempHeight,rect().width(),rect().height()-iTopOffset-itempHeight, bshBackground); - - QRectF rectDest(0,iTopOffset,rect().width(),itempHeight); - QRectF rectSource(0,0,rect().width(),itempHeight); - painter.drawPixmap(rectDest,tmpLine.bitmap,rectSource); - painter.end(); - } - update(); -} - -int EText::GetLinePng(QPixmap bigOnePixmap) -{ - QImage tempQImage=bigOnePixmap.toImage(); - m_ImageBkColor=tempQImage.pixelColor(0,0); -// int iFirst=0; -// int iEnd=bigOnePixmap.height(); - bool bLineFlag=false; -// bool bEnd=false; - int iIndex=0; - txtBmpLine tmp; - int iMaxHeight=0; - for(int y=0;y2) - { - if(ipicHeight>iMaxHeight) - iMaxHeight=ipicHeight; - tmp.bitmap=bigOnePixmap.copy(0,tmp.iStart,bigOnePixmap.width(),tmp.iEnd-tmp.iStart); - m_linelist.append(tmp); - bLineFlag=false; - } - } - } - - else //文字行向下判断到了一个背景色的行,扫描了一行也没有发现文字颜色,都是背景色 - { - - tmp.iEnd=y; - int ipicHeight=tmp.iEnd-tmp.iStart; - if(ipicHeight>2) - { - if(ipicHeight>iMaxHeight) - iMaxHeight=ipicHeight; - tmp.bitmap=bigOnePixmap.copy(0,tmp.iStart,bigOnePixmap.width(),tmp.iEnd-tmp.iStart); - m_linelist.append(tmp); - bLineFlag=false; - } - - } - } - } - } - - return iMaxHeight; -} -//生成左右滚动图片素材 -void EText::MakeBigMoveLeftOrRightOnePngToDir(QString strPngPathAndName) { - QPainter painter; - GetPagesPosList(); - QTextDocument doc; - m_attr.opt.setAlignment(Qt::AlignLeft); - doc.setDefaultTextOption(m_attr.opt); - doc.setDocumentMargin(0); - doc.setTextWidth(3800); - QFont font; - if(gTextAntialiasing) font.setHintingPreference(QFont::PreferNoHinting); - else { - font.setLetterSpacing(QFont::AbsoluteSpacing, m_attr.letterSpacing); - font.setStyleStrategy(QFont::NoAntialias); - } - font.setPixelSize(16); - doc.setDefaultFont(font); - - const int lineSpacing = QFontMetrics(doc.defaultFont()).lineSpacing(); - int lineH = m_attr.lineSpacing + lineSpacing; - doc.setHtml("
"+m_attr.text+"
"); - - //int iwidth=this->rect().toRect().width()*iAllPagesTemp; - int iwidth=3800; - QRectF OutPutBmpRect = QRectF(0, 0, iwidth, doc.size().height());//实际绘制文本的矩形大小 - int iheight=OutPutBmpRect.toRect().height(); - - QPixmap map(iwidth,iheight); - map.fill(m_attr.cBackground); - painter.begin(&map); - doc.drawContents(&painter,OutPutBmpRect); - painter.end(); - QPixmap bigOnePixmap=map.copy(OutPutBmpRect.toRect()); - //获取 - bigOnePixmap.save("f:/a.png","PNG"); - m_linelist.clear(); - //获取到长图的每页添加到list,并返回最大高度 - GetLinePng(bigOnePixmap); - //把list中的图片拼接起来 - int iMaxHeight=rect().height(); - if(m_linelist.count()>0) - { - QBrush bshBackground(m_attr.cBackground);// = LoAppTools::getInstance()->getBrush(m_attr.cBackground); - QList listPageWidth; - int iPicLongSize=0; - for (int j=0;j4096-rect().width()) - { - listPageWidth.append(iPicLongSize); -// iPicLongSize=0; - } - } -// if(iPicLongSize!=0) -// { -// listPageWidth.append(iPicLongSize); -// } - - int iIOffset=0; - for (int m=0;mbegin(&bigOneLongPixmap); - iPicLongSize=0; - for (int i=iIOffset;ifillRect((i-iIOffset)*iwidth,0,rect().width(),iTopOffset, bshBackground); - pPainterTemp->fillRect((i-iIOffset)*iwidth,iTopOffset+itempHeight,rect().width(),iMaxHeight-iTopOffset-itempHeight, bshBackground); - } - - QRectF rectDest((i-iIOffset)*iwidth,(iMaxHeight-itempHeight)/2,iwidth,itempHeight); - pPainterTemp->drawPixmap(rectDest,tmpLine.bitmap,tmpLine.bitmap.rect()); - if(iPicLongSize==itempWidth) - { - - pPainterTemp->end(); - delete pPainterTemp; - if(m==listPageWidth.count()-1) - { - //如果启用了首位相接,根据间隔值处理吧文字后边的黑边流出来。 - if(m_attr.rolling.headTailConnected) - { - int itempSpace=GetWordSpaceRealInBmp(bigOneLongPixmap); - ProcessLastStartEndLianJie(bigOneLongPixmap,strPngPathAndName+QString::number(m)+".png",itempSpace+m_attr.rolling.headTailSpacing); - - } - else { - int itempSpace=GetWordSpaceRealInBmp(bigOneLongPixmap); - ProcessLastStartEndLianJie(bigOneLongPixmap,strPngPathAndName+QString::number(m)+".png",itempSpace); - //bigOneLongPixmap.save(strPngPathAndName+QString::number(m)+".png","PNG"); - - } - } - else { - int itempSpace=GetWordSpaceRealInBmp(bigOneLongPixmap); - ProcessLastStartEndLianJie(bigOneLongPixmap,strPngPathAndName+QString::number(m)+".png",itempSpace); - //bigOneLongPixmap.save(strPngPathAndName+QString::number(m)+".png","PNG"); - - } - iIOffset=i+1; - break; - } - else { - pPainterTemp->end(); - delete pPainterTemp; - - } - } - } - } - -} -void EText::ProcessLastStartEndLianJie(QPixmap bmp,QString strPngFilePathName,int iLastRightNoWordWidth) { - QImage tempQImage=bmp.toImage(); - int iWidth = bmp.width(); - for (int x=iWidth-1;x>0;x--) { - for(int y=0;ybegin(&returnBmp); - pPainterTemp->drawPixmap(bmp.rect(),bmp,bmp.rect()); - pPainterTemp->end(); - if(m_attr.rolling.headTailConnected) - { - if(returnBmp.width()>=rect().width())//如果图片的宽大于区域的宽 - { - returnBmp.save(strPngFilePathName,"PNG"); - } - else { - int iBeiShu=rect().width()/returnBmp.width(); - int iTempWidth=returnBmp.width(); - QPixmap returnNewBmp(iTempWidth*(iBeiShu+1),bmp.height()); - returnNewBmp.fill(m_ImageBkColor); - QPainter painter; - painter.begin(&returnNewBmp); - for (int ii=0;ii=rect().width())//如果图片的宽大于区域的宽 - { - returnBmp.save(strPngFilePathName,"PNG"); - - } - else { - int iTempWidth=returnBmp.width(); - QPixmap returnNewBmp(rect().width(),bmp.height()); - returnNewBmp.fill(m_ImageBkColor); - QPainter painter; - painter.begin(&returnNewBmp); - QBrush bshBackground = Tools::getBrush(m_attr.cBackground); - - painter.fillRect(returnNewBmp.rect(),bshBackground); - QRect tempRc(0,0,iTempWidth,returnBmp.height()); - painter.drawPixmap(tempRc,returnBmp,returnBmp.rect()); - returnNewBmp.save(strPngFilePathName,"PNG"); - } - - } - - delete pPainterTemp; - return; - } - } - } -} - - -int EText::GetWordSpaceRealInBmp(QPixmap bmp) -{ - QImage tempQImage=bmp.toImage(); -// m_ImageBkColor=tempQImage.pixelColor(0,0); - int iWidth= bmp.width(); - int iLastX = iWidth; - int iCount=0; - for (int x=iWidth-1;x>0;x--) - { - int iAllSameFlag=0; - for(int y=0;ydiv{color:#fff; line-height:"+QString::number(lineH)+"px; white-space:pre-wrap;}
"+m_attr.text+"
"); - int iwidth = innerRect().width(); - QRectF OutPutBmpRect(0, 0, iwidth, doc.size().height());//实际绘制文本的矩形大小 - int iheight = OutPutBmpRect.toRect().height(); - - QPixmap map(iwidth,iheight); - map.fill(m_attr.cBackground); - QPainter painter; - painter.begin(&map); - doc.drawContents(&painter, OutPutBmpRect); - painter.end(); - - QPixmap pRenderPixmap = QPixmap(rect().size().toSize()); - pRenderPixmap.fill(m_attr.cBackground); - painter.begin(&pRenderPixmap); - if(rect().height()>map.height()) { - QBrush bshBackground = Tools::getBrush(m_attr.cBackground); - if(bshBackground != Qt::NoBrush) painter.fillRect(0,map.height(),rect().width(),rect().height()-map.height(), bshBackground); - painter.drawPixmap(map.rect(),map,map.rect()); - pRenderPixmap.save(strPngPathAndName); - } else { - QRectF rectSource(0,0,rect().width(),rect().height()); - painter.drawPixmap(rect(),map,rectSource); - map.copy(OutPutBmpRect.toRect()).save(strPngPathAndName); - } - painter.end(); -} -//生成翻页和静态图片素材 -void EText::MakeMuliPngToDir(int iPageIndex,QString strPngPathAndName){ - iPageIndex=iPageIndex-1; - if(iPageIndex<0) iPageIndex=0; - if(iPageIndex>=0){ - if(m_list.count()>0&&iPageIndex -#include -#include -#include -#include "ebase.h" -#include "QTime" - -//这条语句害死人,加了这条语句文字就不能做到无反锯齿 MYFONT.setHintingPreference(QFont::PreferNoHinting); - -class txtBmpPage{ -public: - int index=0; - QPixmap bitmap; -}; - -class txtBmpLine{ -public: - int index=0; - int iStart=0; - int iEnd=0; - QPixmap bitmap; -}; - -class EText : public EBase { - Q_OBJECT -public: - enum PlayStyle { - Flip = 0, - Scroll, - Static - }; - - enum RollingStyle { - Left2Right = 0, - Right2Left, - Top2Bottom, - Bottom2Top - }; - struct Turning { - int playDuration{10}; - int pageDuration{10}; - QString effect{"no"}; - int effectDuration{3}; - }; - struct Rolling { - int playDuration{10}; - int rollingStyle; - int rollingSpeed; - bool headTailConnected; - int headTailSpacing=10; - }; - struct Data { - QString text; - QTextOption opt; - int lineSpacing = 0; - int letterSpacing = 0; - QColor cBackground; - int iPageCount=1; - int playStyle; - Turning turning; - Rolling rolling; - int playDuration{10}; - }; - - static void setElement(const QJsonObject &json, Data &attr); - - explicit EText(EBase *multiWin = nullptr); - explicit EText(const QJsonObject &json, EBase *multiWin = nullptr); - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; - int type() const override { return EBase::Text; } - QWidget* attrWgt() override; - bool save(const QString &pRoot) override; - QJsonObject attrJson() const override; -signals: - void sPageCountChanged(int); - -public slots: // Widget - void RefreshBigPixmap(); - void OnPageIndexPreview(int iPageIndex); - -private: - int ClearPixmapTopAndBottomBlack(); - void MakeMuliPngToDir(int iPageIndex,QString strPngPathAndName) ; - void MakeBigMoveUpOrDownOnePngToDir() ; - void MakeBigMoveLeftOrRightOnePngToDir() ; - void MakeBigMoveUpOrDownOnePngToDir(QString strPngPathAndName) ; - void MakeBigMoveLeftOrRightOnePngToDir(QString strPngPathAndName) ; - void CreateBigOnePixBmp(); - int GetPagesPosList(); - txtBmpPage GetFirstPagePixmap(); - int GetLinePng(QPixmap bigOnePixmap) ; - void ProcessLastStartEndLianJie(QPixmap bmp,QString strPngFilePathName,int iLastRightNoWordWidth); - int GetWordSpaceRealInBmp(QPixmap bmp); - -private: // Interior - QPointF m_pText; - QRectF m_rClip; - Data m_attr; - int m_lineH; - QPixmap mRenderImg; - QPixmap m_bigOnePixBmp; - - QList m_list; - qreal m_oldWidth=0; - qreal m_oldHeight=0; - QColor m_ImageBkColor; - QString m_pRootPath; - QList m_linelist; - -}; - -#endif // ETEXT_H diff --git a/LedOK/wProgramManager/threadexportprogrampro.cpp b/LedOK/wProgramManager/threadexportprogrampro.cpp deleted file mode 100644 index 443676e..0000000 --- a/LedOK/wProgramManager/threadexportprogrampro.cpp +++ /dev/null @@ -1,161 +0,0 @@ -#include "threadexportprogrampro.h" -#include -#include -#include -#include -#include -#include - -ThreadExportProgramPro::ThreadExportProgramPro() -{ - m_createfile = new QDir(); - -} -ThreadExportProgramPro::~ThreadExportProgramPro() -{ - if(m_createfile) { - m_createfile = Q_NULLPTR; - delete m_createfile; - } - -} -void ThreadExportProgramPro::SetSourceDirAndDestDir(QString strSource,QString strDest) -{ - - m_strSource=strSource; - m_strDest=strDest; - -} -void ThreadExportProgramPro::run(){ - totalCopySize=0; - copyDirectoryFiles(m_strSource,m_strDest,true); -} -bool ThreadExportProgramPro::copyFileToPath(QString sourceDir, QString toDir, bool coverFileIfExist){ - if (sourceDir == toDir){ - return true; - } - if (!QFile::exists(sourceDir)){ - return false; - } - bool exist = m_createfile->exists(toDir); - if (exist){ - if(coverFileIfExist){ - m_createfile->remove(toDir); - } - } - - - if(!QFile::copy(sourceDir, toDir)) { - return false; - } - return true; -} - - -bool ThreadExportProgramPro::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist) -{ - QDir sourceDir(fromDir); - QDir targetDir(toDir); - qDebug() << "copyDirectoryFiles:" << fromDir << toDir; - if(!targetDir.exists()){ - if(!targetDir.mkdir(targetDir.absolutePath())) { - return false; - } - } - QFileInfoList fileInfoList = sourceDir.entryInfoList(); - - - if(m_firstRead) { - int isfileTMP = 0; - qDebug() << "a copyDirectoryFiles:" << fileInfoList.count(); - foreach(QFileInfo fileInfo, fileInfoList){ - if(fileInfo.isFile()) { - isfileTMP++; - } - } - m_total = fileInfoList.count() - 2 - isfileTMP; // 2为.和.. - m_value = 0; - m_firstRead = false; - qDebug() << "a copyDirectoryFiles:" << fileInfoList.count() < m_total) || (m_value == m_total)) { - m_firstRead = true; - emit sigCopyDirOver(); - } - } - foreach(QFileInfo fileInfo, fileInfoList){ - if(fileInfo.fileName() == "." || fileInfo.fileName() == "..") { - continue; - } - if(fileInfo.isDir()){ //< 当为目录时,递归的进行copy - if(!copyDirectoryFiles(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName()), coverFileIfExist)) { - return false; - } - } else{ //当允许覆盖操作时,将旧文件进行删除操作 - if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){ - targetDir.remove(fileInfo.fileName()); - } - /// 进行文件copy - if(!QFile::copy(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName()))){ - return false; - } - else { - totalCopySize+=fileInfo.size(); - emit sigSendExportProgressValue(totalCopySize); - } -// if(!copyFile(fromDir+MACRO_FENGEFU+fileInfo.fileName(),toDir+MACRO_FENGEFU+fileInfo.fileName())){ -// return false; -// } - } - } - return true; -} -bool ThreadExportProgramPro::copyFile(const QString &fromFIleName, const QString &toFileName) -{ - char* byteTemp = new char[4096];//字节数组 - int fileSize = 0; - QFile tofile; - int iCurFileSize=0; - tofile.setFileName(toFileName); - QDataStream out(&tofile); - out.setVersion(QDataStream::Qt_4_8); - - QFile fromfile; - fromfile.setFileName(fromFIleName); - if(!fromfile.open(QIODevice::ReadOnly)){ - qDebug() << "open fromfile failed!!!"; - return false; - } - fileSize = fromfile.size(); - QDataStream in(&fromfile); - - in.setVersion(QDataStream::Qt_4_8); - while(!in.atEnd()) - { - int readSize = 0; - //读入字节数组,返回读取的字节数量,如果小于4096,则到了文件尾 - readSize = in.readRawData(byteTemp, 4096); - out.writeRawData(byteTemp, readSize); - totalCopySize += readSize; - iCurFileSize+=readSize; - emit sigSendExportProgressValue(totalCopySize); - } - if(iCurFileSize == fileSize){ - tofile.setPermissions(QFile::ExeUser); - fromfile.close(); - tofile.close(); - return true; - } - else - return false; -} diff --git a/LedOK/wProgramManager/threadexportprogrampro.h b/LedOK/wProgramManager/threadexportprogrampro.h deleted file mode 100644 index 71b0eb4..0000000 --- a/LedOK/wProgramManager/threadexportprogrampro.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef THREADEXPORTPROGRAMPRO_H -#define THREADEXPORTPROGRAMPRO_H -#include -#include -class ThreadExportProgramPro:public QThread -{ - Q_OBJECT -public: - ThreadExportProgramPro(); - ~ThreadExportProgramPro(); - void run(); - void SetSourceDirAndDestDir(QString strSource,QString strDest); -private: - bool copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist); - bool copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist); - bool copyFile(const QString &fromFIleName, const QString &toFileName); -signals: - void sigSendExportProgressValue(int); -signals: - void sigCopyDirStation(float); - void sigCopyDirOver(); -private: - QDir * m_createfile = Q_NULLPTR; - float m_total = 0; - float m_value = 0; - bool m_firstRead = true; - QString m_strSource; - QString m_strDest; - int totalCopySize = 0; - -}; -#endif // THREADEXPORTPROGRAMPRO_H diff --git a/LedOK/wProgramManager/wexportprogramitem.cpp b/LedOK/wProgramManager/wexportprogramitem.cpp deleted file mode 100644 index f8102d8..0000000 --- a/LedOK/wProgramManager/wexportprogramitem.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "wexportprogramitem.h" -#include -#include "globaldefine.h" -#include - -wExportProgramItem::wExportProgramItem(QTableWidget *parent,QString strProgramName,int iIndex): - QObject(parent), - QTableWidgetItem(UserType) -{ - /*上面用到的两个枚举中:~Qt::ItemIsEnabled可以保证单击该Item时不会被选中,但是在启用Ctrl + A时,全选操作会导致Item被选中。 - * ~Qt::ItemIsSelectable的使用可以保证全选状态下也不会被选中,但是在单独使用时出现了虚线框,没有真正实现“不存在”的效果。所以必须两个同用。*/ - m_parent=parent; - m_iIndex=iIndex; - setFlags(flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable); - progress= new QProgressBar(parent); - progress->setValue(0); - setData(0,strProgramName); - parent->setCellWidget(iIndex, 1, progress); - //ThreadExportProgramPro *pThread = new ThreadExportProgramPro(strSourceDir,strDestPath); - //connect(pItem) - pThread = new ThreadExportProgramPro(); -// connect(pThread,SIGNAL(sigCopyDirStation(float)),this,SLOT(OnProgressSet(float))); -// connect(pThread,SIGNAL(sigCopyDirOver()),this,SLOT(OnCopyDirOver())); - connect(pThread,SIGNAL(sigSendExportProgressValue(int)),this,SLOT(OnSendExportProgressValue(int))); -} -wExportProgramItem::~wExportProgramItem() -{ - if(pThread!=nullptr) - delete pThread; - m_parent->removeCellWidget(m_iIndex,1); - // delete progress; - -} -extern QWidget *gMainWin; -bool wExportProgramItem::ExportPro(QString strDestPath,QString strSourceDir) -{ - strSourceDir= strSourceDir+MACRO_FENGEFU+text(); - strDestPath=strDestPath+MACRO_FENGEFU+text(); - int iAllSize=dirFileSize(strSourceDir); - progress->setRange(0,iAllSize); - progress->setValue(0); - pThread->SetSourceDirAndDestDir(strSourceDir,strDestPath); - - QDir DirDest(strDestPath); - if(DirDest.exists()) { - auto res = QMessageBox::information(gMainWin, tr("Tip Info"), text()+tr(":solution(s) already exist.are you sure you want to overwrite the existing solution(s)?"), QMessageBox::Ok, QMessageBox::Cancel); - if(res == QMessageBox::Ok) pThread->start(); - else return false; - } - else pThread->start(); - return true; -} -void wExportProgramItem::OnProgressSet(float num) -{ - progress->setValue(num); -} -void wExportProgramItem::OnCopyDirOver() -{ - progress->setValue(100); -} -void wExportProgramItem::OnSendExportProgressValue(int iValue) -{ - progress->setValue(iValue); -} diff --git a/LedOK/wProgramManager/wexportprogramitem.h b/LedOK/wProgramManager/wexportprogramitem.h deleted file mode 100644 index f8a0b93..0000000 --- a/LedOK/wProgramManager/wexportprogramitem.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef WEXPORTPROGRAMITEM_H -#define WEXPORTPROGRAMITEM_H -#include -#include -#include -class wExportProgramItem:public QObject, public QTableWidgetItem -{ - Q_OBJECT -public: - wExportProgramItem(QTableWidget *parent = nullptr,QString strProgramName="",int iIndex=0); - ~wExportProgramItem(); - bool ExportPro(QString strDestPath,QString strSourceDir); -protected slots: - void OnProgressSet(float); - void OnCopyDirOver(); - void OnSendExportProgressValue(int); -private: - QProgressBar *progress =nullptr; - ThreadExportProgramPro *pThread=nullptr; - QTableWidget *m_parent=nullptr; - int m_iIndex=0; -}; - -#endif // WEXPORTPROGRAMITEM_H diff --git a/LedOK/x_uimsgonlyclosebtn.cpp b/LedOK/x_uimsgonlyclosebtn.cpp index b98b246..2f68392 100644 --- a/LedOK/x_uimsgonlyclosebtn.cpp +++ b/LedOK/x_uimsgonlyclosebtn.cpp @@ -1,14 +1,14 @@ -#include "x_uimsgonlyclosebtn.h" -#include "ui_x_uimsgonlyclosebtn.h" - -x_uiMsgOnlyCloseBtn::x_uiMsgOnlyCloseBtn(QWidget *parent) : - QDialog(parent), - ui(new Ui::x_uiMsgOnlyCloseBtn) -{ - ui->setupUi(this); -} - -x_uiMsgOnlyCloseBtn::~x_uiMsgOnlyCloseBtn() -{ - delete ui; -} +#include "x_uimsgonlyclosebtn.h" +#include "ui_x_uimsgonlyclosebtn.h" + +x_uiMsgOnlyCloseBtn::x_uiMsgOnlyCloseBtn(QWidget *parent) : + QDialog(parent), + ui(new Ui::x_uiMsgOnlyCloseBtn) +{ + ui->setupUi(this); +} + +x_uiMsgOnlyCloseBtn::~x_uiMsgOnlyCloseBtn() +{ + delete ui; +} diff --git a/LedOK/x_uimsgonlyclosebtn.h b/LedOK/x_uimsgonlyclosebtn.h index 8102318..2bc1006 100644 --- a/LedOK/x_uimsgonlyclosebtn.h +++ b/LedOK/x_uimsgonlyclosebtn.h @@ -1,22 +1,22 @@ -#ifndef X_UIMSGONLYCLOSEBTN_H -#define X_UIMSGONLYCLOSEBTN_H - -#include - -namespace Ui { -class x_uiMsgOnlyCloseBtn; -} - -class x_uiMsgOnlyCloseBtn : public QDialog -{ - Q_OBJECT - -public: - explicit x_uiMsgOnlyCloseBtn(QWidget *parent = nullptr); - ~x_uiMsgOnlyCloseBtn(); - -private: - Ui::x_uiMsgOnlyCloseBtn *ui; -}; - -#endif // X_UIMSGONLYCLOSEBTN_H +#ifndef X_UIMSGONLYCLOSEBTN_H +#define X_UIMSGONLYCLOSEBTN_H + +#include + +namespace Ui { +class x_uiMsgOnlyCloseBtn; +} + +class x_uiMsgOnlyCloseBtn : public QDialog +{ + Q_OBJECT + +public: + explicit x_uiMsgOnlyCloseBtn(QWidget *parent = nullptr); + ~x_uiMsgOnlyCloseBtn(); + +private: + Ui::x_uiMsgOnlyCloseBtn *ui; +}; + +#endif // X_UIMSGONLYCLOSEBTN_H diff --git a/LedOK/x_uimsgonlyclosebtn.ui b/LedOK/x_uimsgonlyclosebtn.ui index b48d8ab..c6c3d87 100644 --- a/LedOK/x_uimsgonlyclosebtn.ui +++ b/LedOK/x_uimsgonlyclosebtn.ui @@ -1,19 +1,19 @@ - - - x_uiMsgOnlyCloseBtn - - - - 0 - 0 - 400 - 300 - - - - Dialog - - - - - + + + x_uiMsgOnlyCloseBtn + + + + 0 + 0 + 400 + 300 + + + + Dialog + + + + + diff --git a/LedOK/y50 param/1080x1920(30hz)/rk_lcd_parameters b/LedOK/y50 param/1080x1920(30hz)/rk_lcd_parameters new file mode 100644 index 0000000..6d0fb64 --- /dev/null +++ b/LedOK/y50 param/1080x1920(30hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 1080; +hfront-porch = 30; +hsync-len = 10; +hback-porch = 58; +vactive = 1920; +vfront-porch = 30; +vsync-len = 11; +vback-porch = 88; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file diff --git a/LedOK/y50 param/1280x720(60hz)/rk_lcd_parameters b/LedOK/y50 param/1280x720(60hz)/rk_lcd_parameters new file mode 100644 index 0000000..1a70eef --- /dev/null +++ b/LedOK/y50 param/1280x720(60hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 1280; +hfront-porch = 30; +hsync-len = 10; +hback-porch = 99; +vactive = 720; +vfront-porch = 30; +vsync-len = 10; +vback-porch = 90; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file diff --git a/LedOK/y50 param/1920x1080(30hz)/rk_lcd_parameters b/LedOK/y50 param/1920x1080(30hz)/rk_lcd_parameters new file mode 100644 index 0000000..b87f02a --- /dev/null +++ b/LedOK/y50 param/1920x1080(30hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 1920; +hfront-porch = 40; +hsync-len = 20; +hback-porch = 22; +vactive = 1080; +vfront-porch = 100; +vsync-len = 6; +vback-porch = 22; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file diff --git a/LedOK/y50 param/1920x512(60hz)/rk_lcd_parameters b/LedOK/y50 param/1920x512(60hz)/rk_lcd_parameters new file mode 100644 index 0000000..fcad60e --- /dev/null +++ b/LedOK/y50 param/1920x512(60hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 1920; +hfront-porch = 30; +hsync-len = 10; +hback-porch = 99; +vactive = 512; +vfront-porch = 30; +vsync-len = 10; +vback-porch = 34; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file diff --git a/LedOK/y50 param/512x1920(60hz)/rk_lcd_parameters b/LedOK/y50 param/512x1920(60hz)/rk_lcd_parameters new file mode 100644 index 0000000..424e92e --- /dev/null +++ b/LedOK/y50 param/512x1920(60hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 512; +hfront-porch = 30; +hsync-len = 34; +hback-porch = 10; +vactive = 1920; +vfront-porch = 30; +vsync-len = 10; +vback-porch = 99; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file diff --git a/LedOK/y50 param/720x1280(60hz)/rk_lcd_parameters b/LedOK/y50 param/720x1280(60hz)/rk_lcd_parameters new file mode 100644 index 0000000..80a938d --- /dev/null +++ b/LedOK/y50 param/720x1280(60hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 720; +hfront-porch = 30; +hsync-len = 10; +hback-porch = 90; +vactive = 1280; +vfront-porch = 30; +vsync-len = 10; +vback-porch = 99; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file diff --git a/LedOK/y50 param/768x1280(60hz)/rk_lcd_parameters b/LedOK/y50 param/768x1280(60hz)/rk_lcd_parameters new file mode 100644 index 0000000..e927ecc --- /dev/null +++ b/LedOK/y50 param/768x1280(60hz)/rk_lcd_parameters @@ -0,0 +1,35 @@ +##ע +#ע +# 0 - DSI; 1 - EDP; 2 - LVDS; 3 - RGB +panel-type = 3; + +# panel info +unprepare-delay-ms = 20; +enable-delay-ms = 20; +disable-delay-ms = 20; +prepare-delay-ms = 20; +reset-delay-ms = 100; +init-delay-ms = 100; +width-mm = 154; +height-mm = 86; + +# panel timing +clock-frequency = 72400000; +hactive = 768; +hfront-porch = 24; +hsync-len = 8; +hback-porch = 57; +vactive = 1280; +vfront-porch = 31; +vsync-len = 11; +vback-porch = 86; +hsync-active = 0; +vsync-active = 0; +de-active = 0; +pixelclk-active = 0; + +# for dsi panel +#dsi,flags = 0; +#dsi,format = 0; +#dsi,lanes = 4; +#panel-init-sequence = 29 00 06 14 01 08 00 00 00 ff aa 01 02 03 04 05 06 07 ff aa AA bb ff; \ No newline at end of file